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