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