You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1494 lines
50KB

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