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