[Ffmpeg-devel] Re: [Patch] aligned av_realloc

Hervé W. H.O.W.aka.V+ffmpeg
Sat Aug 5 20:37:34 CEST 2006


On 21/07/06, Herv? W. <H.O.W.aka.V+ffmpeg at gmail.com> wrote:
> Hi,

again :-)

> On 30/06/06, Herv? W. wrote:
> > The changes:
> > for the case memalign-hack:
> > *changed the type of 'diff' from int to long. In this patch diff gets
> > used in exactly the same way as in av_malloc and per r4911: "long is
> > better than int for pointer differences"
> >
> > *ptr is reallocated. If the data isn't aligned, it gets moved in the
> > allocated space, and diff is updated.
> >
> > with memalign:
> > *memalign is called, the original data is copied and the old ptr is
> > av_free'd.
>
> [...]
>
> > without hack or memalign:
> > *as regular realloc. The memalign hack isn't needed (or wanted), nor
> > is memalign, therefore malloc is aligned on 16 (or does not need to
> > be?) and, presumably, the same applies to realloc.
>
> The previous patch had some mistakes.

Less comments in this patch.
Any comment whatsoever on the patch would be appreciated.

Thanks.
-V
-------------- next part --------------
Index: libavutil/mem.c
===================================================================
--- libavutil/mem.c	(revision 5936)
+++ libavutil/mem.c	(working copy)
@@ -101,8 +101,9 @@
  */
 void *av_realloc(void *ptr, unsigned int size)
 {
+    void *old_ptr;
 #ifdef MEMALIGN_HACK
-    int diff;
+    long  diff;
 #endif
 
     /* let's disallow possible ambiguous cases */
@@ -110,10 +111,51 @@
         return NULL;
 
 #ifdef MEMALIGN_HACK
-    //FIXME this isn't aligned correctly, though it probably isn't needed
+    /* this should now be aligned correctly to 16 */
     if(!ptr) return av_malloc(size);
     diff= ((char*)ptr)[-1];
-    return realloc(ptr - diff, size + diff) + diff;
+    old_ptr = ptr;
+    ptr -= diff;
+
+    ptr = realloc(ptr, size+16);
+    if(!ptr)
+    {
+        ptr = old_ptr;
+        return NULL;
+    }
+    if( ( ((-(long)ptr - 1)&15) + 1) == diff )
+        return (ptr += diff);
+
+    old_ptr = ptr + diff;   /* old_ptr points to the start of the (not aligned) data */
+    diff= ((-(long)ptr - 1)&15) + 1;
+    ptr += diff;            /* ptr points to where the start of the (aligned) data will be*/
+
+    memmove(ptr, old_ptr, size);
+    ((char*)ptr)[-1]= diff;
+    return ptr;
+#elif defined (HAVE_MEMALIGN)
+    old_ptr = ptr;
+
+    ptr = realloc(ptr, size);
+    if(!ptr)
+    {
+        ptr = old_ptr;
+        return NULL;
+    }
+    if( !(((long)ptr)&15) )
+        return (ptr);
+
+    old_ptr = ptr;
+    ptr = memalign(16,size);
+    if(!ptr)
+    {
+        ptr = old_ptr;
+        return NULL;
+    }
+    memcpy(ptr, old_ptr, size);
+
+    av_free(old_ptr);
+    return ptr;
 #else
     return realloc(ptr, size);
 #endif



More information about the ffmpeg-devel mailing list