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