[Spice-devel,v7,09/23] server: Avoid copying the input frame in the GStreamer encoder

Submitted by Francois Gouget on Dec. 16, 2015, 3:18 p.m.

Details

Message ID alpine.DEB.2.20.1512161124390.16981@amboise
State New
Headers show
Series "Add GStreamer support for video streaming" ( rev: 1 ) in Spice

Not browsing as part of any series.

Commit Message

Francois Gouget Dec. 16, 2015, 3:18 p.m.
This relies on the GStreamer buffer's lifetime being short enough which
it is because:
 - We encode frames one by one.
 - For all encoders but MJPEG, the first element of the pipeline will
   convert the bitmap to another image format which entails copying it.
   So by the time the encoder starts its work, this buffer will not be
   needed anymore.
 - The MJPEG encoder does not perform inter-frame compression and thus
   does not need to keep hold of this buffer once it has processed it.

Note that we can only avoid copies for the first 1 Mpixels or so.
That's because Spice splits larger frames into more chunks than we can
fit GstMemory fragments in a GStreamer buffer. So if there are more
pixels we will avoid copies for the first 3840 KB and copy the rest.

Signed-off-by: Francois Gouget <fgouget@codeweavers.com>
---
 server/gstreamer-encoder.c | 171 ++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 152 insertions(+), 19 deletions(-)

Patch hide | download patch | download mbox

diff --git a/server/gstreamer-encoder.c b/server/gstreamer-encoder.c
index c0991d5..d74c8f7 100644
--- a/server/gstreamer-encoder.c
+++ b/server/gstreamer-encoder.c
@@ -30,6 +30,8 @@ 
 
 #define SPICE_GST_DEFAULT_FPS 30
 
+#define DO_ZERO_COPY
+
 
 typedef struct {
     SpiceBitmapFmt spice_format;
@@ -73,6 +75,11 @@  typedef struct SpiceGstEncoder {
     /* If src_caps is NULL the pipeline has not been configured yet. */
     GstCaps *src_caps;
 
+#ifdef DO_ZERO_COPY
+    /* Set to TRUE until GStreamer no longer needs the raw bitmap buffer. */
+    gboolean needs_bitmap;
+#endif
+
     /* The frame counter for GStreamer buffers */
     uint32_t frame;
 
@@ -284,6 +291,17 @@  static void reconfigure_pipeline(SpiceGstEncoder *encoder)
     }
 }
 
+static int is_chunk_padded(const SpiceBitmap *bitmap, uint32_t index)
+{
+    SpiceChunks *chunks = bitmap->data;
+    if (chunks->chunk[index].len % bitmap->stride != 0) {
+        spice_warning("chunk %d/%d is padded",
+                      index, chunks->num_chunks);
+        return TRUE;
+    }
+    return FALSE;
+}
+
 /* A helper for push_raw_frame() */
 static inline int line_copy(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap,
                             uint32_t chunk_offset, uint32_t stream_stride,
@@ -297,10 +315,7 @@  static inline int line_copy(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap,
           * time around.
           */
          while (chunk_offset >= chunks->chunk[chunk_index].len) {
-             /* Make sure that the chunk is not padded */
-             if (chunks->chunk[chunk_index].len % bitmap->stride != 0) {
-                 spice_warning("chunk %d/%d is padded, cannot copy line %d/%d",
-                               chunk_index, chunks->num_chunks, l, height);
+             if (is_chunk_padded(bitmap, chunk_index)) {
                  return FALSE;
              }
              chunk_offset -= chunks->chunk[chunk_index].len;
@@ -317,18 +332,83 @@  static inline int line_copy(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap,
      return TRUE;
 }
 
+#ifdef DO_ZERO_COPY
+/* A helper for zero_copy() */
+static void unref_bitmap(gpointer mem)
+{
+    SpiceGstEncoder *encoder = (SpiceGstEncoder*)mem;
+    encoder->needs_bitmap = FALSE;
+}
+
+/* A helper for push_raw_frame() */
+static inline int zero_copy(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap,
+                            GstBuffer *buffer, uint32_t *chunk_index,
+                            uint32_t *chunk_offset, uint32_t *len)
+{
+    /* We cannot control the lifetime of the bitmap but we can wrap it in
+     * the buffer anyway because:
+     * - Before returning from gst_encoder_encode_frame() we wait for the
+     *   pipeline to have converted this frame into a compressed buffer.
+     *   So it has to have gone through the frame at least once.
+     * - For all encoders but MJPEG, the first element of the pipeline will
+     *   convert the bitmap to another image format which entails copying
+     *   it. So by the time the encoder starts its work, this buffer will
+     *   not be needed anymore.
+     * - The MJPEG encoder does not perform inter-frame compression and thus
+     *   does not need to keep hold of this buffer once it has processed it.
+     * encoder->needs_bitmap lets us verify that these conditions still hold
+     * true through an assert.
+     */
+    SpiceChunks *chunks = bitmap->data;
+    while (*chunk_offset >= chunks->chunk[*chunk_index].len) {
+        if (is_chunk_padded(bitmap, *chunk_index)) {
+            return FALSE;
+        }
+        *chunk_offset -= chunks->chunk[*chunk_index].len;
+        (*chunk_index)++;
+    }
+
+    int max_mem = gst_buffer_get_max_memory();
+    if (chunks->num_chunks - *chunk_index > max_mem) {
+        /* There are more chunks than we can fit memory objects in a
+         * buffer. This will cause the buffer to merge memory objects to
+         * fit the extra chunks, which means doing wasteful memory copies.
+         * So use the zero-copy approach for the first max_mem-1 chunks, and
+         * let push_raw_frame() deal with the rest.
+         */
+        max_mem = *chunk_index + max_mem - 1;
+    } else {
+        max_mem = chunks->num_chunks;
+    }
+
+    while (*len && *chunk_index < max_mem) {
+        if (is_chunk_padded(bitmap, *chunk_index)) {
+            return FALSE;
+        }
+        uint32_t thislen = MIN(chunks->chunk[*chunk_index].len - *chunk_offset, *len);
+        GstMemory *mem = gst_memory_new_wrapped(GST_MEMORY_FLAG_READONLY,
+                                                chunks->chunk[*chunk_index].data,
+                                                chunks->chunk[*chunk_index].len,
+                                                *chunk_offset, thislen,
+                                                encoder, &unref_bitmap);
+        gst_buffer_append_memory(buffer, mem);
+        *len -= thislen;
+        *chunk_offset = 0;
+        (*chunk_index)++;
+    }
+    encoder->needs_bitmap = TRUE;
+    return TRUE;
+}
+#endif
+
 /* A helper for push_raw_frame() */
 static inline int chunk_copy(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap,
-                             uint32_t chunk_offset, uint32_t len, uint8_t *dst)
+                             uint32_t chunk_offset, uint32_t chunk_index,
+                             uint32_t len, uint8_t *dst)
 {
     SpiceChunks *chunks = bitmap->data;
-    uint32_t chunk_index = 0;
-    /* We can copy the bitmap chunk by chunk */
     while (len && chunk_index < chunks->num_chunks) {
-        /* Make sure that the chunk is not padded */
-        if (chunks->chunk[chunk_index].len % bitmap->stride != 0) {
-            spice_warning("chunk %d/%d is padded, cannot copy it",
-                          chunk_index, chunks->num_chunks);
+        if (is_chunk_padded(bitmap, chunk_index)) {
             return FALSE;
         }
         if (chunk_offset >= chunks->chunk[chunk_index].len) {
@@ -349,6 +429,23 @@  static inline int chunk_copy(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap
     return TRUE;
 }
 
+/* A helper for push_raw_frame() */
+static uint8_t *allocate_and_map_memory(gsize size, GstMapInfo *map, GstBuffer *buffer)
+{
+    GstMemory *mem = gst_allocator_alloc(NULL, size, NULL);
+    if (!mem) {
+        gst_buffer_unref(buffer);
+        return NULL;
+    }
+    if (!gst_memory_map(mem, map, GST_MAP_WRITE))
+    {
+        gst_memory_unref(mem);
+        gst_buffer_unref(buffer);
+        return NULL;
+    }
+    return map->data;
+}
+
 /* A helper for spice_gst_encoder_encode_frame() */
 static int push_raw_frame(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap,
                           const SpiceRect *src, int top_down)
@@ -356,10 +453,9 @@  static int push_raw_frame(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap,
     const uint32_t height = src->bottom - src->top;
     const uint32_t stream_stride = (src->right - src->left) * encoder->format->bpp / 8;
     uint32_t len = stream_stride * height;
-    GstBuffer *buffer = gst_buffer_new_and_alloc(len);
-    GstMapInfo map;
-    gst_buffer_map(buffer, &map, GST_MAP_WRITE);
-    uint8_t *dst = map.data;
+    GstBuffer *buffer = gst_buffer_new();
+    /* TODO Use GST_MAP_INFO_INIT once GStreamer 1.4.5 is no longer relevant */
+    GstMapInfo map = { .memory = NULL };
 
     /* Note that we should not reorder the lines, even if top_down is false.
      * It just changes the number of lines to skip at the start of the bitmap.
@@ -371,20 +467,50 @@  static int push_raw_frame(SpiceGstEncoder *encoder, const SpiceBitmap *bitmap,
         /* We have to do a line-by-line copy because for each we have to leave
          * out pixels on the left or right.
          */
+        uint8_t *dst = allocate_and_map_memory(len, &map, buffer);
+        if (!dst) {
+            return VIDEO_ENCODER_FRAME_UNSUPPORTED;
+        }
+
         chunk_offset += src->left * encoder->format->bpp / 8;
         if (!line_copy(encoder, bitmap, chunk_offset, stream_stride, height, dst)) {
-            gst_buffer_unmap(buffer, &map);
+            gst_memory_unmap(map.memory, &map);
+            gst_memory_unref(map.memory);
             gst_buffer_unref(buffer);
             return VIDEO_ENCODER_FRAME_UNSUPPORTED;
         }
     } else {
-        if (!chunk_copy(encoder, bitmap, chunk_offset, len, dst)) {
-            gst_buffer_unmap(buffer, &map);
+        uint32_t chunk_index = 0;
+        /* We can copy the bitmap chunk by chunk */
+#ifdef DO_ZERO_COPY
+        if (!zero_copy(encoder, bitmap, buffer, &chunk_index, &chunk_offset, &len)) {
             gst_buffer_unref(buffer);
             return VIDEO_ENCODER_FRAME_UNSUPPORTED;
         }
+        /* len now contains the remaining number of bytes to copy.
+         * However we must avoid any write to the GstBuffer object as it would
+         * cause a copy of the read-only memory objects we just added.
+         * Fortunately we can append extra writable memory objects instead.
+         */
+#endif
+
+        if (len) {
+            uint8_t *dst = allocate_and_map_memory(len, &map, buffer);
+            if (!dst) {
+                return VIDEO_ENCODER_FRAME_UNSUPPORTED;
+            }
+            if (!chunk_copy(encoder, bitmap, chunk_index, chunk_offset, len, dst)) {
+                gst_memory_unmap(map.memory, &map);
+                gst_memory_unref(map.memory);
+                gst_buffer_unref(buffer);
+                return VIDEO_ENCODER_FRAME_UNSUPPORTED;
+            }
+        }
+    }
+    if (map.memory) {
+        gst_memory_unmap(map.memory, &map);
+        gst_buffer_append_memory(buffer, map.memory);
     }
-    gst_buffer_unmap(buffer, &map);
     GST_BUFFER_OFFSET(buffer) = encoder->frame++;
 
     GstFlowReturn ret = gst_app_src_push_buffer(encoder->appsrc, buffer);
@@ -463,6 +589,13 @@  static int spice_gst_encoder_encode_frame(VideoEncoder *video_encoder,
     int rc = push_raw_frame(encoder, bitmap, src, top_down);
     if (rc == VIDEO_ENCODER_FRAME_ENCODE_DONE) {
         rc = pull_compressed_buffer(encoder, video_buffer);
+#ifdef DO_ZERO_COPY
+        /* GStreamer should have released the source frame buffer by now */
+        if (encoder->needs_bitmap) {
+            spice_warning("source bitmap is still needed after being encoded. Expect trouble");
+            encoder->needs_bitmap = FALSE;
+        }
+#endif
     }
     return rc;
 }