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