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