]> git.sesse.net Git - vlc/blobdiff - src/misc/block.c
Replace block_New() with block_Alloc()
[vlc] / src / misc / block.c
index 339c5a58ab0f52409a3d30888b0fb2a32b14efb1..069628ab230addee58ba76d6b7ae2b942bb4322e 100644 (file)
@@ -1,24 +1,24 @@
 /*****************************************************************************
  * block.c: Data blocks management functions
  *****************************************************************************
- * Copyright (C) 2003-2004 the VideoLAN team
+ * Copyright (C) 2003-2004 VLC authors and VideoLAN
  * Copyright (C) 2007-2009 RĂ©mi Denis-Courmont
  *
  * Authors: Laurent Aimar <fenrir@videolan.org>
  *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
  *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  *****************************************************************************/
 
 /*****************************************************************************
 # include "config.h"
 #endif
 
-#include <vlc_common.h>
 #include <sys/stat.h>
 #include <assert.h>
-#include "vlc_block.h"
+#include <errno.h>
+#ifdef HAVE_UNISTD_H
+# include <unistd.h>
+#endif
+#include <fcntl.h>
+
+#include <vlc_common.h>
+#include <vlc_block.h>
+#include <vlc_fs.h>
 
 /**
  * @section Block handling functions.
  */
 
-/**
- * Internal state for heap block.
-  */
-struct block_sys_t
-{
-    block_t     self;
-    size_t      i_allocated_buffer;
-    uint8_t     p_allocated_buffer[];
-};
-
 #ifndef NDEBUG
 static void BlockNoRelease( block_t *b )
 {
     fprintf( stderr, "block %p has no release callback! This is a bug!\n", b );
     abort();
 }
+
+static void block_Check (block_t *block)
+{
+    while (block != NULL)
+    {
+        unsigned char *start = block->p_start;
+        unsigned char *end = block->p_start + block->i_size;
+        unsigned char *bufstart = block->p_buffer;
+        unsigned char *bufend = block->p_buffer + block->i_buffer;
+
+        assert (block->pf_release != BlockNoRelease);
+        assert (start <= end);
+        assert (bufstart <= bufend);
+        assert (bufstart >= start);
+        assert (bufend <= end);
+
+        block = block->p_next;
+    }
+}
+
+static void block_Invalidate (block_t *block)
+{
+    block->p_next = NULL;
+    block_Check (block);
+    block->pf_release = BlockNoRelease;
+}
+#else
+# define block_Check(b) ((void)(b))
+# define block_Invalidate(b) ((void)(b))
 #endif
 
 void block_Init( block_t *restrict b, void *buf, size_t size )
 {
     /* Fill all fields to their default */
     b->p_next = NULL;
+    b->p_buffer = buf;
+    b->i_buffer = size;
+    b->p_start = buf;
+    b->i_size = size;
     b->i_flags = 0;
+    b->i_nb_samples = 0;
     b->i_pts =
     b->i_dts = VLC_TS_INVALID;
     b->i_length = 0;
-    b->i_rate = 0;
-    b->p_buffer = buf;
-    b->i_buffer = size;
 #ifndef NDEBUG
     b->pf_release = BlockNoRelease;
 #endif
 }
 
-static void BlockRelease( block_t *p_block )
+static void block_generic_Release (block_t *block)
 {
-    free( p_block );
+    /* That is always true for blocks allocated with block_Alloc(). */
+    assert (block->p_start == (unsigned char *)(block + 1));
+    block_Invalidate (block);
+    free (block);
 }
 
 static void BlockMetaCopy( block_t *restrict out, const block_t *in )
 {
+    out->p_next    = in->p_next;
+    out->i_nb_samples = in->i_nb_samples;
     out->i_dts     = in->i_dts;
     out->i_pts     = in->i_pts;
     out->i_flags   = in->i_flags;
     out->i_length  = in->i_length;
-    out->i_rate    = in->i_rate;
-    out->i_samples = in->i_samples;
 }
 
-/* Memory alignment */
+/* Memory alignment (must be a multiple of sizeof(void*) and a power of two) */
 #define BLOCK_ALIGN        16
-/* Initial size of reserved header and footer */
-#define BLOCK_PADDING_SIZE 32
+/* Initial reserved header and footer size (must be multiple of alignment) */
+#define BLOCK_PADDING      32
 /* Maximum size of reserved footer before we release with realloc() */
 #define BLOCK_WASTE_SIZE   2048
 
-block_t *block_Alloc( size_t i_size )
+block_t *block_Alloc (size_t size)
 {
-    /* We do only one malloc
-     * TODO: bench if doing 2 malloc but keeping a pool of buffer is better
-     * TODO: use memalign
-     * 16 -> align on 16
-     * 2 * BLOCK_PADDING_SIZE -> pre + post padding
-     */
-    const size_t i_alloc = i_size + 2 * BLOCK_PADDING_SIZE + BLOCK_ALIGN;
-    block_sys_t *p_sys = malloc( sizeof( *p_sys ) + i_alloc );
-
-    if( p_sys == NULL )
+    /* 2 * BLOCK_PADDING: pre + post padding */
+    const size_t alloc = sizeof (block_t) + BLOCK_ALIGN + (2 * BLOCK_PADDING)
+                       + size;
+    if (unlikely(alloc <= size))
         return NULL;
 
-    /* Fill opaque data */
-    p_sys->i_allocated_buffer = i_alloc;
-
-    block_Init( &p_sys->self, p_sys->p_allocated_buffer + BLOCK_PADDING_SIZE
-                + BLOCK_ALIGN
-                - ((uintptr_t)p_sys->p_allocated_buffer % BLOCK_ALIGN),
-                i_size );
-    p_sys->self.pf_release    = BlockRelease;
+    block_t *b = malloc (alloc);
+    if (unlikely(b == NULL))
+        return NULL;
 
-    return &p_sys->self;
+    block_Init (b, b + 1, alloc - sizeof (*b));
+    static_assert ((BLOCK_PADDING % BLOCK_ALIGN) == 0,
+                   "BLOCK_PADDING must be a multiple of BLOCK_ALIGN");
+    b->p_buffer += BLOCK_PADDING + BLOCK_ALIGN - 1;
+    b->p_buffer = (void *)(((uintptr_t)b->p_buffer) & ~(BLOCK_ALIGN - 1));
+    b->i_buffer = size;
+    b->pf_release = block_generic_Release;
+    return b;
 }
 
 block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
 {
-    block_sys_t *p_sys = (block_sys_t *)p_block;
     size_t requested = i_prebody + i_body;
 
+    block_Check( p_block );
+
     /* Corner case: empty block requested */
     if( i_prebody <= 0 && i_body <= (size_t)(-i_prebody) )
     {
@@ -131,37 +159,20 @@ block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
         return NULL;
     }
 
-    if( p_block->pf_release != BlockRelease )
-    {
-        /* Special case when pf_release if overloaded
-         * TODO if used one day, then implement it in a smarter way */
-        block_t *p_dup = block_Duplicate( p_block );
-        block_Release( p_block );
-        if( !p_dup )
-            return NULL;
-
-        p_block = p_dup;
-        p_sys = (block_sys_t *)p_block;
-    }
-
-    uint8_t *p_start = p_sys->p_allocated_buffer;
-    uint8_t *p_end = p_sys->p_allocated_buffer + p_sys->i_allocated_buffer;
-
-    assert( p_block->p_buffer + p_block->i_buffer <= p_end );
-    assert( p_block->p_buffer >= p_start );
+    assert( p_block->p_start <= p_block->p_buffer );
+    assert( p_block->p_start + p_block->i_size
+                                    >= p_block->p_buffer + p_block->i_buffer );
 
     /* Corner case: the current payload is discarded completely */
     if( i_prebody <= 0 && p_block->i_buffer <= (size_t)-i_prebody )
          p_block->i_buffer = 0; /* discard current payload */
     if( p_block->i_buffer == 0 )
     {
-        size_t available = p_end - p_start;
-
-        if( requested <= available )
+        if( requested <= p_block->i_size )
         {   /* Enough room: recycle buffer */
-            size_t extra = available - requested;
+            size_t extra = p_block->i_size - requested;
 
-            p_block->p_buffer = p_start + (extra / 2);
+            p_block->p_buffer = p_block->p_start + (extra / 2);
             p_block->i_buffer = requested;
             return p_block;
         }
@@ -189,13 +200,15 @@ block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
     if( p_block->i_buffer > i_body )
         p_block->i_buffer = i_body;
 
+    uint8_t *p_start = p_block->p_start;
+    uint8_t *p_end = p_start + p_block->i_size;
+
     /* Second, reallocate the buffer if we lack space. This is done now to
      * minimize the payload size for memory copy. */
     assert( i_prebody >= 0 );
     if( (size_t)(p_block->p_buffer - p_start) < (size_t)i_prebody
-     || (size_t)(p_end - p_block->p_buffer) < p_block->i_buffer + i_body )
+     || (size_t)(p_end - p_block->p_buffer) < i_body )
     {
-        /* FIXME: this is really dumb, we should use realloc() */
         block_t *p_rea = block_Alloc( requested );
         if( p_rea )
         {
@@ -205,6 +218,8 @@ block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
             memcpy( p_rea->p_buffer, p_block->p_buffer, p_block->i_buffer );
         }
         block_Release( p_block );
+        if( p_rea == NULL )
+            return NULL;
         p_block = p_rea;
     }
     else
@@ -212,16 +227,15 @@ block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
      * XXX it might not preserve the alignment of p_buffer */
     if( p_end - (p_block->p_buffer + i_body) > BLOCK_WASTE_SIZE )
     {
-        const ptrdiff_t i_prebody = p_block->p_buffer - p_start;
-        const size_t i_new = requested + 1 * BLOCK_PADDING_SIZE;
-        block_sys_t *p_new = realloc( p_sys, sizeof (*p_sys) + i_new );
-
-        if( p_new != NULL )
+        block_t *p_rea = block_Alloc( requested );
+        if( p_rea )
         {
-            p_sys = p_new;
-            p_sys->i_allocated_buffer = i_new;
-            p_block = &p_sys->self;
-            p_block->p_buffer = &p_sys->p_allocated_buffer[i_prebody];
+            BlockMetaCopy( p_rea, p_block );
+            p_rea->p_buffer += i_prebody;
+            p_rea->i_buffer -= i_prebody;
+            memcpy( p_rea->p_buffer, p_block->p_buffer, p_block->i_buffer );
+            block_Release( p_block );
+            p_block = p_rea;
         }
     }
 
@@ -245,17 +259,10 @@ block_t *block_Realloc( block_t *p_block, ssize_t i_prebody, size_t i_body )
 }
 
 
-typedef struct
-{
-    block_t  self;
-    void    *mem;
-} block_heap_t;
-
-static void block_heap_Release (block_t *self)
+static void block_heap_Release (block_t *block)
 {
-    block_heap_t *block = (block_heap_t *)self;
-
-    free (block->mem);
+    block_Invalidate (block);
+    free (block->p_start);
     free (block);
 }
 
@@ -267,42 +274,32 @@ static void block_heap_Release (block_t *self)
  * When block_Release() is called, VLC will free() the specified pointer.
  *
  * @param ptr base address of the heap allocation (will be free()'d)
- * @param addr base address of the useful buffer data
- * @param length bytes length of the useful buffer datan
+ * @param length bytes length of the heap allocation
  * @return NULL in case of error (ptr free()'d in that case), or a valid
  * block_t pointer.
  */
-block_t *block_heap_Alloc (void *ptr, void *addr, size_t length)
+block_t *block_heap_Alloc (void *addr, size_t length)
 {
-    block_heap_t *block = malloc (sizeof (*block));
+    block_t *block = malloc (sizeof (*block));
     if (block == NULL)
     {
         free (addr);
         return NULL;
     }
 
-    block_Init (&block->self, (uint8_t *)addr, length);
-    block->self.pf_release = block_heap_Release;
-    block->mem = ptr;
-    return &block->self;
+    block_Init (block, addr, length);
+    block->pf_release = block_heap_Release;
+    return block;
 }
 
 #ifdef HAVE_MMAP
 # include <sys/mman.h>
 
-typedef struct block_mmap_t
-{
-    block_t     self;
-    void       *base_addr;
-    size_t      length;
-} block_mmap_t;
-
 static void block_mmap_Release (block_t *block)
 {
-    block_mmap_t *p_sys = (block_mmap_t *)block;
-
-    munmap (p_sys->base_addr, p_sys->length);
-    free (p_sys);
+    block_Invalidate (block);
+    munmap (block->p_start, block->i_size);
+    free (block);
 }
 
 /**
@@ -320,18 +317,16 @@ block_t *block_mmap_Alloc (void *addr, size_t length)
     if (addr == MAP_FAILED)
         return NULL;
 
-    block_mmap_t *block = malloc (sizeof (*block));
+    block_t *block = malloc (sizeof (*block));
     if (block == NULL)
     {
         munmap (addr, length);
         return NULL;
     }
 
-    block_Init (&block->self, (uint8_t *)addr, length);
-    block->self.pf_release = block_mmap_Release;
-    block->base_addr = addr;
-    block->length = length;
-    return &block->self;
+    block_Init (block, addr, length);
+    block->pf_release = block_mmap_Release;
+    return block;
 }
 #else
 block_t *block_mmap_Alloc (void *addr, size_t length)
@@ -342,9 +337,7 @@ block_t *block_mmap_Alloc (void *addr, size_t length)
 
 
 #ifdef WIN32
-#ifdef UNDER_CE
-#define _get_osfhandle(a) ((long) (a))
-#endif
+# include <io.h>
 
 static
 ssize_t pread (int fd, void *buf, size_t count, off_t offset)
@@ -365,10 +358,13 @@ ssize_t pread (int fd, void *buf, size_t count, off_t offset)
 #endif
 
 /**
- * Loads a file into a block of memory. If possible a private file mapping is
- * created. Otherwise, the file is read normally. On 32-bits platforms, this
- * function will not work for very large files, due to memory space
- * constraints. Cancellation point.
+ * Loads a file into a block of memory through a file descriptor.
+ * If possible a private file mapping is created. Otherwise, the file is read
+ * normally. This function is a cancellation point.
+ *
+ * @note On 32-bits platforms,
+ * this function will not work for very large files,
+ * due to memory space constraints.
  *
  * @param fd file descriptor to load from
  * @return a new block with the file content at p_buffer, and file length at
@@ -440,6 +436,21 @@ block_t *block_File (int fd)
     return block;
 }
 
+/**
+ * Loads a file into a block of memory from the file path.
+ * See also block_File().
+ */
+block_t *block_FilePath (const char *path)
+{
+    int fd = vlc_open (path, O_RDONLY);
+    if (fd == -1)
+        return NULL;
+
+    block_t *block = block_File (fd);
+    close (fd);
+    return block;
+}
+
 /**
  * @section Thread-safe block queue functions
  */
@@ -488,23 +499,27 @@ void block_FifoRelease( block_fifo_t *p_fifo )
 
 void block_FifoEmpty( block_fifo_t *p_fifo )
 {
-    block_t *b;
+    block_t *block;
 
     vlc_mutex_lock( &p_fifo->lock );
-    for( b = p_fifo->p_first; b != NULL; )
+    block = p_fifo->p_first;
+    if (block != NULL)
     {
-        block_t *p_next;
-
-        p_next = b->p_next;
-        block_Release( b );
-        b = p_next;
+        p_fifo->i_depth = p_fifo->i_size = 0;
+        p_fifo->p_first = NULL;
+        p_fifo->pp_last = &p_fifo->p_first;
     }
-
-    p_fifo->i_depth = p_fifo->i_size = 0;
-    p_fifo->p_first = NULL;
-    p_fifo->pp_last = &p_fifo->p_first;
     vlc_cond_broadcast( &p_fifo->wait_room );
     vlc_mutex_unlock( &p_fifo->lock );
+
+    while (block != NULL)
+    {
+        block_t *buf;
+
+        buf = block->p_next;
+        block_Release (block);
+        block = buf;
+    }
 }
 
 /**
@@ -542,25 +557,29 @@ void block_FifoPace (block_fifo_t *fifo, size_t max_depth, size_t max_size)
  * Immediately queue one block at the end of a FIFO.
  * @param fifo queue
  * @param block head of a block list to queue (may be NULL)
+ * @return total number of bytes appended to the queue
  */
 size_t block_FifoPut( block_fifo_t *p_fifo, block_t *p_block )
 {
-    size_t i_size = 0;
-    vlc_mutex_lock( &p_fifo->lock );
+    size_t i_size = 0, i_depth = 0;
+    block_t *p_last;
 
-    while (p_block != NULL)
+    if (p_block == NULL)
+        return 0;
+    for (p_last = p_block; ; p_last = p_last->p_next)
     {
-        i_size += p_block->i_buffer;
-
-        *p_fifo->pp_last = p_block;
-        p_fifo->pp_last = &p_block->p_next;
-        p_fifo->i_depth++;
-        p_fifo->i_size += p_block->i_buffer;
-
-        p_block = p_block->p_next;
+        i_size += p_last->i_buffer;
+        i_depth++;
+        if (!p_last->p_next)
+            break;
     }
 
-    /* We queued one block: wake up one read-waiting thread */
+    vlc_mutex_lock (&p_fifo->lock);
+    *p_fifo->pp_last = p_block;
+    p_fifo->pp_last = &p_last->p_next;
+    p_fifo->i_depth += i_depth;
+    p_fifo->i_size += i_size;
+    /* We queued at least one block: wake up one read-waiting thread */
     vlc_cond_signal( &p_fifo->wait );
     vlc_mutex_unlock( &p_fifo->lock );
 
@@ -576,6 +595,12 @@ void block_FifoWake( block_fifo_t *p_fifo )
     vlc_mutex_unlock( &p_fifo->lock );
 }
 
+/**
+ * Dequeue the first block from the FIFO. If necessary, wait until there is
+ * one block in the queue. This function is (always) cancellation point.
+ *
+ * @return a valid block, or NULL if block_FifoWake() was called.
+ */
 block_t *block_FifoGet( block_fifo_t *p_fifo )
 {
     block_t *b;
@@ -618,6 +643,17 @@ block_t *block_FifoGet( block_fifo_t *p_fifo )
     return b;
 }
 
+/**
+ * Peeks the first block in the FIFO.
+ * If necessary, wait until there is one block.
+ * This function is (always) a cancellation point.
+ *
+ * @warning This function leaves the block in the FIFO.
+ * You need to protect against concurrent threads who could dequeue the block.
+ * Preferrably, there should be only one thread reading from the FIFO.
+ *
+ * @return a valid block.
+ */
 block_t *block_FifoShow( block_fifo_t *p_fifo )
 {
     block_t *b;