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