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