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.

920 lines
29KB

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