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