]> git.sesse.net Git - ffmpeg/blob - libavformat/mpegtsenc.c
rtpenc_chain: Don't copy the time_base back to the caller
[ffmpeg] / libavformat / mpegtsenc.c
1 /*
2  * MPEG2 transport stream (aka DVB) muxer
3  * Copyright (c) 2003 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/bswap.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/opt.h"
25 #include "libavcodec/mpegvideo.h"
26 #include "avformat.h"
27 #include "internal.h"
28 #include "mpegts.h"
29 #include "adts.h"
30
31 #define PCR_TIME_BASE 27000000
32
33 /* write DVB SI sections */
34
35 /*********************************************/
36 /* mpegts section writer */
37
38 typedef struct MpegTSSection {
39     int pid;
40     int cc;
41     void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
42     void *opaque;
43 } MpegTSSection;
44
45 typedef struct MpegTSService {
46     MpegTSSection pmt; /* MPEG2 pmt table context */
47     int sid;           /* service ID */
48     char *name;
49     char *provider_name;
50     int pcr_pid;
51     int pcr_packet_count;
52     int pcr_packet_period;
53 } MpegTSService;
54
55 typedef struct MpegTSWrite {
56     MpegTSSection pat; /* MPEG2 pat table */
57     MpegTSSection sdt; /* MPEG2 sdt table context */
58     MpegTSService **services;
59     int sdt_packet_count;
60     int sdt_packet_period;
61     int pat_packet_count;
62     int pat_packet_period;
63     int nb_services;
64     int onid;
65     int tsid;
66     int64_t first_pcr;
67     int mux_rate; ///< set to 1 when VBR
68
69     int transport_stream_id;
70     int original_network_id;
71     int service_id;
72
73     int pmt_start_pid;
74     int start_pid;
75 } MpegTSWrite;
76
77 static const AVOption options[] = {
78     { "mpegts_transport_stream_id", "Set transport_stream_id field.",
79       offsetof(MpegTSWrite, transport_stream_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
80     { "mpegts_original_network_id", "Set original_network_id field.",
81       offsetof(MpegTSWrite, original_network_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
82     { "mpegts_service_id", "Set service_id field.",
83       offsetof(MpegTSWrite, service_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
84     { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
85       offsetof(MpegTSWrite, pmt_start_pid), FF_OPT_TYPE_INT, 0x1000, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
86     { "mpegts_start_pid", "Set the first pid.",
87       offsetof(MpegTSWrite, start_pid), FF_OPT_TYPE_INT, 0x0100, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
88     { NULL },
89 };
90
91 static const AVClass mpegts_muxer_class = {
92     "MPEGTS muxer",
93     av_default_item_name,
94     options,
95     LIBAVUTIL_VERSION_INT,
96 };
97
98 /* NOTE: 4 bytes must be left at the end for the crc32 */
99 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
100 {
101     unsigned int crc;
102     unsigned char packet[TS_PACKET_SIZE];
103     const unsigned char *buf_ptr;
104     unsigned char *q;
105     int first, b, len1, left;
106
107     crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
108     buf[len - 4] = (crc >> 24) & 0xff;
109     buf[len - 3] = (crc >> 16) & 0xff;
110     buf[len - 2] = (crc >> 8) & 0xff;
111     buf[len - 1] = (crc) & 0xff;
112
113     /* send each packet */
114     buf_ptr = buf;
115     while (len > 0) {
116         first = (buf == buf_ptr);
117         q = packet;
118         *q++ = 0x47;
119         b = (s->pid >> 8);
120         if (first)
121             b |= 0x40;
122         *q++ = b;
123         *q++ = s->pid;
124         s->cc = (s->cc + 1) & 0xf;
125         *q++ = 0x10 | s->cc;
126         if (first)
127             *q++ = 0; /* 0 offset */
128         len1 = TS_PACKET_SIZE - (q - packet);
129         if (len1 > len)
130             len1 = len;
131         memcpy(q, buf_ptr, len1);
132         q += len1;
133         /* add known padding data */
134         left = TS_PACKET_SIZE - (q - packet);
135         if (left > 0)
136             memset(q, 0xff, left);
137
138         s->write_packet(s, packet);
139
140         buf_ptr += len1;
141         len -= len1;
142     }
143 }
144
145 static inline void put16(uint8_t **q_ptr, int val)
146 {
147     uint8_t *q;
148     q = *q_ptr;
149     *q++ = val >> 8;
150     *q++ = val;
151     *q_ptr = q;
152 }
153
154 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
155                           int version, int sec_num, int last_sec_num,
156                           uint8_t *buf, int len)
157 {
158     uint8_t section[1024], *q;
159     unsigned int tot_len;
160     /* reserved_future_use field must be set to 1 for SDT */
161     unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
162
163     tot_len = 3 + 5 + len + 4;
164     /* check if not too big */
165     if (tot_len > 1024)
166         return -1;
167
168     q = section;
169     *q++ = tid;
170     put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
171     put16(&q, id);
172     *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
173     *q++ = sec_num;
174     *q++ = last_sec_num;
175     memcpy(q, buf, len);
176
177     mpegts_write_section(s, section, tot_len);
178     return 0;
179 }
180
181 /*********************************************/
182 /* mpegts writer */
183
184 #define DEFAULT_PROVIDER_NAME   "FFmpeg"
185 #define DEFAULT_SERVICE_NAME    "Service01"
186
187 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
188 #define DEFAULT_PES_HEADER_FREQ 16
189 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
190
191 /* we retransmit the SI info at this rate */
192 #define SDT_RETRANS_TIME 500
193 #define PAT_RETRANS_TIME 100
194 #define PCR_RETRANS_TIME 20
195
196 typedef struct MpegTSWriteStream {
197     struct MpegTSService *service;
198     int pid; /* stream associated pid */
199     int cc;
200     int payload_index;
201     int first_pts_check; ///< first pts check needed
202     int64_t payload_pts;
203     int64_t payload_dts;
204     uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
205     ADTSContext *adts;
206 } MpegTSWriteStream;
207
208 static void mpegts_write_pat(AVFormatContext *s)
209 {
210     MpegTSWrite *ts = s->priv_data;
211     MpegTSService *service;
212     uint8_t data[1012], *q;
213     int i;
214
215     q = data;
216     for(i = 0; i < ts->nb_services; i++) {
217         service = ts->services[i];
218         put16(&q, service->sid);
219         put16(&q, 0xe000 | service->pmt.pid);
220     }
221     mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
222                           data, q - data);
223 }
224
225 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
226 {
227     //    MpegTSWrite *ts = s->priv_data;
228     uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
229     int val, stream_type, i;
230
231     q = data;
232     put16(&q, 0xe000 | service->pcr_pid);
233
234     program_info_length_ptr = q;
235     q += 2; /* patched after */
236
237     /* put program info here */
238
239     val = 0xf000 | (q - program_info_length_ptr - 2);
240     program_info_length_ptr[0] = val >> 8;
241     program_info_length_ptr[1] = val;
242
243     for(i = 0; i < s->nb_streams; i++) {
244         AVStream *st = s->streams[i];
245         MpegTSWriteStream *ts_st = st->priv_data;
246         AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
247         switch(st->codec->codec_id) {
248         case CODEC_ID_MPEG1VIDEO:
249         case CODEC_ID_MPEG2VIDEO:
250             stream_type = STREAM_TYPE_VIDEO_MPEG2;
251             break;
252         case CODEC_ID_MPEG4:
253             stream_type = STREAM_TYPE_VIDEO_MPEG4;
254             break;
255         case CODEC_ID_H264:
256             stream_type = STREAM_TYPE_VIDEO_H264;
257             break;
258         case CODEC_ID_DIRAC:
259             stream_type = STREAM_TYPE_VIDEO_DIRAC;
260             break;
261         case CODEC_ID_MP2:
262         case CODEC_ID_MP3:
263             stream_type = STREAM_TYPE_AUDIO_MPEG1;
264             break;
265         case CODEC_ID_AAC:
266             stream_type = STREAM_TYPE_AUDIO_AAC;
267             break;
268         case CODEC_ID_AAC_LATM:
269             stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
270             break;
271         case CODEC_ID_AC3:
272             stream_type = STREAM_TYPE_AUDIO_AC3;
273             break;
274         default:
275             stream_type = STREAM_TYPE_PRIVATE_DATA;
276             break;
277         }
278         *q++ = stream_type;
279         put16(&q, 0xe000 | ts_st->pid);
280         desc_length_ptr = q;
281         q += 2; /* patched after */
282
283         /* write optional descriptors here */
284         switch(st->codec->codec_type) {
285         case AVMEDIA_TYPE_AUDIO:
286             if (lang && strlen(lang->value) == 3) {
287                 *q++ = 0x0a; /* ISO 639 language descriptor */
288                 *q++ = 4;
289                 *q++ = lang->value[0];
290                 *q++ = lang->value[1];
291                 *q++ = lang->value[2];
292                 *q++ = 0; /* undefined type */
293             }
294             break;
295         case AVMEDIA_TYPE_SUBTITLE:
296             {
297                 const char *language;
298                 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
299                 *q++ = 0x59;
300                 *q++ = 8;
301                 *q++ = language[0];
302                 *q++ = language[1];
303                 *q++ = language[2];
304                 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
305                 if(st->codec->extradata_size == 4) {
306                     memcpy(q, st->codec->extradata, 4);
307                     q += 4;
308                 } else {
309                     put16(&q, 1); /* page id */
310                     put16(&q, 1); /* ancillary page id */
311                 }
312             }
313             break;
314         case AVMEDIA_TYPE_VIDEO:
315             if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
316                 *q++ = 0x05; /*MPEG-2 registration descriptor*/
317                 *q++ = 4;
318                 *q++ = 'd';
319                 *q++ = 'r';
320                 *q++ = 'a';
321                 *q++ = 'c';
322             }
323             break;
324         }
325
326         val = 0xf000 | (q - desc_length_ptr - 2);
327         desc_length_ptr[0] = val >> 8;
328         desc_length_ptr[1] = val;
329     }
330     mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
331                           data, q - data);
332 }
333
334 /* NOTE: str == NULL is accepted for an empty string */
335 static void putstr8(uint8_t **q_ptr, const char *str)
336 {
337     uint8_t *q;
338     int len;
339
340     q = *q_ptr;
341     if (!str)
342         len = 0;
343     else
344         len = strlen(str);
345     *q++ = len;
346     memcpy(q, str, len);
347     q += len;
348     *q_ptr = q;
349 }
350
351 static void mpegts_write_sdt(AVFormatContext *s)
352 {
353     MpegTSWrite *ts = s->priv_data;
354     MpegTSService *service;
355     uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
356     int i, running_status, free_ca_mode, val;
357
358     q = data;
359     put16(&q, ts->onid);
360     *q++ = 0xff;
361     for(i = 0; i < ts->nb_services; i++) {
362         service = ts->services[i];
363         put16(&q, service->sid);
364         *q++ = 0xfc | 0x00; /* currently no EIT info */
365         desc_list_len_ptr = q;
366         q += 2;
367         running_status = 4; /* running */
368         free_ca_mode = 0;
369
370         /* write only one descriptor for the service name and provider */
371         *q++ = 0x48;
372         desc_len_ptr = q;
373         q++;
374         *q++ = 0x01; /* digital television service */
375         putstr8(&q, service->provider_name);
376         putstr8(&q, service->name);
377         desc_len_ptr[0] = q - desc_len_ptr - 1;
378
379         /* fill descriptor length */
380         val = (running_status << 13) | (free_ca_mode << 12) |
381             (q - desc_list_len_ptr - 2);
382         desc_list_len_ptr[0] = val >> 8;
383         desc_list_len_ptr[1] = val;
384     }
385     mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
386                           data, q - data);
387 }
388
389 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
390                                          int sid,
391                                          const char *provider_name,
392                                          const char *name)
393 {
394     MpegTSService *service;
395
396     service = av_mallocz(sizeof(MpegTSService));
397     if (!service)
398         return NULL;
399     service->pmt.pid = ts->pmt_start_pid + ts->nb_services - 1;
400     service->sid = sid;
401     service->provider_name = av_strdup(provider_name);
402     service->name = av_strdup(name);
403     service->pcr_pid = 0x1fff;
404     dynarray_add(&ts->services, &ts->nb_services, service);
405     return service;
406 }
407
408 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
409 {
410     AVFormatContext *ctx = s->opaque;
411     put_buffer(ctx->pb, packet, TS_PACKET_SIZE);
412 }
413
414 static int mpegts_write_header(AVFormatContext *s)
415 {
416     MpegTSWrite *ts = s->priv_data;
417     MpegTSWriteStream *ts_st;
418     MpegTSService *service;
419     AVStream *st, *pcr_st = NULL;
420     AVMetadataTag *title, *provider;
421     int i, j;
422     const char *service_name;
423     const char *provider_name;
424     int *pids;
425
426     ts->tsid = ts->transport_stream_id;
427     ts->onid = ts->original_network_id;
428     /* allocate a single DVB service */
429     title = av_metadata_get(s->metadata, "service_name", NULL, 0);
430     if (!title)
431         title = av_metadata_get(s->metadata, "title", NULL, 0);
432     service_name = title ? title->value : DEFAULT_SERVICE_NAME;
433     provider = av_metadata_get(s->metadata, "service_provider", NULL, 0);
434     provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
435     service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
436     service->pmt.write_packet = section_write_packet;
437     service->pmt.opaque = s;
438     service->pmt.cc = 15;
439
440     ts->pat.pid = PAT_PID;
441     ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
442     ts->pat.write_packet = section_write_packet;
443     ts->pat.opaque = s;
444
445     ts->sdt.pid = SDT_PID;
446     ts->sdt.cc = 15;
447     ts->sdt.write_packet = section_write_packet;
448     ts->sdt.opaque = s;
449
450     pids = av_malloc(s->nb_streams * sizeof(*pids));
451     if (!pids)
452         return AVERROR(ENOMEM);
453
454     /* assign pids to each stream */
455     for(i = 0;i < s->nb_streams; i++) {
456         st = s->streams[i];
457         ts_st = av_mallocz(sizeof(MpegTSWriteStream));
458         if (!ts_st)
459             goto fail;
460         st->priv_data = ts_st;
461         ts_st->service = service;
462         /* MPEG pid values < 16 are reserved. Applications which set st->id in
463          * this range are assigned a calculated pid. */
464         if (st->id < 16) {
465             ts_st->pid = ts->start_pid + i;
466         } else if (st->id < 0x1FFF) {
467             ts_st->pid = st->id;
468         } else {
469             av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
470             goto fail;
471         }
472         if (ts_st->pid == service->pmt.pid) {
473             av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
474             goto fail;
475         }
476         for (j = 0; j < i; j++)
477             if (pids[j] == ts_st->pid) {
478                 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
479                 goto fail;
480             }
481         pids[i] = ts_st->pid;
482         ts_st->payload_pts = AV_NOPTS_VALUE;
483         ts_st->payload_dts = AV_NOPTS_VALUE;
484         ts_st->first_pts_check = 1;
485         ts_st->cc = 15;
486         /* update PCR pid by using the first video stream */
487         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
488             service->pcr_pid == 0x1fff) {
489             service->pcr_pid = ts_st->pid;
490             pcr_st = st;
491         }
492         if (st->codec->codec_id == CODEC_ID_AAC &&
493             st->codec->extradata_size > 0) {
494             ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
495             if (!ts_st->adts)
496                 return AVERROR(ENOMEM);
497             if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
498                                          st->codec->extradata_size) < 0)
499                 return -1;
500         }
501     }
502
503     av_free(pids);
504
505     /* if no video stream, use the first stream as PCR */
506     if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
507         pcr_st = s->streams[0];
508         ts_st = pcr_st->priv_data;
509         service->pcr_pid = ts_st->pid;
510     }
511
512     ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
513
514     if (ts->mux_rate > 1) {
515         service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
516             (TS_PACKET_SIZE * 8 * 1000);
517         ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /
518             (TS_PACKET_SIZE * 8 * 1000);
519         ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
520             (TS_PACKET_SIZE * 8 * 1000);
521
522         ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
523     } else {
524         /* Arbitrary values, PAT/PMT could be written on key frames */
525         ts->sdt_packet_period = 200;
526         ts->pat_packet_period = 40;
527         if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
528             if (!pcr_st->codec->frame_size) {
529                 av_log(s, AV_LOG_WARNING, "frame size not set\n");
530                 service->pcr_packet_period =
531                     pcr_st->codec->sample_rate/(10*512);
532             } else {
533                 service->pcr_packet_period =
534                     pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
535             }
536         } else {
537             // max delta PCR 0.1s
538             service->pcr_packet_period =
539                 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
540         }
541     }
542
543     // output a PCR as soon as possible
544     service->pcr_packet_count = service->pcr_packet_period;
545     ts->pat_packet_count = ts->pat_packet_period-1;
546     ts->sdt_packet_count = ts->sdt_packet_period-1;
547
548     if (ts->mux_rate == 1)
549         av_log(s, AV_LOG_INFO, "muxrate VBR, ");
550     else
551         av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
552     av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
553            "sdt every %d, pat/pmt every %d pkts\n",
554            service->pcr_packet_period,
555            ts->sdt_packet_period, ts->pat_packet_period);
556
557     put_flush_packet(s->pb);
558
559     return 0;
560
561  fail:
562     av_free(pids);
563     for(i = 0;i < s->nb_streams; i++) {
564         st = s->streams[i];
565         av_free(st->priv_data);
566     }
567     return -1;
568 }
569
570 /* send SDT, PAT and PMT tables regulary */
571 static void retransmit_si_info(AVFormatContext *s)
572 {
573     MpegTSWrite *ts = s->priv_data;
574     int i;
575
576     if (++ts->sdt_packet_count == ts->sdt_packet_period) {
577         ts->sdt_packet_count = 0;
578         mpegts_write_sdt(s);
579     }
580     if (++ts->pat_packet_count == ts->pat_packet_period) {
581         ts->pat_packet_count = 0;
582         mpegts_write_pat(s);
583         for(i = 0; i < ts->nb_services; i++) {
584             mpegts_write_pmt(s, ts->services[i]);
585         }
586     }
587 }
588
589 static int64_t get_pcr(const MpegTSWrite *ts, ByteIOContext *pb)
590 {
591     return av_rescale(url_ftell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
592            ts->first_pcr;
593 }
594
595 static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
596 {
597     int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
598
599     *buf++ = pcr_high >> 25;
600     *buf++ = pcr_high >> 17;
601     *buf++ = pcr_high >> 9;
602     *buf++ = pcr_high >> 1;
603     *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
604     *buf++ = pcr_low;
605
606     return buf;
607 }
608
609 /* Write a single null transport stream packet */
610 static void mpegts_insert_null_packet(AVFormatContext *s)
611 {
612     uint8_t *q;
613     uint8_t buf[TS_PACKET_SIZE];
614
615     q = buf;
616     *q++ = 0x47;
617     *q++ = 0x00 | 0x1f;
618     *q++ = 0xff;
619     *q++ = 0x10;
620     memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
621     put_buffer(s->pb, buf, TS_PACKET_SIZE);
622 }
623
624 /* Write a single transport stream packet with a PCR and no payload */
625 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
626 {
627     MpegTSWrite *ts = s->priv_data;
628     MpegTSWriteStream *ts_st = st->priv_data;
629     uint8_t *q;
630     uint8_t buf[TS_PACKET_SIZE];
631
632     q = buf;
633     *q++ = 0x47;
634     *q++ = ts_st->pid >> 8;
635     *q++ = ts_st->pid;
636     *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
637     /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
638     *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
639     *q++ = 0x10;               /* Adaptation flags: PCR present */
640
641     /* PCR coded into 6 bytes */
642     q = write_pcr_bits(q, get_pcr(ts, s->pb));
643
644     /* stuffing bytes */
645     memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
646     put_buffer(s->pb, buf, TS_PACKET_SIZE);
647 }
648
649 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
650 {
651     int val;
652
653     val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
654     *q++ = val;
655     val = (((pts >> 15) & 0x7fff) << 1) | 1;
656     *q++ = val >> 8;
657     *q++ = val;
658     val = (((pts) & 0x7fff) << 1) | 1;
659     *q++ = val >> 8;
660     *q++ = val;
661 }
662
663 /* Add a pes header to the front of payload, and segment into an integer number of
664  * ts packets. The final ts packet is padded using an over-sized adaptation header
665  * to exactly fill the last ts packet.
666  * NOTE: 'payload' contains a complete PES payload.
667  */
668 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
669                              const uint8_t *payload, int payload_size,
670                              int64_t pts, int64_t dts)
671 {
672     MpegTSWriteStream *ts_st = st->priv_data;
673     MpegTSWrite *ts = s->priv_data;
674     uint8_t buf[TS_PACKET_SIZE];
675     uint8_t *q;
676     int val, is_start, len, header_len, write_pcr, private_code, flags;
677     int afc_len, stuffing_len;
678     int64_t pcr = -1; /* avoid warning */
679     int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
680
681     is_start = 1;
682     while (payload_size > 0) {
683         retransmit_si_info(s);
684
685         write_pcr = 0;
686         if (ts_st->pid == ts_st->service->pcr_pid) {
687             if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
688                 ts_st->service->pcr_packet_count++;
689             if (ts_st->service->pcr_packet_count >=
690                 ts_st->service->pcr_packet_period) {
691                 ts_st->service->pcr_packet_count = 0;
692                 write_pcr = 1;
693             }
694         }
695
696         if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
697             (dts - get_pcr(ts, s->pb)/300) > delay) {
698             /* pcr insert gets priority over null packet insert */
699             if (write_pcr)
700                 mpegts_insert_pcr_only(s, st);
701             else
702                 mpegts_insert_null_packet(s);
703             continue; /* recalculate write_pcr and possibly retransmit si_info */
704         }
705
706         /* prepare packet header */
707         q = buf;
708         *q++ = 0x47;
709         val = (ts_st->pid >> 8);
710         if (is_start)
711             val |= 0x40;
712         *q++ = val;
713         *q++ = ts_st->pid;
714         ts_st->cc = (ts_st->cc + 1) & 0xf;
715         *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
716         if (write_pcr) {
717             // add 11, pcr references the last byte of program clock reference base
718             if (ts->mux_rate > 1)
719                 pcr = get_pcr(ts, s->pb);
720             else
721                 pcr = (dts - delay)*300;
722             if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
723                 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
724             *q++ = 7; /* AFC length */
725             *q++ = 0x10; /* flags: PCR present */
726             q = write_pcr_bits(q, pcr);
727         }
728         if (is_start) {
729             int pes_extension = 0;
730             /* write PES header */
731             *q++ = 0x00;
732             *q++ = 0x00;
733             *q++ = 0x01;
734             private_code = 0;
735             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
736                 if (st->codec->codec_id == CODEC_ID_DIRAC) {
737                     *q++ = 0xfd;
738                 } else
739                     *q++ = 0xe0;
740             } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
741                        (st->codec->codec_id == CODEC_ID_MP2 ||
742                         st->codec->codec_id == CODEC_ID_MP3)) {
743                 *q++ = 0xc0;
744             } else {
745                 *q++ = 0xbd;
746                 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
747                     private_code = 0x20;
748                 }
749             }
750             header_len = 0;
751             flags = 0;
752             if (pts != AV_NOPTS_VALUE) {
753                 header_len += 5;
754                 flags |= 0x80;
755             }
756             if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
757                 header_len += 5;
758                 flags |= 0x40;
759             }
760             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
761                 st->codec->codec_id == CODEC_ID_DIRAC) {
762                 /* set PES_extension_flag */
763                 pes_extension = 1;
764                 flags |= 0x01;
765
766                 /*
767                 * One byte for PES2 extension flag +
768                 * one byte for extension length +
769                 * one byte for extension id
770                 */
771                 header_len += 3;
772             }
773             len = payload_size + header_len + 3;
774             if (private_code != 0)
775                 len++;
776             if (len > 0xffff)
777                 len = 0;
778             *q++ = len >> 8;
779             *q++ = len;
780             val = 0x80;
781             /* data alignment indicator is required for subtitle data */
782             if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
783                 val |= 0x04;
784             *q++ = val;
785             *q++ = flags;
786             *q++ = header_len;
787             if (pts != AV_NOPTS_VALUE) {
788                 write_pts(q, flags >> 6, pts);
789                 q += 5;
790             }
791             if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
792                 write_pts(q, 1, dts);
793                 q += 5;
794             }
795             if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
796                 flags = 0x01;  /* set PES_extension_flag_2 */
797                 *q++ = flags;
798                 *q++ = 0x80 | 0x01;  /* marker bit + extension length */
799                 /*
800                 * Set the stream id extension flag bit to 0 and
801                 * write the extended stream id
802                 */
803                 *q++ = 0x00 | 0x60;
804             }
805             if (private_code != 0)
806                 *q++ = private_code;
807             is_start = 0;
808         }
809         /* header size */
810         header_len = q - buf;
811         /* data len */
812         len = TS_PACKET_SIZE - header_len;
813         if (len > payload_size)
814             len = payload_size;
815         stuffing_len = TS_PACKET_SIZE - header_len - len;
816         if (stuffing_len > 0) {
817             /* add stuffing with AFC */
818             if (buf[3] & 0x20) {
819                 /* stuffing already present: increase its size */
820                 afc_len = buf[4] + 1;
821                 memmove(buf + 4 + afc_len + stuffing_len,
822                         buf + 4 + afc_len,
823                         header_len - (4 + afc_len));
824                 buf[4] += stuffing_len;
825                 memset(buf + 4 + afc_len, 0xff, stuffing_len);
826             } else {
827                 /* add stuffing */
828                 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
829                 buf[3] |= 0x20;
830                 buf[4] = stuffing_len - 1;
831                 if (stuffing_len >= 2) {
832                     buf[5] = 0x00;
833                     memset(buf + 6, 0xff, stuffing_len - 2);
834                 }
835             }
836         }
837         memcpy(buf + TS_PACKET_SIZE - len, payload, len);
838         payload += len;
839         payload_size -= len;
840         put_buffer(s->pb, buf, TS_PACKET_SIZE);
841     }
842     put_flush_packet(s->pb);
843 }
844
845 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
846 {
847     AVStream *st = s->streams[pkt->stream_index];
848     int size = pkt->size;
849     uint8_t *buf= pkt->data;
850     uint8_t *data= NULL;
851     MpegTSWriteStream *ts_st = st->priv_data;
852     const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
853     int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
854
855     if (pkt->pts != AV_NOPTS_VALUE)
856         pts = pkt->pts + delay;
857     if (pkt->dts != AV_NOPTS_VALUE)
858         dts = pkt->dts + delay;
859
860     if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
861         av_log(s, AV_LOG_ERROR, "first pts value must set\n");
862         return -1;
863     }
864     ts_st->first_pts_check = 0;
865
866     if (st->codec->codec_id == CODEC_ID_H264) {
867         const uint8_t *p = buf, *buf_end = p+size;
868         uint32_t state = -1;
869
870         if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
871             av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
872                    "no startcode found, use -vbsf h264_mp4toannexb\n");
873             return -1;
874         }
875
876         do {
877             p = ff_find_start_code(p, buf_end, &state);
878             //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
879         } while (p < buf_end && (state & 0x1f) != 9 &&
880                  (state & 0x1f) != 5 && (state & 0x1f) != 1);
881
882         if ((state & 0x1f) != 9) { // AUD NAL
883             data = av_malloc(pkt->size+6);
884             if (!data)
885                 return -1;
886             memcpy(data+6, pkt->data, pkt->size);
887             AV_WB32(data, 0x00000001);
888             data[4] = 0x09;
889             data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
890             buf  = data;
891             size = pkt->size+6;
892         }
893     } else if (st->codec->codec_id == CODEC_ID_AAC) {
894         if (pkt->size < 2)
895             return -1;
896         if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
897             ADTSContext *adts = ts_st->adts;
898             int new_size;
899             if (!adts) {
900                 av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
901                        "and extradata missing\n");
902                 return -1;
903             }
904             new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
905             if ((unsigned)new_size >= INT_MAX)
906                 return -1;
907             data = av_malloc(new_size);
908             if (!data)
909                 return AVERROR(ENOMEM);
910             ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
911             if (adts->pce_size) {
912                 memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
913                 adts->pce_size = 0;
914             }
915             memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
916             buf = data;
917             size = new_size;
918         }
919     }
920
921     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
922         // for video and subtitle, write a single pes packet
923         mpegts_write_pes(s, st, buf, size, pts, dts);
924         av_free(data);
925         return 0;
926     }
927
928     if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
929         mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
930                          ts_st->payload_pts, ts_st->payload_dts);
931         ts_st->payload_index = 0;
932     }
933
934     if (!ts_st->payload_index) {
935         ts_st->payload_pts = pts;
936         ts_st->payload_dts = dts;
937     }
938
939     memcpy(ts_st->payload + ts_st->payload_index, buf, size);
940     ts_st->payload_index += size;
941
942     av_free(data);
943
944     return 0;
945 }
946
947 static int mpegts_write_end(AVFormatContext *s)
948 {
949     MpegTSWrite *ts = s->priv_data;
950     MpegTSWriteStream *ts_st;
951     MpegTSService *service;
952     AVStream *st;
953     int i;
954
955     /* flush current packets */
956     for(i = 0; i < s->nb_streams; i++) {
957         st = s->streams[i];
958         ts_st = st->priv_data;
959         if (ts_st->payload_index > 0) {
960             mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
961                              ts_st->payload_pts, ts_st->payload_dts);
962         }
963         av_freep(&ts_st->adts);
964     }
965     put_flush_packet(s->pb);
966
967     for(i = 0; i < ts->nb_services; i++) {
968         service = ts->services[i];
969         av_freep(&service->provider_name);
970         av_freep(&service->name);
971         av_free(service);
972     }
973     av_free(ts->services);
974
975     return 0;
976 }
977
978 AVOutputFormat ff_mpegts_muxer = {
979     "mpegts",
980     NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
981     "video/x-mpegts",
982     "ts,m2t",
983     sizeof(MpegTSWrite),
984     CODEC_ID_MP2,
985     CODEC_ID_MPEG2VIDEO,
986     mpegts_write_header,
987     mpegts_write_packet,
988     mpegts_write_end,
989     .priv_class = &mpegts_muxer_class,
990 };