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