transcodebin: Create the decodebin in _init
[platform/upstream/gstreamer.git] / gst / mpegtsmux / gstbasetsmux.c
1 /*
2  * Copyright 2006, 2007, 2008, 2009, 2010 Fluendo S.A.
3  *  Authors: Jan Schmidt <jan@fluendo.com>
4  *           Kapil Agrawal <kapil@fluendo.com>
5  *           Julien Moutte <julien@fluendo.com>
6  *
7  * Copyright (C) 2011 Jan Schmidt <thaytan@noraisin.net>
8  *
9  * This library is licensed under 4 different licenses and you
10  * can choose to use it under the terms of any one of them. The
11  * four licenses are the MPL 1.1, the LGPL, the GPL and the MIT
12  * license.
13  *
14  * MPL:
15  *
16  * The contents of this file are subject to the Mozilla Public License
17  * Version 1.1 (the "License"); you may not use this file except in
18  * compliance with the License. You may obtain a copy of the License at
19  * http://www.mozilla.org/MPL/.
20  *
21  * Software distributed under the License is distributed on an "AS IS"
22  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
23  * License for the specific language governing rights and limitations
24  * under the License.
25  *
26  * LGPL:
27  *
28  * This library is free software; you can redistribute it and/or
29  * modify it under the terms of the GNU Library General Public
30  * License as published by the Free Software Foundation; either
31  * version 2 of the License, or (at your option) any later version.
32  *
33  * This library is distributed in the hope that it will be useful,
34  * but WITHOUT ANY WARRANTY; without even the implied warranty of
35  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
36  * Library General Public License for more details.
37  *
38  * You should have received a copy of the GNU Library General Public
39  * License along with this library; if not, write to the
40  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
41  * Boston, MA 02110-1301, USA.
42  *
43  * GPL:
44  *
45  * This program is free software; you can redistribute it and/or modify
46  * it under the terms of the GNU General Public License as published by
47  * the Free Software Foundation; either version 2 of the License, or
48  * (at your option) any later version.
49  *
50  * This program is distributed in the hope that it will be useful,
51  * but WITHOUT ANY WARRANTY; without even the implied warranty of
52  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
53  * GNU General Public License for more details.
54  *
55  * You should have received a copy of the GNU General Public License
56  * along with this program; if not, write to the Free Software
57  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
58  *
59  * MIT:
60  *
61  * Unless otherwise indicated, Source Code is licensed under MIT license.
62  * See further explanation attached in License Statement (distributed in the file
63  * LICENSE).
64  *
65  * Permission is hereby granted, free of charge, to any person obtaining a copy of
66  * this software and associated documentation files (the "Software"), to deal in
67  * the Software without restriction, including without limitation the rights to
68  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
69  * of the Software, and to permit persons to whom the Software is furnished to do
70  * so, subject to the following conditions:
71  *
72  * The above copyright notice and this permission notice shall be included in all
73  * copies or substantial portions of the Software.
74  *
75  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
76  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
77  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
78  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
79  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
80  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
81  * SOFTWARE.
82  *
83  */
84
85 #include <stdio.h>
86 #include <string.h>
87
88 #include <gst/tag/tag.h>
89 #include <gst/video/video.h>
90 #include <gst/mpegts/mpegts.h>
91 #include <gst/pbutils/pbutils.h>
92 #include <gst/videoparsers/gstjpeg2000parse.h>
93 #include <gst/video/video-color.h>
94
95 #include "gstbasetsmux.h"
96 #include "gstbasetsmuxaac.h"
97 #include "gstbasetsmuxttxt.h"
98 #include "gstbasetsmuxopus.h"
99 #include "gstbasetsmuxjpeg2000.h"
100
101 GST_DEBUG_CATEGORY (gst_base_ts_mux_debug);
102 #define GST_CAT_DEFAULT gst_base_ts_mux_debug
103
104 /* GstBaseTsMuxPad */
105
106 G_DEFINE_TYPE (GstBaseTsMuxPad, gst_base_ts_mux_pad, GST_TYPE_AGGREGATOR_PAD);
107
108 /* Internals */
109
110 static void
111 gst_base_ts_mux_pad_reset (GstBaseTsMuxPad * pad)
112 {
113   pad->dts = GST_CLOCK_STIME_NONE;
114   pad->prog_id = -1;
115
116   if (pad->free_func)
117     pad->free_func (pad->prepare_data);
118   pad->prepare_data = NULL;
119   pad->prepare_func = NULL;
120   pad->free_func = NULL;
121
122   if (pad->codec_data)
123     gst_buffer_replace (&pad->codec_data, NULL);
124
125   /* reference owned elsewhere */
126   pad->stream = NULL;
127   pad->prog = NULL;
128
129   if (pad->language) {
130     g_free (pad->language);
131     pad->language = NULL;
132   }
133 }
134
135 /* GstAggregatorPad implementation */
136
137 static GstFlowReturn
138 gst_base_ts_mux_pad_flush (GstAggregatorPad * agg_pad, GstAggregator * agg)
139 {
140   GList *cur;
141   GstBaseTsMux *mux = GST_BASE_TS_MUX (agg);
142
143   /* Send initial segments again after a flush-stop, and also resend the
144    * header sections */
145   mux->first = TRUE;
146
147   /* output PAT, SI tables */
148   tsmux_resend_pat (mux->tsmux);
149   tsmux_resend_si (mux->tsmux);
150
151   /* output PMT for each program */
152   for (cur = mux->tsmux->programs; cur; cur = cur->next) {
153     TsMuxProgram *program = (TsMuxProgram *) cur->data;
154
155     tsmux_resend_pmt (program);
156   }
157
158   return GST_FLOW_OK;
159 }
160
161 /* GObject implementation */
162
163 static void
164 gst_base_ts_mux_pad_dispose (GObject * obj)
165 {
166   GstBaseTsMuxPad *ts_pad = GST_BASE_TS_MUX_PAD (obj);
167
168   gst_base_ts_mux_pad_reset (ts_pad);
169
170   G_OBJECT_CLASS (gst_base_ts_mux_pad_parent_class)->dispose (obj);
171 }
172
173 static void
174 gst_base_ts_mux_pad_class_init (GstBaseTsMuxPadClass * klass)
175 {
176   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
177   GstAggregatorPadClass *gstaggpad_class = GST_AGGREGATOR_PAD_CLASS (klass);
178
179   gobject_class->dispose = gst_base_ts_mux_pad_dispose;
180   gstaggpad_class->flush = gst_base_ts_mux_pad_flush;
181
182   gst_type_mark_as_plugin_api (GST_TYPE_BASE_TS_MUX, 0);
183 }
184
185 static void
186 gst_base_ts_mux_pad_init (GstBaseTsMuxPad * vaggpad)
187 {
188 }
189
190 /* GstBaseTsMux */
191
192 enum
193 {
194   PROP_0,
195   PROP_PROG_MAP,
196   PROP_PAT_INTERVAL,
197   PROP_PMT_INTERVAL,
198   PROP_ALIGNMENT,
199   PROP_SI_INTERVAL,
200   PROP_BITRATE,
201   PROP_PCR_INTERVAL,
202   PROP_SCTE_35_PID,
203   PROP_SCTE_35_NULL_INTERVAL
204 };
205
206 #define DEFAULT_SCTE_35_PID 0
207
208 #define BASETSMUX_DEFAULT_ALIGNMENT    -1
209
210 #define CLOCK_BASE 9LL
211 #define CLOCK_FREQ (CLOCK_BASE * 10000) /* 90 kHz PTS clock */
212 #define CLOCK_FREQ_SCR (CLOCK_FREQ * 300)       /* 27 MHz SCR clock */
213
214 #define GSTTIME_TO_MPEGTIME(time) \
215     (((time) > 0 ? (gint64) 1 : (gint64) -1) * \
216     (gint64) gst_util_uint64_scale (ABS(time), CLOCK_BASE, GST_MSECOND/10))
217 /* 27 MHz SCR conversions: */
218 #define MPEG_SYS_TIME_TO_GSTTIME(time) (gst_util_uint64_scale ((time), \
219                         GST_USECOND, CLOCK_FREQ_SCR / 1000000))
220 #define GSTTIME_TO_MPEG_SYS_TIME(time) (gst_util_uint64_scale ((time), \
221                         CLOCK_FREQ_SCR / 1000000, GST_USECOND))
222
223 #define DEFAULT_PROG_ID 0
224
225 static GstStaticPadTemplate gst_base_ts_mux_src_factory =
226 GST_STATIC_PAD_TEMPLATE ("src",
227     GST_PAD_SRC,
228     GST_PAD_ALWAYS,
229     GST_STATIC_CAPS ("video/mpegts, "
230         "systemstream = (boolean) true, " "packetsize = (int) { 188, 192} ")
231     );
232
233 typedef struct
234 {
235   GstMapInfo map_info;
236   GstBuffer *buffer;
237 } StreamData;
238
239 G_DEFINE_TYPE (GstBaseTsMux, gst_base_ts_mux, GST_TYPE_AGGREGATOR);
240
241 /* Internals */
242
243 /* Takes over the ref on the buffer */
244 static StreamData *
245 stream_data_new (GstBuffer * buffer)
246 {
247   StreamData *res = g_new (StreamData, 1);
248   res->buffer = buffer;
249   gst_buffer_map (buffer, &(res->map_info), GST_MAP_READ);
250
251   return res;
252 }
253
254 static void
255 stream_data_free (StreamData * data)
256 {
257   if (data) {
258     gst_buffer_unmap (data->buffer, &data->map_info);
259     gst_buffer_unref (data->buffer);
260     g_free (data);
261   }
262 }
263
264 #define parent_class gst_base_ts_mux_parent_class
265
266 static void
267 gst_base_ts_mux_set_header_on_caps (GstBaseTsMux * mux)
268 {
269   GstBuffer *buf;
270   GstStructure *structure;
271   GValue array = { 0 };
272   GValue value = { 0 };
273   GstCaps *caps;
274
275   caps =
276       gst_caps_make_writable (gst_pad_get_current_caps (GST_AGGREGATOR_SRC_PAD
277           (mux)));
278   structure = gst_caps_get_structure (caps, 0);
279
280   g_value_init (&array, GST_TYPE_ARRAY);
281
282   GST_LOG_OBJECT (mux, "setting %u packets into streamheader",
283       g_queue_get_length (&mux->streamheader));
284
285   while ((buf = GST_BUFFER (g_queue_pop_head (&mux->streamheader)))) {
286     g_value_init (&value, GST_TYPE_BUFFER);
287     gst_value_take_buffer (&value, buf);
288     gst_value_array_append_value (&array, &value);
289     g_value_unset (&value);
290   }
291
292   gst_structure_set_value (structure, "streamheader", &array);
293   gst_aggregator_set_src_caps (GST_AGGREGATOR (mux), caps);
294   g_value_unset (&array);
295   gst_caps_unref (caps);
296 }
297
298 static gboolean
299 steal_si_section (GstMpegtsSectionType * type, TsMuxSection * section,
300     TsMux * mux)
301 {
302   g_hash_table_insert (mux->si_sections, type, section);
303
304   return TRUE;
305 }
306
307 static void
308 gst_base_ts_mux_reset (GstBaseTsMux * mux, gboolean alloc)
309 {
310   GstBuffer *buf;
311   GstBaseTsMuxClass *klass = GST_BASE_TS_MUX_GET_CLASS (mux);
312   GHashTable *si_sections = NULL;
313   GList *l;
314
315   mux->first = TRUE;
316   mux->last_flow_ret = GST_FLOW_OK;
317   mux->last_ts = 0;
318   mux->is_delta = TRUE;
319   mux->is_header = FALSE;
320
321   mux->streamheader_sent = FALSE;
322   mux->pending_key_unit_ts = GST_CLOCK_TIME_NONE;
323   gst_event_replace (&mux->force_key_unit_event, NULL);
324
325   if (mux->out_adapter)
326     gst_adapter_clear (mux->out_adapter);
327
328   if (mux->tsmux) {
329     if (mux->tsmux->si_sections)
330       si_sections = g_hash_table_ref (mux->tsmux->si_sections);
331
332     tsmux_free (mux->tsmux);
333     mux->tsmux = NULL;
334   }
335
336   if (mux->programs) {
337     g_hash_table_destroy (mux->programs);
338   }
339   mux->programs = g_hash_table_new (g_direct_hash, g_direct_equal);
340
341   while ((buf = GST_BUFFER (g_queue_pop_head (&mux->streamheader))))
342     gst_buffer_unref (buf);
343
344   gst_event_replace (&mux->force_key_unit_event, NULL);
345   gst_buffer_replace (&mux->out_buffer, NULL);
346
347   GST_OBJECT_LOCK (mux);
348
349   for (l = GST_ELEMENT (mux)->sinkpads; l; l = l->next) {
350     gst_base_ts_mux_pad_reset (GST_BASE_TS_MUX_PAD (l->data));
351   }
352
353   GST_OBJECT_UNLOCK (mux);
354
355   if (alloc) {
356     g_assert (klass->create_ts_mux);
357
358     mux->tsmux = klass->create_ts_mux (mux);
359
360     /* Preserve user-specified sections across resets */
361     if (si_sections)
362       g_hash_table_foreach_steal (si_sections, (GHRFunc) steal_si_section,
363           mux->tsmux);
364   }
365
366   if (si_sections)
367     g_hash_table_unref (si_sections);
368
369   if (klass->reset)
370     klass->reset (mux);
371 }
372
373 static void
374 release_buffer_cb (guint8 * data, void *user_data)
375 {
376   stream_data_free ((StreamData *) user_data);
377 }
378
379 static GstFlowReturn
380 gst_base_ts_mux_create_stream (GstBaseTsMux * mux, GstBaseTsMuxPad * ts_pad)
381 {
382   GstFlowReturn ret = GST_FLOW_ERROR;
383   GstCaps *caps;
384   GstStructure *s;
385   GstPad *pad;
386   guint st = TSMUX_ST_RESERVED;
387   const gchar *mt;
388   const GValue *value = NULL;
389   GstBuffer *codec_data = NULL;
390   guint8 opus_channel_config_code = 0;
391   guint16 profile = GST_JPEG2000_PARSE_PROFILE_NONE;
392   guint8 main_level = 0;
393   guint32 max_rate = 0;
394   guint8 color_spec = 0;
395   j2k_private_data *private_data = NULL;
396   const gchar *stream_format = NULL;
397
398   pad = GST_PAD (ts_pad);
399   caps = gst_pad_get_current_caps (pad);
400   if (caps == NULL)
401     goto not_negotiated;
402
403   GST_DEBUG_OBJECT (pad, "Creating stream with PID 0x%04x for caps %"
404       GST_PTR_FORMAT, ts_pad->pid, caps);
405
406   s = gst_caps_get_structure (caps, 0);
407
408   mt = gst_structure_get_name (s);
409   value = gst_structure_get_value (s, "codec_data");
410   if (value != NULL)
411     codec_data = gst_value_get_buffer (value);
412
413   stream_format = gst_structure_get_string (s, "stream-format");
414
415   if (strcmp (mt, "video/x-dirac") == 0) {
416     st = TSMUX_ST_VIDEO_DIRAC;
417   } else if (strcmp (mt, "audio/x-ac3") == 0) {
418     st = TSMUX_ST_PS_AUDIO_AC3;
419   } else if (strcmp (mt, "audio/x-dts") == 0) {
420     st = TSMUX_ST_PS_AUDIO_DTS;
421   } else if (strcmp (mt, "audio/x-lpcm") == 0) {
422     st = TSMUX_ST_PS_AUDIO_LPCM;
423   } else if (strcmp (mt, "video/x-h264") == 0) {
424     st = TSMUX_ST_VIDEO_H264;
425   } else if (strcmp (mt, "video/x-h265") == 0) {
426     st = TSMUX_ST_VIDEO_HEVC;
427   } else if (strcmp (mt, "audio/mpeg") == 0) {
428     gint mpegversion;
429
430     if (!gst_structure_get_int (s, "mpegversion", &mpegversion)) {
431       GST_ERROR_OBJECT (pad, "caps missing mpegversion");
432       goto not_negotiated;
433     }
434
435     switch (mpegversion) {
436       case 1:{
437         int mpegaudioversion = 1;       /* Assume mpegaudioversion=1 for backwards compatibility */
438         (void) gst_structure_get_int (s, "mpegaudioversion", &mpegaudioversion);
439
440         if (mpegaudioversion == 1)
441           st = TSMUX_ST_AUDIO_MPEG1;
442         else
443           st = TSMUX_ST_AUDIO_MPEG2;
444         break;
445       }
446       case 2:{
447         /* mpegversion=2 in GStreamer refers to MPEG-2 Part 7 audio,  */
448
449         st = TSMUX_ST_AUDIO_AAC;
450
451         /* Check the stream format. If raw, make dummy internal codec data from the caps */
452         if (g_strcmp0 (stream_format, "raw") == 0) {
453           ts_pad->codec_data =
454               gst_base_ts_mux_aac_mpeg2_make_codec_data (mux, caps);
455           ts_pad->prepare_func = gst_base_ts_mux_prepare_aac_mpeg2;
456           if (ts_pad->codec_data == NULL) {
457             GST_ERROR_OBJECT (mux, "Invalid or incomplete caps for MPEG-2 AAC");
458             goto not_negotiated;
459           }
460         }
461         break;
462       }
463       case 4:
464       {
465         st = TSMUX_ST_AUDIO_AAC;
466
467         /* Check the stream format. We need codec_data with RAW streams and mpegversion=4 */
468         if (g_strcmp0 (stream_format, "raw") == 0) {
469           if (codec_data) {
470             GST_DEBUG_OBJECT (pad,
471                 "we have additional codec data (%" G_GSIZE_FORMAT " bytes)",
472                 gst_buffer_get_size (codec_data));
473             ts_pad->codec_data = gst_buffer_ref (codec_data);
474             ts_pad->prepare_func = gst_base_ts_mux_prepare_aac_mpeg4;
475           } else {
476             ts_pad->codec_data = NULL;
477             GST_ERROR_OBJECT (mux, "Need codec_data for raw MPEG-4 AAC");
478             goto not_negotiated;
479           }
480         }
481         break;
482       }
483       default:
484         GST_WARNING_OBJECT (pad, "unsupported mpegversion %d", mpegversion);
485         goto not_negotiated;
486     }
487   } else if (strcmp (mt, "video/mpeg") == 0) {
488     gint mpegversion;
489
490     if (!gst_structure_get_int (s, "mpegversion", &mpegversion)) {
491       GST_ERROR_OBJECT (pad, "caps missing mpegversion");
492       goto not_negotiated;
493     }
494
495     switch (mpegversion) {
496       case 1:
497         st = TSMUX_ST_VIDEO_MPEG1;
498         break;
499       case 2:
500         st = TSMUX_ST_VIDEO_MPEG2;
501         break;
502       case 4:
503         st = TSMUX_ST_VIDEO_MPEG4;
504         break;
505       default:
506         GST_WARNING_OBJECT (pad, "unsupported mpegversion %d", mpegversion);
507         goto not_negotiated;
508     }
509   } else if (strcmp (mt, "subpicture/x-dvb") == 0) {
510     st = TSMUX_ST_PS_DVB_SUBPICTURE;
511   } else if (strcmp (mt, "application/x-teletext") == 0) {
512     st = TSMUX_ST_PS_TELETEXT;
513     /* needs a particularly sized layout */
514     ts_pad->prepare_func = gst_base_ts_mux_prepare_teletext;
515   } else if (strcmp (mt, "audio/x-opus") == 0) {
516     guint8 channels, mapping_family, stream_count, coupled_count;
517     guint8 channel_mapping[256];
518
519     if (!gst_codec_utils_opus_parse_caps (caps, NULL, &channels,
520             &mapping_family, &stream_count, &coupled_count, channel_mapping)) {
521       GST_ERROR_OBJECT (pad, "Incomplete Opus caps");
522       goto not_negotiated;
523     }
524
525     if (channels <= 2 && mapping_family == 0) {
526       opus_channel_config_code = channels;
527     } else if (channels == 2 && mapping_family == 255 && stream_count == 1
528         && coupled_count == 1) {
529       /* Dual mono */
530       opus_channel_config_code = 0;
531     } else if (channels >= 2 && channels <= 8 && mapping_family == 1) {
532       static const guint8 coupled_stream_counts[9] = {
533         1, 0, 1, 1, 2, 2, 2, 3, 3
534       };
535       static const guint8 channel_map_a[8][8] = {
536         {0},
537         {0, 1},
538         {0, 2, 1},
539         {0, 1, 2, 3},
540         {0, 4, 1, 2, 3},
541         {0, 4, 1, 2, 3, 5},
542         {0, 4, 1, 2, 3, 5, 6},
543         {0, 6, 1, 2, 3, 4, 5, 7},
544       };
545       static const guint8 channel_map_b[8][8] = {
546         {0},
547         {0, 1},
548         {0, 1, 2},
549         {0, 1, 2, 3},
550         {0, 1, 2, 3, 4},
551         {0, 1, 2, 3, 4, 5},
552         {0, 1, 2, 3, 4, 5, 6},
553         {0, 1, 2, 3, 4, 5, 6, 7},
554       };
555
556       /* Vorbis mapping */
557       if (stream_count == channels - coupled_stream_counts[channels] &&
558           coupled_count == coupled_stream_counts[channels] &&
559           memcmp (channel_mapping, channel_map_a[channels - 1],
560               channels) == 0) {
561         opus_channel_config_code = channels;
562       } else if (stream_count == channels - coupled_stream_counts[channels] &&
563           coupled_count == coupled_stream_counts[channels] &&
564           memcmp (channel_mapping, channel_map_b[channels - 1],
565               channels) == 0) {
566         opus_channel_config_code = channels | 0x80;
567       } else {
568         GST_FIXME_OBJECT (pad, "Opus channel mapping not handled");
569         goto not_negotiated;
570       }
571     }
572
573     st = TSMUX_ST_PS_OPUS;
574     ts_pad->prepare_func = gst_base_ts_mux_prepare_opus;
575   } else if (strcmp (mt, "meta/x-klv") == 0) {
576     st = TSMUX_ST_PS_KLV;
577   } else if (strcmp (mt, "image/x-jpc") == 0) {
578     /*
579      * See this document for more details on standard:
580      *
581      * https://www.itu.int/rec/T-REC-H.222.0-201206-S/en
582      *  Annex S describes J2K details
583      *  Page 104 of this document describes J2k video descriptor
584      */
585
586     const GValue *vProfile = gst_structure_get_value (s, "profile");
587     const GValue *vMainlevel = gst_structure_get_value (s, "main-level");
588     const GValue *vFramerate = gst_structure_get_value (s, "framerate");
589     const GValue *vColorimetry = gst_structure_get_value (s, "colorimetry");
590     private_data = g_new0 (j2k_private_data, 1);
591     /* for now, we relax the condition that profile must exist and equal
592      * GST_JPEG2000_PARSE_PROFILE_BC_SINGLE */
593     if (vProfile) {
594       profile = g_value_get_int (vProfile);
595       if (profile != GST_JPEG2000_PARSE_PROFILE_BC_SINGLE) {
596         GST_LOG_OBJECT (pad, "Invalid JPEG 2000 profile %d", profile);
597         /*goto not_negotiated; */
598       }
599     }
600     /* for now, we will relax the condition that the main level must be present */
601     if (vMainlevel) {
602       main_level = g_value_get_uint (vMainlevel);
603       if (main_level > 11) {
604         GST_ERROR_OBJECT (pad, "Invalid main level %d", main_level);
605         goto not_negotiated;
606       }
607       if (main_level >= 6) {
608         max_rate = 2 ^ (main_level - 6) * 1600 * 1000000;
609       } else {
610         switch (main_level) {
611           case 0:
612           case 1:
613           case 2:
614           case 3:
615             max_rate = 200 * 1000000;
616             break;
617           case 4:
618             max_rate = 400 * 1000000;
619             break;
620           case 5:
621             max_rate = 800 * 1000000;
622             break;
623           default:
624             break;
625         }
626       }
627     } else {
628       /*GST_ERROR_OBJECT (pad, "Missing main level");
629          goto not_negotiated; */
630     }
631     /* We always mux video in J2K-over-MPEG-TS non-interlaced mode */
632     private_data->interlace = FALSE;
633     private_data->den = 0;
634     private_data->num = 0;
635     private_data->max_bitrate = max_rate;
636     private_data->color_spec = 1;
637     /* these two fields are not used, since we always mux as non-interlaced */
638     private_data->Fic = 1;
639     private_data->Fio = 0;
640
641     /* Get Framerate */
642     if (vFramerate != NULL) {
643       /* Data for ELSM header */
644       private_data->num = gst_value_get_fraction_numerator (vFramerate);
645       private_data->den = gst_value_get_fraction_denominator (vFramerate);
646     }
647     /* Get Colorimetry */
648     if (vColorimetry) {
649       const char *colorimetry = g_value_get_string (vColorimetry);
650       color_spec = GST_MPEGTS_JPEG2000_COLORSPEC_SRGB;  /* RGB as default */
651       if (g_str_equal (colorimetry, GST_VIDEO_COLORIMETRY_BT601)) {
652         color_spec = GST_MPEGTS_JPEG2000_COLORSPEC_REC601;
653       } else {
654         if (g_str_equal (colorimetry, GST_VIDEO_COLORIMETRY_BT709)
655             || g_str_equal (colorimetry, GST_VIDEO_COLORIMETRY_SMPTE240M)) {
656           color_spec = GST_MPEGTS_JPEG2000_COLORSPEC_REC709;
657         }
658       }
659       private_data->color_spec = color_spec;
660     } else {
661       GST_ERROR_OBJECT (pad, "Colorimetry not present in caps");
662       goto not_negotiated;
663     }
664     st = TSMUX_ST_VIDEO_JP2K;
665     ts_pad->prepare_func = gst_base_ts_mux_prepare_jpeg2000;
666     ts_pad->prepare_data = private_data;
667     ts_pad->free_func = gst_base_ts_mux_free_jpeg2000;
668   } else {
669     GstBaseTsMuxClass *klass = GST_BASE_TS_MUX_GET_CLASS (mux);
670
671     if (klass->handle_media_type) {
672       st = klass->handle_media_type (mux, mt, ts_pad);
673     }
674   }
675
676
677   if (st != TSMUX_ST_RESERVED) {
678     ts_pad->stream = tsmux_create_stream (mux->tsmux, st, ts_pad->pid,
679         ts_pad->language);
680   } else {
681     GST_DEBUG_OBJECT (pad, "Failed to determine stream type");
682   }
683
684   if (ts_pad->stream != NULL) {
685     const char *interlace_mode = gst_structure_get_string (s, "interlace-mode");
686     gst_structure_get_int (s, "rate", &ts_pad->stream->audio_sampling);
687     gst_structure_get_int (s, "channels", &ts_pad->stream->audio_channels);
688     gst_structure_get_int (s, "bitrate", &ts_pad->stream->audio_bitrate);
689
690     /* frame rate */
691     gst_structure_get_fraction (s, "framerate", &ts_pad->stream->num,
692         &ts_pad->stream->den);
693
694     /* Interlace mode */
695     ts_pad->stream->interlace_mode = FALSE;
696     if (interlace_mode) {
697       ts_pad->stream->interlace_mode =
698           g_str_equal (interlace_mode, "interleaved");
699     }
700     /* Width and Height */
701     gst_structure_get_int (s, "width", &ts_pad->stream->horizontal_size);
702     gst_structure_get_int (s, "height", &ts_pad->stream->vertical_size);
703
704     ts_pad->stream->color_spec = color_spec;
705     ts_pad->stream->max_bitrate = max_rate;
706     ts_pad->stream->profile_and_level = profile | main_level;
707
708     ts_pad->stream->opus_channel_config_code = opus_channel_config_code;
709
710     tsmux_stream_set_buffer_release_func (ts_pad->stream, release_buffer_cb);
711     tsmux_program_add_stream (ts_pad->prog, ts_pad->stream);
712
713     ret = GST_FLOW_OK;
714   }
715   gst_caps_unref (caps);
716   return ret;
717   /* ERRORS */
718 not_negotiated:
719   {
720     g_free (private_data);
721     GST_DEBUG_OBJECT (pad, "Sink pad caps were not set before pushing");
722     if (caps)
723       gst_caps_unref (caps);
724     return GST_FLOW_NOT_NEGOTIATED;
725   }
726 }
727
728 static GstFlowReturn
729 gst_base_ts_mux_create_pad_stream (GstBaseTsMux * mux, GstPad * pad)
730 {
731   GstBaseTsMuxPad *ts_pad = GST_BASE_TS_MUX_PAD (pad);
732   gchar *name = NULL;
733   gchar *pcr_name;
734   GstFlowReturn ret = GST_FLOW_OK;
735
736   if (ts_pad->prog_id == -1) {
737     name = GST_PAD_NAME (pad);
738     if (mux->prog_map != NULL && gst_structure_has_field (mux->prog_map, name)) {
739       gint idx;
740       gboolean ret = gst_structure_get_int (mux->prog_map, name, &idx);
741       if (!ret) {
742         GST_ELEMENT_ERROR (mux, STREAM, MUX,
743             ("Reading program map failed. Assuming default"), (NULL));
744         idx = DEFAULT_PROG_ID;
745       }
746       if (idx < 0) {
747         GST_DEBUG_OBJECT (mux, "Program number %d associate with pad %s less "
748             "than zero; DEFAULT_PROGRAM = %d is used instead",
749             idx, name, DEFAULT_PROG_ID);
750         idx = DEFAULT_PROG_ID;
751       }
752       ts_pad->prog_id = idx;
753     } else {
754       ts_pad->prog_id = DEFAULT_PROG_ID;
755     }
756   }
757
758   ts_pad->prog =
759       (TsMuxProgram *) g_hash_table_lookup (mux->programs,
760       GINT_TO_POINTER (ts_pad->prog_id));
761   if (ts_pad->prog == NULL) {
762     ts_pad->prog = tsmux_program_new (mux->tsmux, ts_pad->prog_id);
763     if (ts_pad->prog == NULL)
764       goto no_program;
765     tsmux_set_pmt_interval (ts_pad->prog, mux->pmt_interval);
766     tsmux_program_set_scte35_pid (ts_pad->prog, mux->scte35_pid);
767     tsmux_program_set_scte35_interval (ts_pad->prog, mux->scte35_null_interval);
768     g_hash_table_insert (mux->programs, GINT_TO_POINTER (ts_pad->prog_id),
769         ts_pad->prog);
770   }
771
772   if (ts_pad->stream == NULL) {
773     ret = gst_base_ts_mux_create_stream (mux, ts_pad);
774     if (ret != GST_FLOW_OK)
775       goto no_stream;
776   }
777
778   if (ts_pad->prog->pcr_stream == NULL) {
779     /* Take the first stream of the program for the PCR */
780     GST_DEBUG_OBJECT (ts_pad,
781         "Use stream (pid=%d) from pad as PCR for program (prog_id = %d)",
782         ts_pad->pid, ts_pad->prog_id);
783
784     tsmux_program_set_pcr_stream (ts_pad->prog, ts_pad->stream);
785   }
786
787   /* Check for user-specified PCR PID */
788   pcr_name = g_strdup_printf ("PCR_%d", ts_pad->prog->pgm_number);
789   if (mux->prog_map && gst_structure_has_field (mux->prog_map, pcr_name)) {
790     const gchar *sink_name = gst_structure_get_string (mux->prog_map, pcr_name);
791
792     if (!g_strcmp0 (name, sink_name)) {
793       GST_DEBUG_OBJECT (mux, "User specified stream (pid=%d) as PCR for "
794           "program (prog_id = %d)", ts_pad->pid, ts_pad->prog->pgm_number);
795       tsmux_program_set_pcr_stream (ts_pad->prog, ts_pad->stream);
796     }
797   }
798   g_free (pcr_name);
799
800   return ret;
801
802   /* ERRORS */
803 no_program:
804   {
805     GST_ELEMENT_ERROR (mux, STREAM, MUX,
806         ("Could not create new program"), (NULL));
807     return GST_FLOW_ERROR;
808   }
809 no_stream:
810   {
811     GST_ELEMENT_ERROR (mux, STREAM, MUX,
812         ("Could not create handler for stream"), (NULL));
813     return ret;
814   }
815 }
816
817 static gboolean
818 gst_base_ts_mux_create_pad_stream_func (GstElement * element, GstPad * pad,
819     gpointer user_data)
820 {
821   GstFlowReturn *ret = user_data;
822
823   *ret = gst_base_ts_mux_create_pad_stream (GST_BASE_TS_MUX (element), pad);
824
825   return *ret == GST_FLOW_OK;
826 }
827
828 static GstFlowReturn
829 gst_base_ts_mux_create_streams (GstBaseTsMux * mux)
830 {
831   GstFlowReturn ret = GST_FLOW_OK;
832
833   gst_element_foreach_sink_pad (GST_ELEMENT_CAST (mux),
834       gst_base_ts_mux_create_pad_stream_func, &ret);
835
836   return ret;
837 }
838
839 static void
840 new_packet_common_init (GstBaseTsMux * mux, GstBuffer * buf, guint8 * data,
841     guint len)
842 {
843   /* Packets should be at least 188 bytes, but check anyway */
844   g_assert (len >= 2 || !data);
845
846   if (!mux->streamheader_sent && data) {
847     guint pid = ((data[1] & 0x1f) << 8) | data[2];
848     /* if it's a PAT or a PMT */
849     if (pid == 0x00 || (pid >= TSMUX_START_PMT_PID && pid < TSMUX_START_ES_PID)) {
850       GstBuffer *hbuf;
851
852       if (!buf) {
853         hbuf = gst_buffer_new_and_alloc (len);
854         gst_buffer_fill (hbuf, 0, data, len);
855       } else {
856         hbuf = gst_buffer_copy (buf);
857       }
858       GST_LOG_OBJECT (mux,
859           "Collecting packet with pid 0x%04x into streamheaders", pid);
860
861       g_queue_push_tail (&mux->streamheader, hbuf);
862     } else if (!g_queue_is_empty (&mux->streamheader)) {
863       gst_base_ts_mux_set_header_on_caps (mux);
864       mux->streamheader_sent = TRUE;
865     }
866   }
867
868   if (buf) {
869     if (mux->is_header) {
870       GST_LOG_OBJECT (mux, "marking as header buffer");
871       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
872     }
873     if (mux->is_delta) {
874       GST_LOG_OBJECT (mux, "marking as delta unit");
875       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
876     } else {
877       GST_DEBUG_OBJECT (mux, "marking as non-delta unit");
878       mux->is_delta = TRUE;
879     }
880   }
881 }
882
883 static GstFlowReturn
884 gst_base_ts_mux_push_packets (GstBaseTsMux * mux, gboolean force)
885 {
886   GstBufferList *buffer_list;
887   gint align = mux->alignment;
888   gint av, packet_size;
889
890   packet_size = mux->packet_size;
891
892   if (align < 0)
893     align = mux->automatic_alignment;
894
895   av = gst_adapter_available (mux->out_adapter);
896   GST_LOG_OBJECT (mux, "align %d, av %d", align, av);
897
898   if (av == 0)
899     return GST_FLOW_OK;
900
901   /* no alignment, just push all available data */
902   if (align == 0) {
903     buffer_list = gst_adapter_take_buffer_list (mux->out_adapter, av);
904     return gst_aggregator_finish_buffer_list (GST_AGGREGATOR (mux),
905         buffer_list);
906   }
907
908   align *= packet_size;
909
910   if (!force && align > av)
911     return GST_FLOW_OK;
912
913   buffer_list = gst_buffer_list_new_sized ((av / align) + 1);
914
915   GST_LOG_OBJECT (mux, "aligning to %d bytes", align);
916   while (align <= av) {
917     GstBuffer *buf;
918     GstClockTime pts;
919
920     pts = gst_adapter_prev_pts (mux->out_adapter, NULL);
921     buf = gst_adapter_take_buffer (mux->out_adapter, align);
922
923     GST_BUFFER_PTS (buf) = pts;
924
925     gst_buffer_list_add (buffer_list, buf);
926     av -= align;
927   }
928
929   if (av > 0 && force) {
930     GstBuffer *buf;
931     GstClockTime pts;
932     guint8 *data;
933     guint32 header;
934     gint dummy;
935     GstMapInfo map;
936
937     GST_LOG_OBJECT (mux, "handling %d leftover bytes", av);
938
939     pts = gst_adapter_prev_pts (mux->out_adapter, NULL);
940     buf = gst_buffer_new_and_alloc (align);
941
942     GST_BUFFER_PTS (buf) = pts;
943
944     gst_buffer_map (buf, &map, GST_MAP_READ);
945     data = map.data;
946
947     gst_adapter_copy (mux->out_adapter, data, 0, av);
948     gst_adapter_clear (mux->out_adapter);
949
950     data += av;
951     header = GST_READ_UINT32_BE (data - packet_size);
952
953     dummy = (map.size - av) / packet_size;
954     GST_LOG_OBJECT (mux, "adding %d null packets", dummy);
955
956     for (; dummy > 0; dummy--) {
957       gint offset;
958
959       if (packet_size > GST_BASE_TS_MUX_NORMAL_PACKET_LENGTH) {
960         GST_WRITE_UINT32_BE (data, header);
961         /* simply increase header a bit and never mind too much */
962         header++;
963         offset = 4;
964       } else {
965         offset = 0;
966       }
967       GST_WRITE_UINT8 (data + offset, TSMUX_SYNC_BYTE);
968       /* null packet PID */
969       GST_WRITE_UINT16_BE (data + offset + 1, 0x1FFF);
970       /* no adaptation field exists | continuity counter undefined */
971       GST_WRITE_UINT8 (data + offset + 3, 0x10);
972       /* payload */
973       memset (data + offset + 4, 0, GST_BASE_TS_MUX_NORMAL_PACKET_LENGTH - 4);
974       data += packet_size;
975     }
976
977     gst_buffer_unmap (buf, &map);
978     gst_buffer_list_add (buffer_list, buf);
979   }
980
981   return gst_aggregator_finish_buffer_list (GST_AGGREGATOR (mux), buffer_list);
982 }
983
984 static GstFlowReturn
985 gst_base_ts_mux_collect_packet (GstBaseTsMux * mux, GstBuffer * buf)
986 {
987   GST_LOG_OBJECT (mux, "collecting packet size %" G_GSIZE_FORMAT,
988       gst_buffer_get_size (buf));
989   gst_adapter_push (mux->out_adapter, buf);
990
991   return GST_FLOW_OK;
992 }
993
994 static GstEvent *
995 check_pending_key_unit_event (GstEvent * pending_event, GstSegment * segment,
996     GstClockTime timestamp, guint flags, GstClockTime pending_key_unit_ts)
997 {
998   GstClockTime running_time, stream_time;
999   gboolean all_headers;
1000   guint count;
1001   GstEvent *event = NULL;
1002
1003   g_assert (segment != NULL);
1004
1005   if (pending_event == NULL)
1006     goto out;
1007
1008   if (GST_CLOCK_TIME_IS_VALID (pending_key_unit_ts) &&
1009       timestamp == GST_CLOCK_TIME_NONE)
1010     goto out;
1011
1012   running_time = timestamp;
1013
1014   GST_INFO ("now %" GST_TIME_FORMAT " wanted %" GST_TIME_FORMAT,
1015       GST_TIME_ARGS (running_time), GST_TIME_ARGS (pending_key_unit_ts));
1016   if (GST_CLOCK_TIME_IS_VALID (pending_key_unit_ts) &&
1017       running_time < pending_key_unit_ts)
1018     goto out;
1019
1020   if (flags & GST_BUFFER_FLAG_DELTA_UNIT) {
1021     GST_INFO ("pending force key unit, waiting for keyframe");
1022     goto out;
1023   }
1024
1025   stream_time = gst_segment_to_stream_time (segment,
1026       GST_FORMAT_TIME, timestamp);
1027
1028   if (GST_EVENT_TYPE (pending_event) == GST_EVENT_CUSTOM_DOWNSTREAM) {
1029     gst_video_event_parse_downstream_force_key_unit (pending_event,
1030         NULL, NULL, NULL, &all_headers, &count);
1031   } else {
1032     gst_video_event_parse_upstream_force_key_unit (pending_event, NULL,
1033         &all_headers, &count);
1034   }
1035
1036   event =
1037       gst_video_event_new_downstream_force_key_unit (timestamp, stream_time,
1038       running_time, all_headers, count);
1039   gst_event_set_seqnum (event, gst_event_get_seqnum (pending_event));
1040
1041 out:
1042   return event;
1043 }
1044
1045 /* Called when the TsMux has prepared a packet for output. Return FALSE
1046  * on error */
1047 static gboolean
1048 new_packet_cb (GstBuffer * buf, void *user_data, gint64 new_pcr)
1049 {
1050   GstBaseTsMux *mux = (GstBaseTsMux *) user_data;
1051   GstBaseTsMuxClass *klass = GST_BASE_TS_MUX_GET_CLASS (mux);
1052   GstMapInfo map;
1053
1054   g_assert (klass->output_packet);
1055
1056   gst_buffer_map (buf, &map, GST_MAP_READWRITE);
1057
1058   if (!GST_CLOCK_TIME_IS_VALID (GST_BUFFER_PTS (buf)))
1059     GST_BUFFER_PTS (buf) = mux->last_ts;
1060
1061   /* do common init (flags and streamheaders) */
1062   new_packet_common_init (mux, buf, map.data, map.size);
1063
1064   gst_buffer_unmap (buf, &map);
1065
1066   return klass->output_packet (mux, buf, new_pcr);
1067 }
1068
1069 /* called when TsMux needs new packet to write into */
1070 static void
1071 alloc_packet_cb (GstBuffer ** buf, void *user_data)
1072 {
1073   GstBaseTsMux *mux = (GstBaseTsMux *) user_data;
1074   GstBaseTsMuxClass *klass = GST_BASE_TS_MUX_GET_CLASS (mux);
1075
1076   g_assert (klass->allocate_packet);
1077
1078   klass->allocate_packet (mux, buf);
1079 }
1080
1081 static GstFlowReturn
1082 gst_base_ts_mux_aggregate_buffer (GstBaseTsMux * mux,
1083     GstAggregatorPad * agg_pad, GstBuffer * buf)
1084 {
1085   GstFlowReturn ret = GST_FLOW_OK;
1086   GstBaseTsMuxPad *best = GST_BASE_TS_MUX_PAD (agg_pad);
1087   TsMuxProgram *prog;
1088   gint64 pts = GST_CLOCK_STIME_NONE;
1089   gint64 dts = GST_CLOCK_STIME_NONE;
1090   gboolean delta = TRUE, header = FALSE;
1091   StreamData *stream_data;
1092   GstMpegtsSection *scte_section = NULL;
1093
1094   GST_DEBUG_OBJECT (mux, "Pads collected");
1095
1096   if (buf && gst_buffer_get_size (buf) == 0
1097       && GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_GAP)) {
1098     gst_buffer_unref (buf);
1099     return GST_FLOW_OK;
1100   }
1101
1102   if (G_UNLIKELY (mux->first)) {
1103     ret = gst_base_ts_mux_create_streams (mux);
1104     if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1105       if (buf)
1106         gst_buffer_unref (buf);
1107       return ret;
1108     }
1109
1110     mux->first = FALSE;
1111   }
1112
1113   prog = best->prog;
1114   if (prog == NULL) {
1115     GList *cur;
1116
1117     gst_base_ts_mux_create_pad_stream (mux, GST_PAD (best));
1118     tsmux_resend_pat (mux->tsmux);
1119     tsmux_resend_si (mux->tsmux);
1120     prog = best->prog;
1121     g_assert_nonnull (prog);
1122
1123     /* output PMT for each program */
1124     for (cur = mux->tsmux->programs; cur; cur = cur->next) {
1125       TsMuxProgram *program = (TsMuxProgram *) cur->data;
1126
1127       tsmux_resend_pmt (program);
1128     }
1129   }
1130
1131   g_assert (buf != NULL);
1132
1133   if (best->prepare_func) {
1134     GstBuffer *tmp;
1135
1136     tmp = best->prepare_func (buf, best, mux);
1137     g_assert (tmp);
1138     gst_buffer_unref (buf);
1139     buf = tmp;
1140   }
1141
1142   if (mux->force_key_unit_event != NULL && best->stream->is_video_stream) {
1143     GstEvent *event;
1144
1145     event = check_pending_key_unit_event (mux->force_key_unit_event,
1146         &agg_pad->segment, GST_BUFFER_PTS (buf),
1147         GST_BUFFER_FLAGS (buf), mux->pending_key_unit_ts);
1148     if (event) {
1149       GstClockTime running_time;
1150       guint count;
1151       GList *cur;
1152
1153       mux->pending_key_unit_ts = GST_CLOCK_TIME_NONE;
1154       gst_event_replace (&mux->force_key_unit_event, NULL);
1155
1156       gst_video_event_parse_downstream_force_key_unit (event,
1157           NULL, NULL, &running_time, NULL, &count);
1158
1159       GST_INFO_OBJECT (mux, "pushing downstream force-key-unit event %d "
1160           "%" GST_TIME_FORMAT " count %d", gst_event_get_seqnum (event),
1161           GST_TIME_ARGS (running_time), count);
1162       gst_pad_push_event (GST_AGGREGATOR_SRC_PAD (mux), event);
1163
1164       /* output PAT, SI tables */
1165       tsmux_resend_pat (mux->tsmux);
1166       tsmux_resend_si (mux->tsmux);
1167
1168       /* output PMT for each program */
1169       for (cur = mux->tsmux->programs; cur; cur = cur->next) {
1170         TsMuxProgram *program = (TsMuxProgram *) cur->data;
1171
1172         tsmux_resend_pmt (program);
1173       }
1174     }
1175   }
1176
1177   if (G_UNLIKELY (prog->pcr_stream == NULL)) {
1178     /* Take the first data stream for the PCR */
1179     GST_DEBUG_OBJECT (best,
1180         "Use stream (pid=%d) from pad as PCR for program (prog_id = %d)",
1181         best->pid, best->prog_id);
1182
1183     /* Set the chosen PCR stream */
1184     tsmux_program_set_pcr_stream (prog, best->stream);
1185   }
1186
1187   GST_DEBUG_OBJECT (best, "Chose stream for output (PID: 0x%04x)", best->pid);
1188
1189   GST_OBJECT_LOCK (mux);
1190   scte_section = mux->pending_scte35_section;
1191   mux->pending_scte35_section = NULL;
1192   GST_OBJECT_UNLOCK (mux);
1193   if (G_UNLIKELY (scte_section)) {
1194     GST_DEBUG_OBJECT (mux, "Sending pending SCTE section");
1195     if (!tsmux_send_section (mux->tsmux, scte_section))
1196       GST_ERROR_OBJECT (mux, "Error sending SCTE section !");
1197   }
1198
1199   if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_PTS (buf))) {
1200     pts = GSTTIME_TO_MPEGTIME (GST_BUFFER_PTS (buf));
1201     GST_DEBUG_OBJECT (mux, "Buffer has PTS  %" GST_TIME_FORMAT " pts %"
1202         G_GINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (buf)), pts);
1203   }
1204
1205   if (GST_CLOCK_STIME_IS_VALID (best->dts)) {
1206     dts = GSTTIME_TO_MPEGTIME (best->dts);
1207     GST_DEBUG_OBJECT (mux, "Buffer has DTS %" GST_STIME_FORMAT " dts %"
1208         G_GINT64_FORMAT, GST_STIME_ARGS (best->dts), dts);
1209   }
1210
1211   /* should not have a DTS without PTS */
1212   if (!GST_CLOCK_STIME_IS_VALID (pts) && GST_CLOCK_STIME_IS_VALID (dts)) {
1213     GST_DEBUG_OBJECT (mux, "using DTS for unknown PTS");
1214     pts = dts;
1215   }
1216
1217   if (best->stream->is_video_stream) {
1218     delta = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
1219     header = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_HEADER);
1220   }
1221
1222   if (best->stream->is_meta && gst_buffer_get_size (buf) > (G_MAXUINT16 - 3)) {
1223     GST_WARNING_OBJECT (mux, "KLV meta unit too big, splitting not supported");
1224
1225     gst_buffer_unref (buf);
1226     return GST_FLOW_OK;
1227   }
1228
1229   GST_DEBUG_OBJECT (mux, "delta: %d", delta);
1230
1231   stream_data = stream_data_new (buf);
1232   tsmux_stream_add_data (best->stream, stream_data->map_info.data,
1233       stream_data->map_info.size, stream_data, pts, dts, !delta);
1234
1235   /* outgoing ts follows ts of PCR program stream */
1236   if (prog->pcr_stream == best->stream) {
1237     /* prefer DTS if present for PCR as it should be monotone */
1238     mux->last_ts =
1239         GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) ?
1240         GST_BUFFER_DTS (buf) : GST_BUFFER_PTS (buf);
1241   }
1242
1243   mux->is_delta = delta;
1244   mux->is_header = header;
1245   while (tsmux_stream_bytes_in_buffer (best->stream) > 0) {
1246     if (!tsmux_write_stream_packet (mux->tsmux, best->stream)) {
1247       /* Failed writing data for some reason. Set appropriate error */
1248       GST_DEBUG_OBJECT (mux, "Failed to write data packet");
1249       GST_ELEMENT_ERROR (mux, STREAM, MUX,
1250           ("Failed writing output data to stream %04x", best->stream->id),
1251           (NULL));
1252       goto write_fail;
1253     }
1254   }
1255   /* flush packet cache */
1256   return gst_base_ts_mux_push_packets (mux, FALSE);
1257
1258   /* ERRORS */
1259 write_fail:
1260   {
1261     return mux->last_flow_ret;
1262   }
1263 }
1264
1265 /* GstElement implementation */
1266
1267 static GstPad *
1268 gst_base_ts_mux_request_new_pad (GstElement * element, GstPadTemplate * templ,
1269     const gchar * name, const GstCaps * caps)
1270 {
1271   GstBaseTsMux *mux = GST_BASE_TS_MUX (element);
1272   gint pid = -1;
1273   GstPad *pad = NULL;
1274
1275   if (name != NULL && sscanf (name, "sink_%d", &pid) == 1) {
1276     if (tsmux_find_stream (mux->tsmux, pid))
1277       goto stream_exists;
1278     /* Make sure we don't use reserved PID.
1279      * FIXME : This should be extended to other variants (ex: ATSC) reserved PID */
1280     if (pid < TSMUX_START_ES_PID)
1281       goto invalid_stream_pid;
1282   } else {
1283     pid = tsmux_get_new_pid (mux->tsmux);
1284   }
1285
1286   pad = (GstPad *)
1287       GST_ELEMENT_CLASS (parent_class)->request_new_pad (element,
1288       templ, name, caps);
1289
1290   gst_base_ts_mux_pad_reset (GST_BASE_TS_MUX_PAD (pad));
1291   GST_BASE_TS_MUX_PAD (pad)->pid = pid;
1292
1293   return pad;
1294
1295   /* ERRORS */
1296 stream_exists:
1297   {
1298     GST_ELEMENT_ERROR (element, STREAM, MUX, ("Duplicate PID requested"),
1299         (NULL));
1300     return NULL;
1301   }
1302
1303 invalid_stream_pid:
1304   {
1305     GST_ELEMENT_ERROR (element, STREAM, MUX,
1306         ("Invalid Elementary stream PID (< 0x40)"), (NULL));
1307     return NULL;
1308   }
1309 }
1310
1311 static void
1312 gst_base_ts_mux_release_pad (GstElement * element, GstPad * pad)
1313 {
1314   GstBaseTsMux *mux = GST_BASE_TS_MUX (element);
1315
1316   if (mux->tsmux) {
1317     GList *cur;
1318     GstBaseTsMuxPad *ts_pad = GST_BASE_TS_MUX_PAD (pad);
1319     gint pid = ts_pad->pid;
1320
1321     if (ts_pad->prog) {
1322       if (ts_pad->prog->pcr_stream == ts_pad->stream) {
1323         tsmux_program_set_pcr_stream (ts_pad->prog, NULL);
1324       }
1325       if (tsmux_remove_stream (mux->tsmux, pid, ts_pad->prog)) {
1326         g_hash_table_remove (mux->programs, GINT_TO_POINTER (ts_pad->prog_id));
1327       }
1328     }
1329
1330     tsmux_resend_pat (mux->tsmux);
1331     tsmux_resend_si (mux->tsmux);
1332
1333     /* output PMT for each program */
1334     for (cur = mux->tsmux->programs; cur; cur = cur->next) {
1335       TsMuxProgram *program = (TsMuxProgram *) cur->data;
1336
1337       tsmux_resend_pmt (program);
1338     }
1339   }
1340
1341   GST_ELEMENT_CLASS (parent_class)->release_pad (element, pad);
1342 }
1343
1344 static gboolean
1345 gst_base_ts_mux_send_event (GstElement * element, GstEvent * event)
1346 {
1347   GstMpegtsSection *section;
1348   GstBaseTsMux *mux = GST_BASE_TS_MUX (element);
1349
1350   section = gst_event_parse_mpegts_section (event);
1351
1352   if (section) {
1353     GST_DEBUG ("Received event with mpegts section");
1354
1355     if (section->section_type == GST_MPEGTS_SECTION_SCTE_SIT) {
1356       /* Will be sent from the streaming threads */
1357       GST_DEBUG_OBJECT (mux, "Storing SCTE event");
1358       GST_OBJECT_LOCK (element);
1359       if (mux->pending_scte35_section)
1360         gst_mpegts_section_unref (mux->pending_scte35_section);
1361       mux->pending_scte35_section = section;
1362       GST_OBJECT_UNLOCK (element);
1363     } else {
1364       /* TODO: Check that the section type is supported */
1365       tsmux_add_mpegts_si_section (mux->tsmux, section);
1366     }
1367
1368     gst_event_unref (event);
1369
1370     return TRUE;
1371   }
1372
1373   return GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
1374 }
1375
1376 /* GstAggregator implementation */
1377
1378 static gboolean
1379 gst_base_ts_mux_sink_event (GstAggregator * agg, GstAggregatorPad * agg_pad,
1380     GstEvent * event)
1381 {
1382   GstAggregatorClass *agg_class = GST_AGGREGATOR_CLASS (parent_class);
1383   GstBaseTsMux *mux = GST_BASE_TS_MUX (agg);
1384   GstBaseTsMuxPad *ts_pad = GST_BASE_TS_MUX_PAD (agg_pad);
1385   gboolean res = FALSE;
1386   gboolean forward = TRUE;
1387
1388   switch (GST_EVENT_TYPE (event)) {
1389     case GST_EVENT_CUSTOM_DOWNSTREAM:
1390     {
1391       GstClockTime timestamp, stream_time, running_time;
1392       gboolean all_headers;
1393       guint count;
1394
1395       if (!gst_video_event_is_force_key_unit (event))
1396         goto out;
1397
1398       res = TRUE;
1399       forward = FALSE;
1400
1401       gst_video_event_parse_downstream_force_key_unit (event,
1402           &timestamp, &stream_time, &running_time, &all_headers, &count);
1403       GST_INFO_OBJECT (ts_pad, "have downstream force-key-unit event, "
1404           "seqnum %d, running-time %" GST_TIME_FORMAT " count %d",
1405           gst_event_get_seqnum (event), GST_TIME_ARGS (running_time), count);
1406
1407       if (mux->force_key_unit_event != NULL) {
1408         GST_INFO_OBJECT (mux, "skipping downstream force key unit event "
1409             "as an upstream force key unit is already queued");
1410         goto out;
1411       }
1412
1413       if (!all_headers)
1414         goto out;
1415
1416       mux->pending_key_unit_ts = running_time;
1417       gst_event_replace (&mux->force_key_unit_event, event);
1418       break;
1419     }
1420     case GST_EVENT_TAG:{
1421       GstTagList *list;
1422       gchar *lang = NULL;
1423
1424       GST_DEBUG_OBJECT (mux, "received tag event");
1425       gst_event_parse_tag (event, &list);
1426
1427       /* Matroska wants ISO 639-2B code, taglist most likely contains 639-1 */
1428       if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &lang)) {
1429         const gchar *lang_code;
1430
1431         lang_code = gst_tag_get_language_code_iso_639_2B (lang);
1432         if (lang_code) {
1433           GST_DEBUG_OBJECT (ts_pad, "Setting language to '%s'", lang_code);
1434
1435           g_free (ts_pad->language);
1436           ts_pad->language = g_strdup (lang_code);
1437         } else {
1438           GST_WARNING_OBJECT (ts_pad, "Did not get language code for '%s'",
1439               lang);
1440         }
1441         g_free (lang);
1442       }
1443
1444       /* handled this, don't want collectpads to forward it downstream */
1445       res = TRUE;
1446       forward = gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL;
1447       break;
1448     }
1449     case GST_EVENT_STREAM_START:{
1450       GstStreamFlags flags;
1451
1452       gst_event_parse_stream_flags (event, &flags);
1453
1454       /* Don't wait for data on sparse inputs like metadata streams */
1455       /*
1456          if ((flags & GST_STREAM_FLAG_SPARSE)) {
1457          GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_LOCKED);
1458          gst_collect_pads_set_waiting (pads, data, FALSE);
1459          GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_LOCKED);
1460          }
1461        */
1462       break;
1463     }
1464     default:
1465       break;
1466   }
1467
1468 out:
1469   if (!forward)
1470     gst_event_unref (event);
1471   else
1472     res = agg_class->sink_event (agg, agg_pad, event);
1473
1474   return res;
1475 }
1476
1477 static gboolean
1478 gst_base_ts_mux_src_event (GstAggregator * agg, GstEvent * event)
1479 {
1480   GstAggregatorClass *agg_class = GST_AGGREGATOR_CLASS (parent_class);
1481   GstBaseTsMux *mux = GST_BASE_TS_MUX (agg);
1482   gboolean res = TRUE, forward = TRUE;
1483
1484   switch (GST_EVENT_TYPE (event)) {
1485     case GST_EVENT_CUSTOM_UPSTREAM:
1486     {
1487       GstIterator *iter;
1488       GValue sinkpad_value = G_VALUE_INIT;
1489       GstClockTime running_time;
1490       gboolean all_headers, done = FALSE, res = FALSE;
1491       guint count;
1492
1493       if (!gst_video_event_is_force_key_unit (event))
1494         break;
1495
1496       forward = FALSE;
1497
1498       gst_video_event_parse_upstream_force_key_unit (event,
1499           &running_time, &all_headers, &count);
1500
1501       GST_INFO_OBJECT (mux, "received upstream force-key-unit event, "
1502           "seqnum %d running_time %" GST_TIME_FORMAT " all_headers %d count %d",
1503           gst_event_get_seqnum (event), GST_TIME_ARGS (running_time),
1504           all_headers, count);
1505
1506       if (!all_headers)
1507         break;
1508
1509       mux->pending_key_unit_ts = running_time;
1510       gst_event_replace (&mux->force_key_unit_event, event);
1511
1512       iter = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mux));
1513
1514       while (!done) {
1515         switch (gst_iterator_next (iter, &sinkpad_value)) {
1516           case GST_ITERATOR_OK:{
1517             GstPad *sinkpad = g_value_get_object (&sinkpad_value);
1518             gboolean tmp;
1519
1520             GST_INFO_OBJECT (GST_AGGREGATOR_SRC_PAD (agg), "forwarding");
1521             tmp = gst_pad_push_event (sinkpad, gst_event_ref (event));
1522             GST_INFO_OBJECT (mux, "result %d", tmp);
1523             /* succeed if at least one pad succeeds */
1524             res |= tmp;
1525             break;
1526           }
1527           case GST_ITERATOR_DONE:
1528             done = TRUE;
1529             break;
1530           case GST_ITERATOR_RESYNC:
1531             gst_iterator_resync (iter);
1532             break;
1533           case GST_ITERATOR_ERROR:
1534             g_assert_not_reached ();
1535             break;
1536         }
1537         g_value_reset (&sinkpad_value);
1538       }
1539       g_value_unset (&sinkpad_value);
1540       gst_iterator_free (iter);
1541       break;
1542     }
1543     default:
1544       break;
1545   }
1546
1547   if (forward)
1548     res = agg_class->src_event (agg, event);
1549   else
1550     gst_event_unref (event);
1551
1552   return res;
1553 }
1554
1555 static GstBuffer *
1556 gst_base_ts_mux_clip (GstAggregator * agg,
1557     GstAggregatorPad * agg_pad, GstBuffer * buf)
1558 {
1559   GstBaseTsMuxPad *pad = GST_BASE_TS_MUX_PAD (agg_pad);
1560   GstClockTime time;
1561   GstBuffer *ret;
1562
1563   ret = buf;
1564
1565   /* PTS */
1566   time = GST_BUFFER_PTS (buf);
1567
1568   /* invalid left alone and passed */
1569   if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (time))) {
1570     time =
1571         gst_segment_to_running_time (&agg_pad->segment, GST_FORMAT_TIME, time);
1572     if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time))) {
1573       GST_DEBUG_OBJECT (pad, "clipping buffer on pad outside segment");
1574       gst_buffer_unref (buf);
1575       ret = NULL;
1576       goto beach;
1577     } else {
1578       GST_LOG_OBJECT (pad, "buffer pts %" GST_TIME_FORMAT " ->  %"
1579           GST_TIME_FORMAT " running time",
1580           GST_TIME_ARGS (GST_BUFFER_PTS (buf)), GST_TIME_ARGS (time));
1581       buf = ret = gst_buffer_make_writable (buf);
1582       GST_BUFFER_PTS (ret) = time;
1583     }
1584   }
1585
1586   /* DTS */
1587   time = GST_BUFFER_DTS (buf);
1588
1589   /* invalid left alone and passed */
1590   if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (time))) {
1591     gint sign;
1592     gint64 dts;
1593
1594     sign = gst_segment_to_running_time_full (&agg_pad->segment, GST_FORMAT_TIME,
1595         time, &time);
1596
1597     if (sign > 0)
1598       dts = (gint64) time;
1599     else
1600       dts = -((gint64) time);
1601
1602     GST_LOG_OBJECT (pad, "buffer dts %" GST_TIME_FORMAT " -> %"
1603         GST_STIME_FORMAT " running time", GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
1604         GST_STIME_ARGS (dts));
1605
1606     if (GST_CLOCK_STIME_IS_VALID (pad->dts) && dts < pad->dts) {
1607       /* Ignore DTS going backward */
1608       GST_WARNING_OBJECT (pad, "ignoring DTS going backward");
1609       dts = pad->dts;
1610     }
1611
1612     ret = gst_buffer_make_writable (buf);
1613     if (sign > 0)
1614       GST_BUFFER_DTS (ret) = time;
1615     else
1616       GST_BUFFER_DTS (ret) = GST_CLOCK_TIME_NONE;
1617
1618     pad->dts = dts;
1619   } else {
1620     pad->dts = GST_CLOCK_STIME_NONE;
1621   }
1622
1623 beach:
1624   return ret;
1625 }
1626
1627 static GstFlowReturn
1628 gst_base_ts_mux_update_src_caps (GstAggregator * agg, GstCaps * caps,
1629     GstCaps ** ret)
1630 {
1631   GstBaseTsMux *mux = GST_BASE_TS_MUX (agg);
1632   GstStructure *s;
1633
1634   *ret = gst_caps_copy (caps);
1635   s = gst_caps_get_structure (*ret, 0);
1636   gst_structure_set (s, "packetsize", G_TYPE_INT, mux->packet_size, NULL);
1637
1638   return GST_FLOW_OK;
1639 }
1640
1641 static GstBaseTsMuxPad *
1642 gst_base_ts_mux_find_best_pad (GstAggregator * aggregator)
1643 {
1644   GstBaseTsMuxPad *best = NULL;
1645   GstClockTime best_ts = GST_CLOCK_TIME_NONE;
1646   GList *l;
1647
1648   GST_OBJECT_LOCK (aggregator);
1649
1650   for (l = GST_ELEMENT_CAST (aggregator)->sinkpads; l; l = l->next) {
1651     GstBaseTsMuxPad *tpad = GST_BASE_TS_MUX_PAD (l->data);
1652     GstAggregatorPad *apad = GST_AGGREGATOR_PAD_CAST (tpad);
1653     GstBuffer *buffer;
1654
1655     buffer = gst_aggregator_pad_peek_buffer (apad);
1656     if (!buffer)
1657       continue;
1658     if (best_ts == GST_CLOCK_TIME_NONE) {
1659       best = tpad;
1660       best_ts = GST_BUFFER_DTS_OR_PTS (buffer);
1661     } else if (GST_BUFFER_DTS_OR_PTS (buffer) != GST_CLOCK_TIME_NONE) {
1662       GstClockTime t = GST_BUFFER_DTS_OR_PTS (buffer);
1663       if (t < best_ts) {
1664         best = tpad;
1665         best_ts = t;
1666       }
1667     }
1668     gst_buffer_unref (buffer);
1669   }
1670
1671   if (best)
1672     gst_object_ref (best);
1673
1674   GST_OBJECT_UNLOCK (aggregator);
1675
1676   GST_DEBUG_OBJECT (aggregator,
1677       "Best pad found with %" GST_TIME_FORMAT ": %" GST_PTR_FORMAT,
1678       GST_TIME_ARGS (best_ts), best);
1679
1680   return best;
1681 }
1682
1683 static gboolean
1684 gst_base_ts_mux_are_all_pads_eos (GstBaseTsMux * mux)
1685 {
1686   GList *l;
1687   gboolean ret = TRUE;
1688
1689   GST_OBJECT_LOCK (mux);
1690
1691   for (l = GST_ELEMENT_CAST (mux)->sinkpads; l; l = l->next) {
1692     GstBaseTsMuxPad *pad = GST_BASE_TS_MUX_PAD (l->data);
1693
1694     if (!gst_aggregator_pad_is_eos (GST_AGGREGATOR_PAD (pad))) {
1695       ret = FALSE;
1696       break;
1697     }
1698   }
1699
1700   GST_OBJECT_UNLOCK (mux);
1701
1702   return ret;
1703 }
1704
1705
1706 static GstFlowReturn
1707 gst_base_ts_mux_aggregate (GstAggregator * agg, gboolean timeout)
1708 {
1709   GstBaseTsMux *mux = GST_BASE_TS_MUX (agg);
1710   GstFlowReturn ret = GST_FLOW_OK;
1711   GstBaseTsMuxPad *best = gst_base_ts_mux_find_best_pad (agg);
1712
1713   if (best) {
1714     GstBuffer *buffer;
1715
1716     buffer = gst_aggregator_pad_pop_buffer (GST_AGGREGATOR_PAD (best));
1717
1718     ret =
1719         gst_base_ts_mux_aggregate_buffer (GST_BASE_TS_MUX (agg),
1720         GST_AGGREGATOR_PAD (best), buffer);
1721
1722     gst_object_unref (best);
1723
1724     if (ret != GST_FLOW_OK)
1725       goto done;
1726   }
1727
1728   if (gst_base_ts_mux_are_all_pads_eos (mux)) {
1729     GstBaseTsMuxClass *klass = GST_BASE_TS_MUX_GET_CLASS (mux);
1730     /* drain some possibly cached data */
1731     if (klass->drain)
1732       klass->drain (mux);
1733     gst_base_ts_mux_push_packets (mux, TRUE);
1734
1735     ret = GST_FLOW_EOS;
1736   }
1737
1738 done:
1739   return ret;
1740 }
1741
1742 static gboolean
1743 gst_base_ts_mux_start (GstAggregator * agg)
1744 {
1745   gst_base_ts_mux_reset (GST_BASE_TS_MUX (agg), TRUE);
1746
1747   return TRUE;
1748 }
1749
1750 static gboolean
1751 gst_base_ts_mux_stop (GstAggregator * agg)
1752 {
1753   gst_base_ts_mux_reset (GST_BASE_TS_MUX (agg), TRUE);
1754
1755   return TRUE;
1756 }
1757
1758 /* GObject implementation */
1759
1760 static void
1761 gst_base_ts_mux_dispose (GObject * object)
1762 {
1763   GstBaseTsMux *mux = GST_BASE_TS_MUX (object);
1764
1765   gst_base_ts_mux_reset (mux, FALSE);
1766
1767   if (mux->out_adapter) {
1768     g_object_unref (mux->out_adapter);
1769     mux->out_adapter = NULL;
1770   }
1771   if (mux->prog_map) {
1772     gst_structure_free (mux->prog_map);
1773     mux->prog_map = NULL;
1774   }
1775   if (mux->programs) {
1776     g_hash_table_destroy (mux->programs);
1777     mux->programs = NULL;
1778   }
1779   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
1780 }
1781
1782 static void
1783 gst_base_ts_mux_constructed (GObject * object)
1784 {
1785   GstBaseTsMux *mux = GST_BASE_TS_MUX (object);
1786
1787   /* initial state */
1788   gst_base_ts_mux_reset (mux, TRUE);
1789 }
1790
1791 static void
1792 gst_base_ts_mux_set_property (GObject * object, guint prop_id,
1793     const GValue * value, GParamSpec * pspec)
1794 {
1795   GstBaseTsMux *mux = GST_BASE_TS_MUX (object);
1796   GList *l;
1797
1798   switch (prop_id) {
1799     case PROP_PROG_MAP:
1800     {
1801       const GstStructure *s = gst_value_get_structure (value);
1802       if (mux->prog_map) {
1803         gst_structure_free (mux->prog_map);
1804       }
1805       if (s)
1806         mux->prog_map = gst_structure_copy (s);
1807       else
1808         mux->prog_map = NULL;
1809       break;
1810     }
1811     case PROP_PAT_INTERVAL:
1812       mux->pat_interval = g_value_get_uint (value);
1813       if (mux->tsmux)
1814         tsmux_set_pat_interval (mux->tsmux, mux->pat_interval);
1815       break;
1816     case PROP_PMT_INTERVAL:
1817       mux->pmt_interval = g_value_get_uint (value);
1818       GST_OBJECT_LOCK (mux);
1819       for (l = GST_ELEMENT_CAST (mux)->sinkpads; l; l = l->next) {
1820         GstBaseTsMuxPad *ts_pad = GST_BASE_TS_MUX_PAD (l->data);
1821
1822         tsmux_set_pmt_interval (ts_pad->prog, mux->pmt_interval);
1823       }
1824       GST_OBJECT_UNLOCK (mux);
1825       break;
1826     case PROP_ALIGNMENT:
1827       mux->alignment = g_value_get_int (value);
1828       break;
1829     case PROP_SI_INTERVAL:
1830       mux->si_interval = g_value_get_uint (value);
1831       tsmux_set_si_interval (mux->tsmux, mux->si_interval);
1832       break;
1833     case PROP_BITRATE:
1834       mux->bitrate = g_value_get_uint64 (value);
1835       if (mux->tsmux)
1836         tsmux_set_bitrate (mux->tsmux, mux->bitrate);
1837       break;
1838     case PROP_PCR_INTERVAL:
1839       mux->pcr_interval = g_value_get_uint (value);
1840       if (mux->tsmux)
1841         tsmux_set_pcr_interval (mux->tsmux, mux->pcr_interval);
1842       break;
1843     case PROP_SCTE_35_PID:
1844       mux->scte35_pid = g_value_get_uint (value);
1845       break;
1846     case PROP_SCTE_35_NULL_INTERVAL:
1847       mux->scte35_null_interval = g_value_get_uint (value);
1848       break;
1849     default:
1850       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1851       break;
1852   }
1853 }
1854
1855 static void
1856 gst_base_ts_mux_get_property (GObject * object, guint prop_id,
1857     GValue * value, GParamSpec * pspec)
1858 {
1859   GstBaseTsMux *mux = GST_BASE_TS_MUX (object);
1860
1861   switch (prop_id) {
1862     case PROP_PROG_MAP:
1863       gst_value_set_structure (value, mux->prog_map);
1864       break;
1865     case PROP_PAT_INTERVAL:
1866       g_value_set_uint (value, mux->pat_interval);
1867       break;
1868     case PROP_PMT_INTERVAL:
1869       g_value_set_uint (value, mux->pmt_interval);
1870       break;
1871     case PROP_ALIGNMENT:
1872       g_value_set_int (value, mux->alignment);
1873       break;
1874     case PROP_SI_INTERVAL:
1875       g_value_set_uint (value, mux->si_interval);
1876       break;
1877     case PROP_BITRATE:
1878       g_value_set_uint64 (value, mux->bitrate);
1879       break;
1880     case PROP_PCR_INTERVAL:
1881       g_value_set_uint (value, mux->pcr_interval);
1882       break;
1883     case PROP_SCTE_35_PID:
1884       g_value_set_uint (value, mux->scte35_pid);
1885       break;
1886     case PROP_SCTE_35_NULL_INTERVAL:
1887       g_value_set_uint (value, mux->scte35_null_interval);
1888       break;
1889     default:
1890       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1891       break;
1892   }
1893 }
1894
1895 /* Default vmethods implementation */
1896
1897 static TsMux *
1898 gst_base_ts_mux_default_create_ts_mux (GstBaseTsMux * mux)
1899 {
1900   TsMux *tsmux = tsmux_new ();
1901   tsmux_set_write_func (tsmux, new_packet_cb, mux);
1902   tsmux_set_alloc_func (tsmux, alloc_packet_cb, mux);
1903   tsmux_set_pat_interval (tsmux, mux->pat_interval);
1904   tsmux_set_si_interval (tsmux, mux->si_interval);
1905   tsmux_set_bitrate (tsmux, mux->bitrate);
1906   tsmux_set_pcr_interval (tsmux, mux->pcr_interval);
1907
1908   return tsmux;
1909 }
1910
1911 static void
1912 gst_base_ts_mux_default_allocate_packet (GstBaseTsMux * mux,
1913     GstBuffer ** buffer)
1914 {
1915   GstBuffer *buf;
1916
1917   buf = gst_buffer_new_and_alloc (mux->packet_size);
1918
1919   *buffer = buf;
1920 }
1921
1922 static gboolean
1923 gst_base_ts_mux_default_output_packet (GstBaseTsMux * mux, GstBuffer * buffer,
1924     gint64 new_pcr)
1925 {
1926   gst_base_ts_mux_collect_packet (mux, buffer);
1927
1928   return TRUE;
1929 }
1930
1931 /* Subclass API */
1932
1933 void
1934 gst_base_ts_mux_set_packet_size (GstBaseTsMux * mux, gsize size)
1935 {
1936   mux->packet_size = size;
1937 }
1938
1939 void
1940 gst_base_ts_mux_set_automatic_alignment (GstBaseTsMux * mux, gsize alignment)
1941 {
1942   mux->automatic_alignment = alignment;
1943 }
1944
1945 static void
1946 gst_base_ts_mux_class_init (GstBaseTsMuxClass * klass)
1947 {
1948   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1949   GstAggregatorClass *gstagg_class = GST_AGGREGATOR_CLASS (klass);
1950   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1951
1952   GST_DEBUG_CATEGORY_INIT (gst_base_ts_mux_debug, "basetsmux", 0,
1953       "MPEG Transport Stream muxer");
1954
1955   gst_element_class_set_static_metadata (gstelement_class,
1956       "MPEG Transport Stream Muxer", "Codec/Muxer",
1957       "Multiplexes media streams into an MPEG Transport Stream",
1958       "Fluendo <contact@fluendo.com>");
1959
1960   gobject_class->set_property =
1961       GST_DEBUG_FUNCPTR (gst_base_ts_mux_set_property);
1962   gobject_class->get_property =
1963       GST_DEBUG_FUNCPTR (gst_base_ts_mux_get_property);
1964   gobject_class->dispose = gst_base_ts_mux_dispose;
1965   gobject_class->constructed = gst_base_ts_mux_constructed;
1966
1967   gstelement_class->request_new_pad = gst_base_ts_mux_request_new_pad;
1968   gstelement_class->release_pad = gst_base_ts_mux_release_pad;
1969   gstelement_class->send_event = gst_base_ts_mux_send_event;
1970
1971   gstagg_class->update_src_caps = gst_base_ts_mux_update_src_caps;
1972   gstagg_class->aggregate = gst_base_ts_mux_aggregate;
1973   gstagg_class->clip = gst_base_ts_mux_clip;
1974   gstagg_class->sink_event = gst_base_ts_mux_sink_event;
1975   gstagg_class->src_event = gst_base_ts_mux_src_event;
1976   gstagg_class->start = gst_base_ts_mux_start;
1977   gstagg_class->stop = gst_base_ts_mux_stop;
1978
1979   klass->create_ts_mux = gst_base_ts_mux_default_create_ts_mux;
1980   klass->allocate_packet = gst_base_ts_mux_default_allocate_packet;
1981   klass->output_packet = gst_base_ts_mux_default_output_packet;
1982
1983   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PROG_MAP,
1984       g_param_spec_boxed ("prog-map", "Program map",
1985           "A GstStructure specifies the mapping from elementary streams to programs",
1986           GST_TYPE_STRUCTURE,
1987           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
1988
1989   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PAT_INTERVAL,
1990       g_param_spec_uint ("pat-interval", "PAT interval",
1991           "Set the interval (in ticks of the 90kHz clock) for writing out the PAT table",
1992           1, G_MAXUINT, TSMUX_DEFAULT_PAT_INTERVAL,
1993           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
1994
1995   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PMT_INTERVAL,
1996       g_param_spec_uint ("pmt-interval", "PMT interval",
1997           "Set the interval (in ticks of the 90kHz clock) for writing out the PMT table",
1998           1, G_MAXUINT, TSMUX_DEFAULT_PMT_INTERVAL,
1999           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
2000
2001   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ALIGNMENT,
2002       g_param_spec_int ("alignment", "packet alignment",
2003           "Number of packets per buffer (padded with dummy packets on EOS) "
2004           "(-1 = auto, 0 = all available packets, 7 for UDP streaming)",
2005           -1, G_MAXINT, BASETSMUX_DEFAULT_ALIGNMENT,
2006           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
2007
2008   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SI_INTERVAL,
2009       g_param_spec_uint ("si-interval", "SI interval",
2010           "Set the interval (in ticks of the 90kHz clock) for writing out the Service"
2011           "Information tables", 1, G_MAXUINT, TSMUX_DEFAULT_SI_INTERVAL,
2012           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
2013
2014   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BITRATE,
2015       g_param_spec_uint64 ("bitrate", "Bitrate (in bits per second)",
2016           "Set the target bitrate, will insert null packets as padding "
2017           " to achieve multiplex-wide constant bitrate (0 means no padding)",
2018           0, G_MAXUINT64, TSMUX_DEFAULT_BITRATE,
2019           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
2020
2021   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PCR_INTERVAL,
2022       g_param_spec_uint ("pcr-interval", "PCR interval",
2023           "Set the interval (in ticks of the 90kHz clock) for writing PCR",
2024           1, G_MAXUINT, TSMUX_DEFAULT_PCR_INTERVAL,
2025           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
2026
2027   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SCTE_35_PID,
2028       g_param_spec_uint ("scte-35-pid", "SCTE-35 PID",
2029           "PID to use for inserting SCTE-35 packets (0: unused)",
2030           0, G_MAXUINT, DEFAULT_SCTE_35_PID,
2031           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
2032
2033   g_object_class_install_property (G_OBJECT_CLASS (klass),
2034       PROP_SCTE_35_NULL_INTERVAL, g_param_spec_uint ("scte-35-null-interval",
2035           "SCTE-35 NULL packet interval",
2036           "Set the interval (in ticks of the 90kHz clock) for writing SCTE-35 NULL (heartbeat) packets."
2037           " (only valid if scte-35-pid is different from 0)", 1, G_MAXUINT,
2038           TSMUX_DEFAULT_SCTE_35_NULL_INTERVAL,
2039           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
2040
2041   gst_element_class_add_static_pad_template_with_gtype (gstelement_class,
2042       &gst_base_ts_mux_src_factory, GST_TYPE_AGGREGATOR_PAD);
2043
2044   gst_type_mark_as_plugin_api (GST_TYPE_BASE_TS_MUX_PAD, 0);
2045 }
2046
2047 static void
2048 gst_base_ts_mux_init (GstBaseTsMux * mux)
2049 {
2050   mux->out_adapter = gst_adapter_new ();
2051
2052   /* properties */
2053   mux->pat_interval = TSMUX_DEFAULT_PAT_INTERVAL;
2054   mux->pmt_interval = TSMUX_DEFAULT_PMT_INTERVAL;
2055   mux->si_interval = TSMUX_DEFAULT_SI_INTERVAL;
2056   mux->pcr_interval = TSMUX_DEFAULT_PCR_INTERVAL;
2057   mux->prog_map = NULL;
2058   mux->alignment = BASETSMUX_DEFAULT_ALIGNMENT;
2059   mux->bitrate = TSMUX_DEFAULT_BITRATE;
2060   mux->scte35_pid = DEFAULT_SCTE_35_PID;
2061   mux->scte35_null_interval = TSMUX_DEFAULT_SCTE_35_NULL_INTERVAL;
2062
2063   mux->packet_size = GST_BASE_TS_MUX_NORMAL_PACKET_LENGTH;
2064   mux->automatic_alignment = 0;
2065 }