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.

955 lines
30KB

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