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