From: Mingke Wang <mingke.wang@freescale.com>
Date: Fri, 16 Oct 2015 19:31:32 +0800
Subject: [PATCH] basetextoverlay: make memory copy when video buffer's memory
 is ready only

1. since gst_buffer_make_writable just lookup the refcount to determine if
   a buffer is writable, and it will use _gst_buffer_copy() which don't
   perform a deep memory copy even if the flag of a memory is set to
   GST_MEMORY_FLAG_READONLY. So, we detect the memory flag and use
   gst_buffer_copy_region with GST_BUFFER_COPY_DEEP parameter to perform
   deep memory copy. if the allocator of a memory don't support mem_copy
   interface, the it will return NULL, if this case, we can use
   gst_buffer_make_writable() to get a shared memory buffer or the orignal
   buffer if the buffer's refcount is 1.

Signed-off-by: Mingke Wang <mingke.wang@freescale.com>
Signed-off-by: Lyon Wang <lyon.wang@freescale.com>
---
 ext/pango/gstbasetextoverlay.c | 32 ++++++++++++++++++++++++++++++--
 1 file changed, 30 insertions(+), 2 deletions(-)
 mode change 100644 => 100755 ext/pango/gstbasetextoverlay.c

diff --git a/ext/pango/gstbasetextoverlay.c b/ext/pango/gstbasetextoverlay.c
old mode 100644
new mode 100755
index e3de7c1eaa1d..50981a77c0c9
--- a/ext/pango/gstbasetextoverlay.c
+++ b/ext/pango/gstbasetextoverlay.c
@@ -2220,16 +2220,44 @@ gst_base_text_overlay_push_frame (GstBaseTextOverlay * overlay,
   if (gst_pad_check_reconfigure (overlay->srcpad))
     gst_base_text_overlay_negotiate (overlay, NULL);
 
-  video_frame = gst_buffer_make_writable (video_frame);
-
   if (overlay->attach_compo_to_buffer) {
     GST_DEBUG_OBJECT (overlay, "Attaching text overlay image to video buffer");
+    video_frame = gst_buffer_make_writable (video_frame);
     gst_buffer_add_video_overlay_composition_meta (video_frame,
         overlay->composition);
     /* FIXME: emulate shaded background box if want_shading=true */
     goto done;
   }
 
+  gint idx = 0;
+  gboolean mem_rdonly = FALSE;
+  GstMemory *mem;
+
+  while (mem = gst_buffer_get_memory(video_frame, idx++)) {
+    if (GST_MEMORY_IS_READONLY(mem)) {
+      gst_memory_unref (mem);
+      mem_rdonly = TRUE;
+      break;
+    }
+    gst_memory_unref (mem);
+  }
+
+  if (mem_rdonly) {
+    GstBuffer *new_buf = gst_buffer_copy_region (video_frame,
+        GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1);
+
+    if (!new_buf) {
+      GST_WARNING_OBJECT(overlay,
+                "buffer memory read only, but copy memory failed");
+      goto done;
+    } else {
+      gst_buffer_unref (video_frame);
+      video_frame = new_buf;
+    }
+  } else {
+    video_frame = gst_buffer_make_writable (video_frame);
+  }
+
   if (!gst_video_frame_map (&frame, &overlay->info, video_frame,
           GST_MAP_READWRITE))
     goto invalid_frame;
