diff --git a/gst/mpegtsmux/tsmux/tsmux.c b/gst/mpegtsmux/tsmux/tsmux.c index 638de15aae..ee2870498e 100644 --- a/gst/mpegtsmux/tsmux/tsmux.c +++ b/gst/mpegtsmux/tsmux/tsmux.c @@ -853,6 +853,7 @@ tsmux_section_write_packet (GstMpegtsSectionType * type, gsize data_size = 0; gsize payload_written; guint len = 0, offset = 0, payload_len = 0; + guint extra_alloc_bytes = 0; g_return_val_if_fail (section != NULL, FALSE); g_return_val_if_fail (mux != NULL, FALSE); @@ -907,12 +908,35 @@ tsmux_section_write_packet (GstMpegtsSectionType * type, TS_DEBUG ("Creating packet buffer at offset " "%" G_GSIZE_FORMAT " with length %u", payload_written, payload_len); + /* If in M2TS mode, we will need to resize to 4 bytes after the end + of the buffer. For performance reasons, we will now try to include + 4 extra bytes from the source buffer, then resize down, to avoid + having an extra 4 byte GstMemory appended. If the source buffer + does not have enough data for this, a new GstMemory will be used */ + if (gst_buffer_get_size (section_buffer) - (payload_written + + payload_len) >= 4) { + /* enough space */ + extra_alloc_bytes = 4; + } packet_buffer = gst_buffer_copy_region (section_buffer, GST_BUFFER_COPY_ALL, - payload_written, payload_len); + payload_written, payload_len + extra_alloc_bytes); /* Prepend the header to the section data */ gst_buffer_prepend_memory (packet_buffer, mem); + /* add an extra 4 bytes if it could not be reserved already */ + if (extra_alloc_bytes == 4) { + /* we allocated those already, resize */ + gst_buffer_set_size (packet_buffer, + gst_buffer_get_size (packet_buffer) - extra_alloc_bytes); + } else { + void *ptr = g_malloc (4); + GstMemory *extra = + gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, ptr, 4, 0, 0, ptr, + g_free); + gst_buffer_append_memory (packet_buffer, extra); + } + TS_DEBUG ("Writing %d bytes to section. %d bytes remaining", len, section->pi.stream_avail - len);