buffer: Free memory before meta.

Followup to "Add GstParentBufferMeta to copied buffer sharing memory",
which is a workaround to design issues in NXP's vpudec. There are
cases where vpudec will still see new buffers coming out of its buffer
pool while it's running, which causes it to error out. One such
case is

vpudec ! glupload ! tee name=t
  t. ! queue leaky=downstream ! ...
  t. ! sink

When the queue leaks a buffer it makes the next buffer writable to
mark it DISCONT. If the buffer is also in use elsewhere in the tee
a copy of the buffer will be made and the original memories attached.
When original returns to the pool and copy is still alive pool will
discard the buffer as memory isn't considered writable. Pool instead
allocates a new buffer for vpudec mid operation, which it's not
designed to handle and it falls over. Fixing vpudec is non-trivial,
instead make sure that any buffer copies outlives the original
and that we free memories before the metas that keeps the original
alive.

This is a NXP specific workaround and is not suitable for upstream.

Change-Id: I6bfbc5cc45342b79c1deddb2f416f823090806d1
diff --git a/gst/gstbuffer.c b/gst/gstbuffer.c
index d0f9c6d..0a8f749 100644
--- a/gst/gstbuffer.c
+++ b/gst/gstbuffer.c
@@ -755,6 +755,17 @@
 
   GST_CAT_LOG (GST_CAT_BUFFER, "finalize %p", buffer);
 
+  /* get the size, when unreffing the memory, we could also unref the buffer
+   * itself */
+  msize = GST_BUFFER_SLICE_SIZE (buffer);
+
+  /* free our memory */
+  len = GST_BUFFER_MEM_LEN (buffer);
+  for (i = 0; i < len; i++) {
+    gst_memory_unlock (GST_BUFFER_MEM_PTR (buffer, i), GST_LOCK_FLAG_EXCLUSIVE);
+    gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
+  }
+
   /* free metadata */
   for (walk = GST_BUFFER_META (buffer); walk; walk = next) {
     GstMeta *meta = &walk->meta;
@@ -769,17 +780,6 @@
     g_slice_free1 (ITEM_SIZE (info), walk);
   }
 
-  /* get the size, when unreffing the memory, we could also unref the buffer
-   * itself */
-  msize = GST_BUFFER_SLICE_SIZE (buffer);
-
-  /* free our memory */
-  len = GST_BUFFER_MEM_LEN (buffer);
-  for (i = 0; i < len; i++) {
-    gst_memory_unlock (GST_BUFFER_MEM_PTR (buffer, i), GST_LOCK_FLAG_EXCLUSIVE);
-    gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
-  }
-
   /* we set msize to 0 when the buffer is part of the memory block */
   if (msize) {
 #ifdef USE_POISONING