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