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