]> git.sesse.net Git - vlc/blob - src/misc/block.c
daad650525db4948b2c43ecd1cdfb655f0651883
[vlc] / src / misc / block.c
1 /*****************************************************************************
2  * block.c: Data blocks management functions
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VLC authors and VideoLAN
5  * Copyright (C) 2007-2009 RĂ©mi Denis-Courmont
6  *
7  * Authors: Laurent Aimar <fenrir@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <sys/stat.h>
32 #include <assert.h>
33 #include <errno.h>
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37
38 #include <vlc_common.h>
39 #include <vlc_block.h>
40
41 /**
42  * @section Block handling functions.
43  */
44
45 #ifndef NDEBUG
46 static void BlockNoRelease( block_t *b )
47 {
48     fprintf( stderr, "block %p has no release callback! This is a bug!\n", b );
49     abort();
50 }
51 #endif
52
53 void block_Init( block_t *restrict b, void *buf, size_t size )
54 {
55     /* Fill all fields to their default */
56     b->p_next = NULL;
57     b->p_buffer = buf;
58     b->i_buffer = size;
59     b->p_start = buf;
60     b->i_size = size;
61     b->i_flags = 0;
62     b->i_nb_samples = 0;
63     b->i_pts =
64     b->i_dts = VLC_TS_INVALID;
65     b->i_length = 0;
66 #ifndef NDEBUG
67     b->pf_release = BlockNoRelease;
68 #endif
69 }
70
71 static void BlockRelease( block_t *p_block )
72 {
73     free( p_block );
74 }
75
76 static void BlockMetaCopy( block_t *restrict out, const block_t *in )
77 {
78     out->p_next    = in->p_next;
79     out->i_nb_samples = in->i_nb_samples;
80     out->i_dts     = in->i_dts;
81     out->i_pts     = in->i_pts;
82     out->i_flags   = in->i_flags;
83     out->i_length  = in->i_length;
84 }
85
86 /* Memory alignment (must be a multiple of sizeof(void*) and a power of two) */
87 #define BLOCK_ALIGN        16
88 /* Initial reserved header and footer size (must be multiple of alignment) */
89 #define BLOCK_PADDING      32
90 /* Maximum size of reserved footer before we release with realloc() */
91 #define BLOCK_WASTE_SIZE   2048
92
93 block_t *block_Alloc (size_t size)
94 {
95     /* 2 * BLOCK_PADDING: pre + post padding */
96     const size_t alloc = sizeof (block_t) + BLOCK_ALIGN + (2 * BLOCK_PADDING)
97                        + size;
98     if (unlikely(alloc <= size))
99         return NULL;
100
101     block_t *b = malloc (alloc);
102     if (unlikely(b == NULL))
103         return NULL;
104
105     block_Init (b, b + 1, alloc);
106     static_assert ((BLOCK_PADDING % BLOCK_ALIGN) == 0,
107                    "BLOCK_PADDING must be a multiple of BLOCK_ALIGN");
108     b->p_buffer += BLOCK_PADDING + BLOCK_ALIGN - 1;
109     b->p_buffer = (void *)(((uintptr_t)b->p_buffer) & ~(BLOCK_ALIGN - 1));
110     b->i_buffer = size;
111     b->pf_release = BlockRelease;
112     return b;
113 }
114
115 block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
116 {
117     size_t requested = i_prebody + i_body;
118
119     /* Corner case: empty block requested */
120     if( i_prebody <= 0 && i_body <= (size_t)(-i_prebody) )
121     {
122         block_Release( p_block );
123         return NULL;
124     }
125
126     assert( p_block->p_start <= p_block->p_buffer );
127     assert( p_block->p_start + p_block->i_size
128                                     >= p_block->p_buffer + p_block->i_buffer );
129
130     /* Corner case: the current payload is discarded completely */
131     if( i_prebody <= 0 && p_block->i_buffer <= (size_t)-i_prebody )
132          p_block->i_buffer = 0; /* discard current payload */
133     if( p_block->i_buffer == 0 )
134     {
135         if( requested <= p_block->i_size )
136         {   /* Enough room: recycle buffer */
137             size_t extra = p_block->i_size - requested;
138
139             p_block->p_buffer = p_block->p_start + (extra / 2);
140             p_block->i_buffer = requested;
141             return p_block;
142         }
143         /* Not enough room: allocate a new buffer */
144         block_t *p_rea = block_Alloc( requested );
145         if( p_rea )
146             BlockMetaCopy( p_rea, p_block );
147         block_Release( p_block );
148         return p_rea;
149     }
150
151     /* First, shrink payload */
152
153     /* Pull payload start */
154     if( i_prebody < 0 )
155     {
156         assert( p_block->i_buffer >= (size_t)-i_prebody );
157         p_block->p_buffer -= i_prebody;
158         p_block->i_buffer += i_prebody;
159         i_body += i_prebody;
160         i_prebody = 0;
161     }
162
163     /* Trim payload end */
164     if( p_block->i_buffer > i_body )
165         p_block->i_buffer = i_body;
166
167     uint8_t *p_start = p_block->p_start;
168     uint8_t *p_end = p_start + p_block->i_size;
169
170     /* Second, reallocate the buffer if we lack space. This is done now to
171      * minimize the payload size for memory copy. */
172     assert( i_prebody >= 0 );
173     if( (size_t)(p_block->p_buffer - p_start) < (size_t)i_prebody
174      || (size_t)(p_end - p_block->p_buffer) < i_body )
175     {
176         block_t *p_rea = block_Alloc( requested );
177         if( p_rea )
178         {
179             BlockMetaCopy( p_rea, p_block );
180             p_rea->p_buffer += i_prebody;
181             p_rea->i_buffer -= i_prebody;
182             memcpy( p_rea->p_buffer, p_block->p_buffer, p_block->i_buffer );
183         }
184         block_Release( p_block );
185         if( p_rea == NULL )
186             return NULL;
187         p_block = p_rea;
188     }
189     else
190     /* We have a very large reserved footer now? Release some of it.
191      * XXX it might not preserve the alignment of p_buffer */
192     if( p_end - (p_block->p_buffer + i_body) > BLOCK_WASTE_SIZE )
193     {
194         block_t *p_rea = block_Alloc( requested );
195         if( p_rea )
196         {
197             BlockMetaCopy( p_rea, p_block );
198             p_rea->p_buffer += i_prebody;
199             p_rea->i_buffer -= i_prebody;
200             memcpy( p_rea->p_buffer, p_block->p_buffer, p_block->i_buffer );
201             block_Release( p_block );
202             p_block = p_rea;
203         }
204     }
205
206     /* NOTE: p_start and p_end are corrupted from this point */
207
208     /* Third, expand payload */
209
210     /* Push payload start */
211     if( i_prebody > 0 )
212     {
213         p_block->p_buffer -= i_prebody;
214         p_block->i_buffer += i_prebody;
215         i_body += i_prebody;
216         i_prebody = 0;
217     }
218
219     /* Expand payload to requested size */
220     p_block->i_buffer = i_body;
221
222     return p_block;
223 }
224
225
226 static void block_heap_Release (block_t *block)
227 {
228     free (block->p_start);
229     free (block);
230 }
231
232 /**
233  * Creates a block from a heap allocation.
234  * This is provided by LibVLC so that manually heap-allocated blocks can safely
235  * be deallocated even after the origin plugin has been unloaded from memory.
236  *
237  * When block_Release() is called, VLC will free() the specified pointer.
238  *
239  * @param ptr base address of the heap allocation (will be free()'d)
240  * @param length bytes length of the heap allocation
241  * @return NULL in case of error (ptr free()'d in that case), or a valid
242  * block_t pointer.
243  */
244 block_t *block_heap_Alloc (void *addr, size_t length)
245 {
246     block_t *block = malloc (sizeof (*block));
247     if (block == NULL)
248     {
249         free (addr);
250         return NULL;
251     }
252
253     block_Init (block, addr, length);
254     block->pf_release = block_heap_Release;
255     return block;
256 }
257
258 #ifdef HAVE_MMAP
259 # include <sys/mman.h>
260
261 static void block_mmap_Release (block_t *block)
262 {
263     munmap (block->p_start, block->i_size);
264     free (block);
265 }
266
267 /**
268  * Creates a block from a virtual address memory mapping (mmap).
269  * This is provided by LibVLC so that mmap blocks can safely be deallocated
270  * even after the allocating plugin has been unloaded from memory.
271  *
272  * @param addr base address of the mapping (as returned by mmap)
273  * @param length length (bytes) of the mapping (as passed to mmap)
274  * @return NULL if addr is MAP_FAILED, or an error occurred (in the later
275  * case, munmap(addr, length) is invoked before returning).
276  */
277 block_t *block_mmap_Alloc (void *addr, size_t length)
278 {
279     if (addr == MAP_FAILED)
280         return NULL;
281
282     block_t *block = malloc (sizeof (*block));
283     if (block == NULL)
284     {
285         munmap (addr, length);
286         return NULL;
287     }
288
289     block_Init (block, addr, length);
290     block->pf_release = block_mmap_Release;
291     return block;
292 }
293 #else
294 block_t *block_mmap_Alloc (void *addr, size_t length)
295 {
296     (void)addr; (void)length; return NULL;
297 }
298 #endif
299
300
301 #ifdef WIN32
302 # include <io.h>
303 # ifdef UNDER_CE
304 #  define _get_osfhandle(a) ((long) (a))
305 # endif
306
307 static
308 ssize_t pread (int fd, void *buf, size_t count, off_t offset)
309 {
310     HANDLE handle = (HANDLE)(intptr_t)_get_osfhandle (fd);
311     if (handle == INVALID_HANDLE_VALUE)
312         return -1;
313
314     OVERLAPPED olap; olap.Offset = offset; olap.OffsetHigh = (offset >> 32);
315     DWORD written;
316     /* This braindead API will override the file pointer even if we specify
317      * an explicit read offset... So do not expect this to mix well with
318      * regular read() calls. */
319     if (ReadFile (handle, buf, count, &written, &olap))
320         return written;
321     return -1;
322 }
323 #elif !defined( HAVE_PREAD )
324 static
325 ssize_t pread(int fd, const void * buf, size_t size, off_t offset) {
326     off_t offs0;
327     ssize_t rd;
328     if ((offs0 = lseek(fd, 0, SEEK_CUR)) == (off_t)-1) return -1;
329     if (lseek(fd, offset, SEEK_SET) == (off_t)-1) return -1;
330     rd = read(fd, (void *)buf, size);
331     if (lseek(fd, offs0, SEEK_SET) == (off_t)-1) return -1;
332     return rd;
333 }
334
335 static
336 ssize_t pwrite(int fd, const void * buf, size_t size, off_t offset) {
337     off_t offs0;
338     ssize_t wr;
339     if ((offs0 = lseek(fd, 0, SEEK_CUR)) == (off_t)-1) return -1;
340     if (lseek(fd, offset, SEEK_SET) == (off_t)-1) return -1;
341     wr = write(fd, (void *)buf, size);
342     if (lseek(fd, offs0, SEEK_SET) == (off_t)-1) return -1;
343     return wr;
344 }
345 #endif
346
347 /**
348  * Loads a file into a block of memory. If possible a private file mapping is
349  * created. Otherwise, the file is read normally. On 32-bits platforms, this
350  * function will not work for very large files, due to memory space
351  * constraints. Cancellation point.
352  *
353  * @param fd file descriptor to load from
354  * @return a new block with the file content at p_buffer, and file length at
355  * i_buffer (release it with block_Release()), or NULL upon error (see errno).
356  */
357 block_t *block_File (int fd)
358 {
359     size_t length;
360     struct stat st;
361
362     /* First, get the file size */
363     if (fstat (fd, &st))
364         return NULL;
365
366     /* st_size is meaningful for regular files, shared memory and typed memory.
367      * It's also meaning for symlinks, but that's not possible with fstat().
368      * In other cases, it's undefined, and we should really not go further. */
369 #ifndef S_TYPEISSHM
370 # define S_TYPEISSHM( buf ) (0)
371 #endif
372     if (S_ISDIR (st.st_mode))
373     {
374         errno = EISDIR;
375         return NULL;
376     }
377     if (!S_ISREG (st.st_mode) && !S_TYPEISSHM (&st))
378     {
379         errno = ESPIPE;
380         return NULL;
381     }
382
383     /* Prevent an integer overflow in mmap() and malloc() */
384     if (st.st_size >= SIZE_MAX)
385     {
386         errno = ENOMEM;
387         return NULL;
388     }
389     length = (size_t)st.st_size;
390
391 #ifdef HAVE_MMAP
392     if (length > 0)
393     {
394         void *addr;
395
396         addr = mmap (NULL, length, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
397         if (addr != MAP_FAILED)
398             return block_mmap_Alloc (addr, length);
399     }
400 #endif
401
402     /* If mmap() is not implemented by the OS _or_ the filesystem... */
403     block_t *block = block_Alloc (length);
404     if (block == NULL)
405         return NULL;
406     block_cleanup_push (block);
407
408     for (size_t i = 0; i < length;)
409     {
410         ssize_t len = pread (fd, block->p_buffer + i, length - i, i);
411         if (len == -1)
412         {
413             block_Release (block);
414             block = NULL;
415             break;
416         }
417         i += len;
418     }
419     vlc_cleanup_pop ();
420     return block;
421 }
422
423 /**
424  * @section Thread-safe block queue functions
425  */
426
427 /**
428  * Internal state for block queues
429  */
430 struct block_fifo_t
431 {
432     vlc_mutex_t         lock;                         /* fifo data lock */
433     vlc_cond_t          wait;      /**< Wait for data */
434     vlc_cond_t          wait_room; /**< Wait for queue depth to shrink */
435
436     block_t             *p_first;
437     block_t             **pp_last;
438     size_t              i_depth;
439     size_t              i_size;
440     bool          b_force_wake;
441 };
442
443 block_fifo_t *block_FifoNew( void )
444 {
445     block_fifo_t *p_fifo = malloc( sizeof( block_fifo_t ) );
446     if( !p_fifo )
447         return NULL;
448
449     vlc_mutex_init( &p_fifo->lock );
450     vlc_cond_init( &p_fifo->wait );
451     vlc_cond_init( &p_fifo->wait_room );
452     p_fifo->p_first = NULL;
453     p_fifo->pp_last = &p_fifo->p_first;
454     p_fifo->i_depth = p_fifo->i_size = 0;
455     p_fifo->b_force_wake = false;
456
457     return p_fifo;
458 }
459
460 void block_FifoRelease( block_fifo_t *p_fifo )
461 {
462     block_FifoEmpty( p_fifo );
463     vlc_cond_destroy( &p_fifo->wait_room );
464     vlc_cond_destroy( &p_fifo->wait );
465     vlc_mutex_destroy( &p_fifo->lock );
466     free( p_fifo );
467 }
468
469 void block_FifoEmpty( block_fifo_t *p_fifo )
470 {
471     block_t *block;
472
473     vlc_mutex_lock( &p_fifo->lock );
474     block = p_fifo->p_first;
475     if (block != NULL)
476     {
477         p_fifo->i_depth = p_fifo->i_size = 0;
478         p_fifo->p_first = NULL;
479         p_fifo->pp_last = &p_fifo->p_first;
480     }
481     vlc_cond_broadcast( &p_fifo->wait_room );
482     vlc_mutex_unlock( &p_fifo->lock );
483
484     while (block != NULL)
485     {
486         block_t *buf;
487
488         buf = block->p_next;
489         block_Release (block);
490         block = buf;
491     }
492 }
493
494 /**
495  * Wait until the FIFO gets below a certain size (if needed).
496  *
497  * Note that if more than one thread writes to the FIFO, you cannot assume that
498  * the FIFO is actually below the requested size upon return (since another
499  * thread could have refilled it already). This is typically not an issue, as
500  * this function is meant for (relaxed) congestion control.
501  *
502  * This function may be a cancellation point and it is cancel-safe.
503  *
504  * @param fifo queue to wait on
505  * @param max_depth wait until the queue has no more than this many blocks
506  *                  (use SIZE_MAX to ignore this constraint)
507  * @param max_size wait until the queue has no more than this many bytes
508  *                  (use SIZE_MAX to ignore this constraint)
509  * @return nothing.
510  */
511 void block_FifoPace (block_fifo_t *fifo, size_t max_depth, size_t max_size)
512 {
513     vlc_testcancel ();
514
515     vlc_mutex_lock (&fifo->lock);
516     while ((fifo->i_depth > max_depth) || (fifo->i_size > max_size))
517     {
518          mutex_cleanup_push (&fifo->lock);
519          vlc_cond_wait (&fifo->wait_room, &fifo->lock);
520          vlc_cleanup_pop ();
521     }
522     vlc_mutex_unlock (&fifo->lock);
523 }
524
525 /**
526  * Immediately queue one block at the end of a FIFO.
527  * @param fifo queue
528  * @param block head of a block list to queue (may be NULL)
529  * @return total number of bytes appended to the queue
530  */
531 size_t block_FifoPut( block_fifo_t *p_fifo, block_t *p_block )
532 {
533     size_t i_size = 0, i_depth = 0;
534     block_t *p_last;
535
536     if (p_block == NULL)
537         return 0;
538     for (p_last = p_block; ; p_last = p_last->p_next)
539     {
540         i_size += p_last->i_buffer;
541         i_depth++;
542         if (!p_last->p_next)
543             break;
544     }
545
546     vlc_mutex_lock (&p_fifo->lock);
547     *p_fifo->pp_last = p_block;
548     p_fifo->pp_last = &p_last->p_next;
549     p_fifo->i_depth += i_depth;
550     p_fifo->i_size += i_size;
551     /* We queued at least one block: wake up one read-waiting thread */
552     vlc_cond_signal( &p_fifo->wait );
553     vlc_mutex_unlock( &p_fifo->lock );
554
555     return i_size;
556 }
557
558 void block_FifoWake( block_fifo_t *p_fifo )
559 {
560     vlc_mutex_lock( &p_fifo->lock );
561     if( p_fifo->p_first == NULL )
562         p_fifo->b_force_wake = true;
563     vlc_cond_broadcast( &p_fifo->wait );
564     vlc_mutex_unlock( &p_fifo->lock );
565 }
566
567 /**
568  * Dequeue the first block from the FIFO. If necessary, wait until there is
569  * one block in the queue. This function is (always) cancellation point.
570  *
571  * @return a valid block, or NULL if block_FifoWake() was called.
572  */
573 block_t *block_FifoGet( block_fifo_t *p_fifo )
574 {
575     block_t *b;
576
577     vlc_testcancel( );
578
579     vlc_mutex_lock( &p_fifo->lock );
580     mutex_cleanup_push( &p_fifo->lock );
581
582     /* Remember vlc_cond_wait() may cause spurious wakeups
583      * (on both Win32 and POSIX) */
584     while( ( p_fifo->p_first == NULL ) && !p_fifo->b_force_wake )
585         vlc_cond_wait( &p_fifo->wait, &p_fifo->lock );
586
587     vlc_cleanup_pop();
588     b = p_fifo->p_first;
589
590     p_fifo->b_force_wake = false;
591     if( b == NULL )
592     {
593         /* Forced wakeup */
594         vlc_mutex_unlock( &p_fifo->lock );
595         return NULL;
596     }
597
598     p_fifo->p_first = b->p_next;
599     p_fifo->i_depth--;
600     p_fifo->i_size -= b->i_buffer;
601
602     if( p_fifo->p_first == NULL )
603     {
604         p_fifo->pp_last = &p_fifo->p_first;
605     }
606
607     /* We don't know how many threads can queue new packets now. */
608     vlc_cond_broadcast( &p_fifo->wait_room );
609     vlc_mutex_unlock( &p_fifo->lock );
610
611     b->p_next = NULL;
612     return b;
613 }
614
615 /**
616  * Peeks the first block in the FIFO.
617  * If necessary, wait until there is one block.
618  * This function is (always) a cancellation point.
619  *
620  * @warning This function leaves the block in the FIFO.
621  * You need to protect against concurrent threads who could dequeue the block.
622  * Preferrably, there should be only one thread reading from the FIFO.
623  *
624  * @return a valid block.
625  */
626 block_t *block_FifoShow( block_fifo_t *p_fifo )
627 {
628     block_t *b;
629
630     vlc_testcancel( );
631
632     vlc_mutex_lock( &p_fifo->lock );
633     mutex_cleanup_push( &p_fifo->lock );
634
635     while( p_fifo->p_first == NULL )
636         vlc_cond_wait( &p_fifo->wait, &p_fifo->lock );
637
638     b = p_fifo->p_first;
639
640     vlc_cleanup_run ();
641     return b;
642 }
643
644 /* FIXME: not thread-safe */
645 size_t block_FifoSize( const block_fifo_t *p_fifo )
646 {
647     return p_fifo->i_size;
648 }
649
650 /* FIXME: not thread-safe */
651 size_t block_FifoCount( const block_fifo_t *p_fifo )
652 {
653     return p_fifo->i_depth;
654 }