1 /*****************************************************************************
2 * block.c: Data blocks management functions
3 *****************************************************************************
4 * Copyright (C) 2003-2004 VLC authors and VideoLAN
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 it
10 * under the terms of the GNU Lesser General Public License as published by
11 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this program; if not, write to the Free Software Foundation,
21 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
38 #include <vlc_common.h>
39 #include <vlc_block.h>
42 * @section Block handling functions.
46 static void BlockNoRelease( block_t *b )
48 fprintf( stderr, "block %p has no release callback! This is a bug!\n", b );
53 void block_Init( block_t *restrict b, void *buf, size_t size )
55 /* Fill all fields to their default */
64 b->i_dts = VLC_TS_INVALID;
67 b->pf_release = BlockNoRelease;
71 static void BlockRelease( block_t *p_block )
76 static void BlockMetaCopy( block_t *restrict out, const block_t *in )
78 out->p_next = in->p_next;
79 out->i_nb_samples = in->i_nb_samples;
80 out->i_dts = in->i_dts;
81 out->i_pts = in->i_pts;
82 out->i_flags = in->i_flags;
83 out->i_length = in->i_length;
86 /* Memory alignment (must be a multiple of sizeof(void*) and a power of two) */
87 #define BLOCK_ALIGN 16
88 /* Initial reserved header and footer size (must be multiple of alignment) */
89 #define BLOCK_PADDING 32
90 /* Maximum size of reserved footer before we release with realloc() */
91 #define BLOCK_WASTE_SIZE 2048
93 block_t *block_Alloc (size_t size)
95 /* 2 * BLOCK_PADDING: pre + post padding */
96 const size_t alloc = sizeof (block_t) + BLOCK_ALIGN + (2 * BLOCK_PADDING)
98 if (unlikely(alloc <= size))
101 block_t *b = malloc (alloc);
102 if (unlikely(b == NULL))
105 block_Init (b, b + 1, alloc);
106 static_assert ((BLOCK_PADDING % BLOCK_ALIGN) == 0,
107 "BLOCK_PADDING must be a multiple of BLOCK_ALIGN");
108 b->p_buffer += BLOCK_PADDING + BLOCK_ALIGN - 1;
109 b->p_buffer = (void *)(((uintptr_t)b->p_buffer) & ~(BLOCK_ALIGN - 1));
111 b->pf_release = BlockRelease;
115 block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
117 size_t requested = i_prebody + i_body;
119 /* Corner case: empty block requested */
120 if( i_prebody <= 0 && i_body <= (size_t)(-i_prebody) )
122 block_Release( p_block );
126 assert( p_block->p_start <= p_block->p_buffer );
127 assert( p_block->p_start + p_block->i_size
128 >= p_block->p_buffer + p_block->i_buffer );
130 /* Corner case: the current payload is discarded completely */
131 if( i_prebody <= 0 && p_block->i_buffer <= (size_t)-i_prebody )
132 p_block->i_buffer = 0; /* discard current payload */
133 if( p_block->i_buffer == 0 )
135 if( requested <= p_block->i_size )
136 { /* Enough room: recycle buffer */
137 size_t extra = p_block->i_size - requested;
139 p_block->p_buffer = p_block->p_start + (extra / 2);
140 p_block->i_buffer = requested;
143 /* Not enough room: allocate a new buffer */
144 block_t *p_rea = block_Alloc( requested );
146 BlockMetaCopy( p_rea, p_block );
147 block_Release( p_block );
151 /* First, shrink payload */
153 /* Pull payload start */
156 assert( p_block->i_buffer >= (size_t)-i_prebody );
157 p_block->p_buffer -= i_prebody;
158 p_block->i_buffer += i_prebody;
163 /* Trim payload end */
164 if( p_block->i_buffer > i_body )
165 p_block->i_buffer = i_body;
167 uint8_t *p_start = p_block->p_start;
168 uint8_t *p_end = p_start + p_block->i_size;
170 /* Second, reallocate the buffer if we lack space. This is done now to
171 * minimize the payload size for memory copy. */
172 assert( i_prebody >= 0 );
173 if( (size_t)(p_block->p_buffer - p_start) < (size_t)i_prebody
174 || (size_t)(p_end - p_block->p_buffer) < i_body )
176 block_t *p_rea = block_Alloc( requested );
179 BlockMetaCopy( p_rea, p_block );
180 p_rea->p_buffer += i_prebody;
181 p_rea->i_buffer -= i_prebody;
182 memcpy( p_rea->p_buffer, p_block->p_buffer, p_block->i_buffer );
184 block_Release( p_block );
190 /* We have a very large reserved footer now? Release some of it.
191 * XXX it might not preserve the alignment of p_buffer */
192 if( p_end - (p_block->p_buffer + i_body) > BLOCK_WASTE_SIZE )
194 block_t *p_rea = block_Alloc( requested );
197 BlockMetaCopy( p_rea, p_block );
198 p_rea->p_buffer += i_prebody;
199 p_rea->i_buffer -= i_prebody;
200 memcpy( p_rea->p_buffer, p_block->p_buffer, p_block->i_buffer );
201 block_Release( p_block );
206 /* NOTE: p_start and p_end are corrupted from this point */
208 /* Third, expand payload */
210 /* Push payload start */
213 p_block->p_buffer -= i_prebody;
214 p_block->i_buffer += i_prebody;
219 /* Expand payload to requested size */
220 p_block->i_buffer = i_body;
226 static void block_heap_Release (block_t *block)
228 free (block->p_start);
233 * Creates a block from a heap allocation.
234 * This is provided by LibVLC so that manually heap-allocated blocks can safely
235 * be deallocated even after the origin plugin has been unloaded from memory.
237 * When block_Release() is called, VLC will free() the specified pointer.
239 * @param ptr base address of the heap allocation (will be free()'d)
240 * @param length bytes length of the heap allocation
241 * @return NULL in case of error (ptr free()'d in that case), or a valid
244 block_t *block_heap_Alloc (void *addr, size_t length)
246 block_t *block = malloc (sizeof (*block));
253 block_Init (block, addr, length);
254 block->pf_release = block_heap_Release;
259 # include <sys/mman.h>
261 static void block_mmap_Release (block_t *block)
263 munmap (block->p_start, block->i_size);
268 * Creates a block from a virtual address memory mapping (mmap).
269 * This is provided by LibVLC so that mmap blocks can safely be deallocated
270 * even after the allocating plugin has been unloaded from memory.
272 * @param addr base address of the mapping (as returned by mmap)
273 * @param length length (bytes) of the mapping (as passed to mmap)
274 * @return NULL if addr is MAP_FAILED, or an error occurred (in the later
275 * case, munmap(addr, length) is invoked before returning).
277 block_t *block_mmap_Alloc (void *addr, size_t length)
279 if (addr == MAP_FAILED)
282 block_t *block = malloc (sizeof (*block));
285 munmap (addr, length);
289 block_Init (block, addr, length);
290 block->pf_release = block_mmap_Release;
294 block_t *block_mmap_Alloc (void *addr, size_t length)
296 (void)addr; (void)length; return NULL;
304 # define _get_osfhandle(a) ((long) (a))
308 ssize_t pread (int fd, void *buf, size_t count, off_t offset)
310 HANDLE handle = (HANDLE)(intptr_t)_get_osfhandle (fd);
311 if (handle == INVALID_HANDLE_VALUE)
314 OVERLAPPED olap; olap.Offset = offset; olap.OffsetHigh = (offset >> 32);
316 /* This braindead API will override the file pointer even if we specify
317 * an explicit read offset... So do not expect this to mix well with
318 * regular read() calls. */
319 if (ReadFile (handle, buf, count, &written, &olap))
323 #elif !defined( HAVE_PREAD )
325 ssize_t pread(int fd, const void * buf, size_t size, off_t offset) {
328 if ((offs0 = lseek(fd, 0, SEEK_CUR)) == (off_t)-1) return -1;
329 if (lseek(fd, offset, SEEK_SET) == (off_t)-1) return -1;
330 rd = read(fd, (void *)buf, size);
331 if (lseek(fd, offs0, SEEK_SET) == (off_t)-1) return -1;
336 ssize_t pwrite(int fd, const void * buf, size_t size, off_t offset) {
339 if ((offs0 = lseek(fd, 0, SEEK_CUR)) == (off_t)-1) return -1;
340 if (lseek(fd, offset, SEEK_SET) == (off_t)-1) return -1;
341 wr = write(fd, (void *)buf, size);
342 if (lseek(fd, offs0, SEEK_SET) == (off_t)-1) return -1;
348 * Loads a file into a block of memory. If possible a private file mapping is
349 * created. Otherwise, the file is read normally. On 32-bits platforms, this
350 * function will not work for very large files, due to memory space
351 * constraints. Cancellation point.
353 * @param fd file descriptor to load from
354 * @return a new block with the file content at p_buffer, and file length at
355 * i_buffer (release it with block_Release()), or NULL upon error (see errno).
357 block_t *block_File (int fd)
362 /* First, get the file size */
366 /* st_size is meaningful for regular files, shared memory and typed memory.
367 * It's also meaning for symlinks, but that's not possible with fstat().
368 * In other cases, it's undefined, and we should really not go further. */
370 # define S_TYPEISSHM( buf ) (0)
372 if (S_ISDIR (st.st_mode))
377 if (!S_ISREG (st.st_mode) && !S_TYPEISSHM (&st))
383 /* Prevent an integer overflow in mmap() and malloc() */
384 if (st.st_size >= SIZE_MAX)
389 length = (size_t)st.st_size;
396 addr = mmap (NULL, length, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
397 if (addr != MAP_FAILED)
398 return block_mmap_Alloc (addr, length);
402 /* If mmap() is not implemented by the OS _or_ the filesystem... */
403 block_t *block = block_Alloc (length);
406 block_cleanup_push (block);
408 for (size_t i = 0; i < length;)
410 ssize_t len = pread (fd, block->p_buffer + i, length - i, i);
413 block_Release (block);
424 * @section Thread-safe block queue functions
428 * Internal state for block queues
432 vlc_mutex_t lock; /* fifo data lock */
433 vlc_cond_t wait; /**< Wait for data */
434 vlc_cond_t wait_room; /**< Wait for queue depth to shrink */
443 block_fifo_t *block_FifoNew( void )
445 block_fifo_t *p_fifo = malloc( sizeof( block_fifo_t ) );
449 vlc_mutex_init( &p_fifo->lock );
450 vlc_cond_init( &p_fifo->wait );
451 vlc_cond_init( &p_fifo->wait_room );
452 p_fifo->p_first = NULL;
453 p_fifo->pp_last = &p_fifo->p_first;
454 p_fifo->i_depth = p_fifo->i_size = 0;
455 p_fifo->b_force_wake = false;
460 void block_FifoRelease( block_fifo_t *p_fifo )
462 block_FifoEmpty( p_fifo );
463 vlc_cond_destroy( &p_fifo->wait_room );
464 vlc_cond_destroy( &p_fifo->wait );
465 vlc_mutex_destroy( &p_fifo->lock );
469 void block_FifoEmpty( block_fifo_t *p_fifo )
473 vlc_mutex_lock( &p_fifo->lock );
474 block = p_fifo->p_first;
477 p_fifo->i_depth = p_fifo->i_size = 0;
478 p_fifo->p_first = NULL;
479 p_fifo->pp_last = &p_fifo->p_first;
481 vlc_cond_broadcast( &p_fifo->wait_room );
482 vlc_mutex_unlock( &p_fifo->lock );
484 while (block != NULL)
489 block_Release (block);
495 * Wait until the FIFO gets below a certain size (if needed).
497 * Note that if more than one thread writes to the FIFO, you cannot assume that
498 * the FIFO is actually below the requested size upon return (since another
499 * thread could have refilled it already). This is typically not an issue, as
500 * this function is meant for (relaxed) congestion control.
502 * This function may be a cancellation point and it is cancel-safe.
504 * @param fifo queue to wait on
505 * @param max_depth wait until the queue has no more than this many blocks
506 * (use SIZE_MAX to ignore this constraint)
507 * @param max_size wait until the queue has no more than this many bytes
508 * (use SIZE_MAX to ignore this constraint)
511 void block_FifoPace (block_fifo_t *fifo, size_t max_depth, size_t max_size)
515 vlc_mutex_lock (&fifo->lock);
516 while ((fifo->i_depth > max_depth) || (fifo->i_size > max_size))
518 mutex_cleanup_push (&fifo->lock);
519 vlc_cond_wait (&fifo->wait_room, &fifo->lock);
522 vlc_mutex_unlock (&fifo->lock);
526 * Immediately queue one block at the end of a FIFO.
528 * @param block head of a block list to queue (may be NULL)
529 * @return total number of bytes appended to the queue
531 size_t block_FifoPut( block_fifo_t *p_fifo, block_t *p_block )
533 size_t i_size = 0, i_depth = 0;
538 for (p_last = p_block; ; p_last = p_last->p_next)
540 i_size += p_last->i_buffer;
546 vlc_mutex_lock (&p_fifo->lock);
547 *p_fifo->pp_last = p_block;
548 p_fifo->pp_last = &p_last->p_next;
549 p_fifo->i_depth += i_depth;
550 p_fifo->i_size += i_size;
551 /* We queued at least one block: wake up one read-waiting thread */
552 vlc_cond_signal( &p_fifo->wait );
553 vlc_mutex_unlock( &p_fifo->lock );
558 void block_FifoWake( block_fifo_t *p_fifo )
560 vlc_mutex_lock( &p_fifo->lock );
561 if( p_fifo->p_first == NULL )
562 p_fifo->b_force_wake = true;
563 vlc_cond_broadcast( &p_fifo->wait );
564 vlc_mutex_unlock( &p_fifo->lock );
568 * Dequeue the first block from the FIFO. If necessary, wait until there is
569 * one block in the queue. This function is (always) cancellation point.
571 * @return a valid block, or NULL if block_FifoWake() was called.
573 block_t *block_FifoGet( block_fifo_t *p_fifo )
579 vlc_mutex_lock( &p_fifo->lock );
580 mutex_cleanup_push( &p_fifo->lock );
582 /* Remember vlc_cond_wait() may cause spurious wakeups
583 * (on both Win32 and POSIX) */
584 while( ( p_fifo->p_first == NULL ) && !p_fifo->b_force_wake )
585 vlc_cond_wait( &p_fifo->wait, &p_fifo->lock );
590 p_fifo->b_force_wake = false;
594 vlc_mutex_unlock( &p_fifo->lock );
598 p_fifo->p_first = b->p_next;
600 p_fifo->i_size -= b->i_buffer;
602 if( p_fifo->p_first == NULL )
604 p_fifo->pp_last = &p_fifo->p_first;
607 /* We don't know how many threads can queue new packets now. */
608 vlc_cond_broadcast( &p_fifo->wait_room );
609 vlc_mutex_unlock( &p_fifo->lock );
616 * Peeks the first block in the FIFO.
617 * If necessary, wait until there is one block.
618 * This function is (always) a cancellation point.
620 * @warning This function leaves the block in the FIFO.
621 * You need to protect against concurrent threads who could dequeue the block.
622 * Preferrably, there should be only one thread reading from the FIFO.
624 * @return a valid block.
626 block_t *block_FifoShow( block_fifo_t *p_fifo )
632 vlc_mutex_lock( &p_fifo->lock );
633 mutex_cleanup_push( &p_fifo->lock );
635 while( p_fifo->p_first == NULL )
636 vlc_cond_wait( &p_fifo->wait, &p_fifo->lock );
644 /* FIXME: not thread-safe */
645 size_t block_FifoSize( const block_fifo_t *p_fifo )
647 return p_fifo->i_size;
650 /* FIXME: not thread-safe */
651 size_t block_FifoCount( const block_fifo_t *p_fifo )
653 return p_fifo->i_depth;