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