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
7 * Authors: Laurent Aimar <fenrir@videolan.org>
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.
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.
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 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
31 #include <vlc_common.h>
35 #include "vlc_block.h"
38 * @section Block handling functions.
42 * Internal state for heap block.
47 size_t i_allocated_buffer;
48 uint8_t p_allocated_buffer[];
52 static void BlockNoRelease( block_t *b )
54 fprintf( stderr, "block %p has no release callback! This is a bug!\n", b );
59 void block_Init( block_t *restrict b, void *buf, size_t size )
61 /* Fill all fields to their default */
65 b->i_dts = VLC_TS_INVALID;
72 b->pf_release = BlockNoRelease;
76 static void BlockRelease( block_t *p_block )
81 static void BlockMetaCopy( block_t *restrict out, const block_t *in )
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;
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
99 block_t *block_Alloc( size_t i_size )
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
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)
116 if( posix_memalign( &ptr, BLOCK_ALIGN, i_alloc ) )
120 buf = p_sys->p_allocated_buffer + (-sizeof(*p_sys) & (BLOCK_ALIGN - 1));
123 const size_t i_alloc = sizeof(*p_sys) + BLOCK_ALIGN + (2 * BLOCK_PADDING)
125 p_sys = malloc( i_alloc );
129 buf = (void *)ALIGN((uintptr_t)p_sys->p_allocated_buffer);
132 buf += BLOCK_PADDING;
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);
142 block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
144 block_sys_t *p_sys = (block_sys_t *)p_block;
145 size_t requested = i_prebody + i_body;
147 /* Corner case: empty block requested */
148 if( i_prebody <= 0 && i_body <= (size_t)(-i_prebody) )
150 block_Release( p_block );
154 if( p_block->pf_release != BlockRelease )
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 );
164 p_sys = (block_sys_t *)p_block;
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;
170 assert( p_block->p_buffer + p_block->i_buffer <= p_end );
171 assert( p_block->p_buffer >= p_start );
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 )
178 size_t available = p_end - p_start;
180 if( requested <= available )
181 { /* Enough room: recycle buffer */
182 size_t extra = available - requested;
184 p_block->p_buffer = p_start + (extra / 2);
185 p_block->i_buffer = requested;
188 /* Not enough room: allocate a new buffer */
189 block_t *p_rea = block_Alloc( requested );
191 BlockMetaCopy( p_rea, p_block );
192 block_Release( p_block );
196 /* First, shrink payload */
198 /* Pull payload start */
201 assert( p_block->i_buffer >= (size_t)-i_prebody );
202 p_block->p_buffer -= i_prebody;
203 p_block->i_buffer += i_prebody;
208 /* Trim payload end */
209 if( p_block->i_buffer > i_body )
210 p_block->i_buffer = i_body;
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 )
218 block_t *p_rea = block_Alloc( requested );
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 );
226 block_Release( p_block );
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 )
234 block_t *p_rea = block_Alloc( requested );
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 );
246 /* NOTE: p_start and p_end are corrupted from this point */
248 /* Third, expand payload */
250 /* Push payload start */
253 p_block->p_buffer -= i_prebody;
254 p_block->i_buffer += i_prebody;
259 /* Expand payload to requested size */
260 p_block->i_buffer = i_body;
272 static void block_heap_Release (block_t *self)
274 block_heap_t *block = (block_heap_t *)self;
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.
285 * When block_Release() is called, VLC will free() the specified pointer.
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 datan
290 * @return NULL in case of error (ptr free()'d in that case), or a valid
293 block_t *block_heap_Alloc (void *ptr, void *addr, size_t length)
295 block_heap_t *block = malloc (sizeof (*block));
302 block_Init (&block->self, (uint8_t *)addr, length);
303 block->self.pf_release = block_heap_Release;
309 # include <sys/mman.h>
311 typedef struct block_mmap_t
318 static void block_mmap_Release (block_t *block)
320 block_mmap_t *p_sys = (block_mmap_t *)block;
322 munmap (p_sys->base_addr, p_sys->length);
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.
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).
336 block_t *block_mmap_Alloc (void *addr, size_t length)
338 if (addr == MAP_FAILED)
341 block_mmap_t *block = malloc (sizeof (*block));
344 munmap (addr, length);
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;
355 block_t *block_mmap_Alloc (void *addr, size_t length)
357 (void)addr; (void)length; return NULL;
364 #define _get_osfhandle(a) ((long) (a))
368 ssize_t pread (int fd, void *buf, size_t count, off_t offset)
370 HANDLE handle = (HANDLE)(intptr_t)_get_osfhandle (fd);
371 if (handle == INVALID_HANDLE_VALUE)
374 OVERLAPPED olap; olap.Offset = offset; olap.OffsetHigh = (offset >> 32);
376 /* This braindead API will override the file pointer even if we specify
377 * an explicit read offset... So do not expect this to mix well with
378 * regular read() calls. */
379 if (ReadFile (handle, buf, count, &written, &olap))
386 * Loads a file into a block of memory. If possible a private file mapping is
387 * created. Otherwise, the file is read normally. On 32-bits platforms, this
388 * function will not work for very large files, due to memory space
389 * constraints. Cancellation point.
391 * @param fd file descriptor to load from
392 * @return a new block with the file content at p_buffer, and file length at
393 * i_buffer (release it with block_Release()), or NULL upon error (see errno).
395 block_t *block_File (int fd)
400 /* First, get the file size */
404 /* st_size is meaningful for regular files, shared memory and typed memory.
405 * It's also meaning for symlinks, but that's not possible with fstat().
406 * In other cases, it's undefined, and we should really not go further. */
408 # define S_TYPEISSHM( buf ) (0)
410 if (S_ISDIR (st.st_mode))
415 if (!S_ISREG (st.st_mode) && !S_TYPEISSHM (&st))
421 /* Prevent an integer overflow in mmap() and malloc() */
422 if (st.st_size >= SIZE_MAX)
427 length = (size_t)st.st_size;
434 addr = mmap (NULL, length, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
435 if (addr != MAP_FAILED)
436 return block_mmap_Alloc (addr, length);
440 /* If mmap() is not implemented by the OS _or_ the filesystem... */
441 block_t *block = block_Alloc (length);
444 block_cleanup_push (block);
446 for (size_t i = 0; i < length;)
448 ssize_t len = pread (fd, block->p_buffer + i, length - i, i);
451 block_Release (block);
462 * @section Thread-safe block queue functions
466 * Internal state for block queues
470 vlc_mutex_t lock; /* fifo data lock */
471 vlc_cond_t wait; /**< Wait for data */
472 vlc_cond_t wait_room; /**< Wait for queue depth to shrink */
481 block_fifo_t *block_FifoNew( void )
483 block_fifo_t *p_fifo = malloc( sizeof( block_fifo_t ) );
487 vlc_mutex_init( &p_fifo->lock );
488 vlc_cond_init( &p_fifo->wait );
489 vlc_cond_init( &p_fifo->wait_room );
490 p_fifo->p_first = NULL;
491 p_fifo->pp_last = &p_fifo->p_first;
492 p_fifo->i_depth = p_fifo->i_size = 0;
493 p_fifo->b_force_wake = false;
498 void block_FifoRelease( block_fifo_t *p_fifo )
500 block_FifoEmpty( p_fifo );
501 vlc_cond_destroy( &p_fifo->wait_room );
502 vlc_cond_destroy( &p_fifo->wait );
503 vlc_mutex_destroy( &p_fifo->lock );
507 void block_FifoEmpty( block_fifo_t *p_fifo )
511 vlc_mutex_lock( &p_fifo->lock );
512 for( b = p_fifo->p_first; b != NULL; )
521 p_fifo->i_depth = p_fifo->i_size = 0;
522 p_fifo->p_first = NULL;
523 p_fifo->pp_last = &p_fifo->p_first;
524 vlc_cond_broadcast( &p_fifo->wait_room );
525 vlc_mutex_unlock( &p_fifo->lock );
529 * Wait until the FIFO gets below a certain size (if needed).
531 * Note that if more than one thread writes to the FIFO, you cannot assume that
532 * the FIFO is actually below the requested size upon return (since another
533 * thread could have refilled it already). This is typically not an issue, as
534 * this function is meant for (relaxed) congestion control.
536 * This function may be a cancellation point and it is cancel-safe.
538 * @param fifo queue to wait on
539 * @param max_depth wait until the queue has no more than this many blocks
540 * (use SIZE_MAX to ignore this constraint)
541 * @param max_size wait until the queue has no more than this many bytes
542 * (use SIZE_MAX to ignore this constraint)
545 void block_FifoPace (block_fifo_t *fifo, size_t max_depth, size_t max_size)
549 vlc_mutex_lock (&fifo->lock);
550 while ((fifo->i_depth > max_depth) || (fifo->i_size > max_size))
552 mutex_cleanup_push (&fifo->lock);
553 vlc_cond_wait (&fifo->wait_room, &fifo->lock);
556 vlc_mutex_unlock (&fifo->lock);
560 * Immediately queue one block at the end of a FIFO.
562 * @param block head of a block list to queue (may be NULL)
564 size_t block_FifoPut( block_fifo_t *p_fifo, block_t *p_block )
567 vlc_mutex_lock( &p_fifo->lock );
569 while (p_block != NULL)
571 i_size += p_block->i_buffer;
573 *p_fifo->pp_last = p_block;
574 p_fifo->pp_last = &p_block->p_next;
576 p_fifo->i_size += p_block->i_buffer;
578 p_block = p_block->p_next;
581 /* We queued one block: wake up one read-waiting thread */
582 vlc_cond_signal( &p_fifo->wait );
583 vlc_mutex_unlock( &p_fifo->lock );
588 void block_FifoWake( block_fifo_t *p_fifo )
590 vlc_mutex_lock( &p_fifo->lock );
591 if( p_fifo->p_first == NULL )
592 p_fifo->b_force_wake = true;
593 vlc_cond_broadcast( &p_fifo->wait );
594 vlc_mutex_unlock( &p_fifo->lock );
597 block_t *block_FifoGet( block_fifo_t *p_fifo )
603 vlc_mutex_lock( &p_fifo->lock );
604 mutex_cleanup_push( &p_fifo->lock );
606 /* Remember vlc_cond_wait() may cause spurious wakeups
607 * (on both Win32 and POSIX) */
608 while( ( p_fifo->p_first == NULL ) && !p_fifo->b_force_wake )
609 vlc_cond_wait( &p_fifo->wait, &p_fifo->lock );
614 p_fifo->b_force_wake = false;
618 vlc_mutex_unlock( &p_fifo->lock );
622 p_fifo->p_first = b->p_next;
624 p_fifo->i_size -= b->i_buffer;
626 if( p_fifo->p_first == NULL )
628 p_fifo->pp_last = &p_fifo->p_first;
631 /* We don't know how many threads can queue new packets now. */
632 vlc_cond_broadcast( &p_fifo->wait_room );
633 vlc_mutex_unlock( &p_fifo->lock );
639 block_t *block_FifoShow( block_fifo_t *p_fifo )
645 vlc_mutex_lock( &p_fifo->lock );
646 mutex_cleanup_push( &p_fifo->lock );
648 while( p_fifo->p_first == NULL )
649 vlc_cond_wait( &p_fifo->wait, &p_fifo->lock );
657 /* FIXME: not thread-safe */
658 size_t block_FifoSize( const block_fifo_t *p_fifo )
660 return p_fifo->i_size;
663 /* FIXME: not thread-safe */
664 size_t block_FifoCount( const block_fifo_t *p_fifo )
666 return p_fifo->i_depth;