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.

961 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. #define PCR_TIME_BASE 27000000
  29. /* write DVB SI sections */
  30. /*********************************************/
  31. /* mpegts section writer */
  32. typedef struct MpegTSSection {
  33. int pid;
  34. int cc;
  35. void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
  36. void *opaque;
  37. } MpegTSSection;
  38. typedef struct MpegTSService {
  39. MpegTSSection pmt; /* MPEG2 pmt table context */
  40. int sid; /* service ID */
  41. char *name;
  42. char *provider_name;
  43. int pcr_pid;
  44. int pcr_packet_count;
  45. int pcr_packet_period;
  46. } MpegTSService;
  47. typedef struct MpegTSWrite {
  48. MpegTSSection pat; /* MPEG2 pat table */
  49. MpegTSSection sdt; /* MPEG2 sdt table context */
  50. MpegTSService **services;
  51. int sdt_packet_count;
  52. int sdt_packet_period;
  53. int pat_packet_count;
  54. int pat_packet_period;
  55. int nb_services;
  56. int onid;
  57. int tsid;
  58. int64_t first_pcr;
  59. int mux_rate; ///< set to 1 when VBR
  60. } MpegTSWrite;
  61. /* NOTE: 4 bytes must be left at the end for the crc32 */
  62. static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
  63. {
  64. MpegTSWrite *ts = ((AVFormatContext*)s->opaque)->priv_data;
  65. unsigned int crc;
  66. unsigned char packet[TS_PACKET_SIZE];
  67. const unsigned char *buf_ptr;
  68. unsigned char *q;
  69. int first, b, len1, left;
  70. crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
  71. buf[len - 4] = (crc >> 24) & 0xff;
  72. buf[len - 3] = (crc >> 16) & 0xff;
  73. buf[len - 2] = (crc >> 8) & 0xff;
  74. buf[len - 1] = (crc) & 0xff;
  75. /* send each packet */
  76. buf_ptr = buf;
  77. while (len > 0) {
  78. first = (buf == buf_ptr);
  79. q = packet;
  80. *q++ = 0x47;
  81. b = (s->pid >> 8);
  82. if (first)
  83. b |= 0x40;
  84. *q++ = b;
  85. *q++ = s->pid;
  86. s->cc = (s->cc + 1) & 0xf;
  87. *q++ = 0x10 | s->cc;
  88. if (first)
  89. *q++ = 0; /* 0 offset */
  90. len1 = TS_PACKET_SIZE - (q - packet);
  91. if (len1 > len)
  92. len1 = len;
  93. memcpy(q, buf_ptr, len1);
  94. q += len1;
  95. /* add known padding data */
  96. left = TS_PACKET_SIZE - (q - packet);
  97. if (left > 0)
  98. memset(q, 0xff, left);
  99. s->write_packet(s, packet);
  100. buf_ptr += len1;
  101. len -= len1;
  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->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, 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. static int64_t get_pcr(const MpegTSWrite *ts, ByteIOContext *pb)
  499. {
  500. return av_rescale(url_ftell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
  501. ts->first_pcr;
  502. }
  503. static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
  504. {
  505. int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
  506. *buf++ = pcr_high >> 25;
  507. *buf++ = pcr_high >> 17;
  508. *buf++ = pcr_high >> 9;
  509. *buf++ = pcr_high >> 1;
  510. *buf++ = ((pcr_high & 1) << 7) | (pcr_low >> 8);
  511. *buf++ = pcr_low;
  512. return buf;
  513. }
  514. /* Write a single null transport stream packet */
  515. static void mpegts_insert_null_packet(AVFormatContext *s)
  516. {
  517. MpegTSWrite *ts = s->priv_data;
  518. uint8_t *q;
  519. uint8_t buf[TS_PACKET_SIZE];
  520. q = buf;
  521. *q++ = 0x47;
  522. *q++ = 0x00 | 0x1f;
  523. *q++ = 0xff;
  524. *q++ = 0x10;
  525. memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
  526. put_buffer(s->pb, buf, TS_PACKET_SIZE);
  527. }
  528. /* Write a single transport stream packet with a PCR and no payload */
  529. static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
  530. {
  531. MpegTSWrite *ts = s->priv_data;
  532. MpegTSWriteStream *ts_st = st->priv_data;
  533. uint8_t *q;
  534. uint8_t buf[TS_PACKET_SIZE];
  535. q = buf;
  536. *q++ = 0x47;
  537. *q++ = ts_st->pid >> 8;
  538. *q++ = ts_st->pid;
  539. *q++ = 0x20 | ts_st->cc; /* Adaptation only */
  540. /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
  541. *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
  542. *q++ = 0x10; /* Adaptation flags: PCR present */
  543. /* PCR coded into 6 bytes */
  544. q = write_pcr_bits(q, get_pcr(ts, s->pb));
  545. /* stuffing bytes */
  546. memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
  547. put_buffer(s->pb, buf, TS_PACKET_SIZE);
  548. }
  549. static void write_pts(uint8_t *q, int fourbits, int64_t pts)
  550. {
  551. int val;
  552. val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
  553. *q++ = val;
  554. val = (((pts >> 15) & 0x7fff) << 1) | 1;
  555. *q++ = val >> 8;
  556. *q++ = val;
  557. val = (((pts) & 0x7fff) << 1) | 1;
  558. *q++ = val >> 8;
  559. *q++ = val;
  560. }
  561. /* Add a pes header to the front of payload, and segment into an integer number of
  562. * ts packets. The final ts packet is padded using an over-sized adaptation header
  563. * to exactly fill the last ts packet.
  564. * NOTE: 'payload' contains a complete PES payload.
  565. */
  566. static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
  567. const uint8_t *payload, int payload_size,
  568. int64_t pts, int64_t dts)
  569. {
  570. MpegTSWriteStream *ts_st = st->priv_data;
  571. MpegTSWrite *ts = s->priv_data;
  572. uint8_t buf[TS_PACKET_SIZE];
  573. uint8_t *q;
  574. int val, is_start, len, header_len, write_pcr, private_code, flags;
  575. int afc_len, stuffing_len;
  576. int64_t pcr = -1; /* avoid warning */
  577. int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
  578. is_start = 1;
  579. while (payload_size > 0) {
  580. retransmit_si_info(s);
  581. write_pcr = 0;
  582. if (ts_st->pid == ts_st->service->pcr_pid) {
  583. if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
  584. ts_st->service->pcr_packet_count++;
  585. if (ts_st->service->pcr_packet_count >=
  586. ts_st->service->pcr_packet_period) {
  587. ts_st->service->pcr_packet_count = 0;
  588. write_pcr = 1;
  589. }
  590. }
  591. if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
  592. (dts - get_pcr(ts, s->pb)/300) > delay) {
  593. /* pcr insert gets priority over null packet insert */
  594. if (write_pcr)
  595. mpegts_insert_pcr_only(s, st);
  596. else
  597. mpegts_insert_null_packet(s);
  598. continue; /* recalculate write_pcr and possibly retransmit si_info */
  599. }
  600. /* prepare packet header */
  601. q = buf;
  602. *q++ = 0x47;
  603. val = (ts_st->pid >> 8);
  604. if (is_start)
  605. val |= 0x40;
  606. *q++ = val;
  607. *q++ = ts_st->pid;
  608. ts_st->cc = (ts_st->cc + 1) & 0xf;
  609. *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
  610. if (write_pcr) {
  611. // add 11, pcr references the last byte of program clock reference base
  612. if (ts->mux_rate > 1)
  613. pcr = get_pcr(ts, s->pb);
  614. else
  615. pcr = (dts - delay)*300;
  616. if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
  617. av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
  618. *q++ = 7; /* AFC length */
  619. *q++ = 0x10; /* flags: PCR present */
  620. q = write_pcr_bits(q, pcr);
  621. }
  622. if (is_start) {
  623. int pes_extension = 0;
  624. /* write PES header */
  625. *q++ = 0x00;
  626. *q++ = 0x00;
  627. *q++ = 0x01;
  628. private_code = 0;
  629. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  630. if (st->codec->codec_id == CODEC_ID_DIRAC) {
  631. *q++ = 0xfd;
  632. } else
  633. *q++ = 0xe0;
  634. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  635. (st->codec->codec_id == CODEC_ID_MP2 ||
  636. st->codec->codec_id == CODEC_ID_MP3)) {
  637. *q++ = 0xc0;
  638. } else {
  639. *q++ = 0xbd;
  640. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  641. private_code = 0x20;
  642. }
  643. }
  644. header_len = 0;
  645. flags = 0;
  646. if (pts != AV_NOPTS_VALUE) {
  647. header_len += 5;
  648. flags |= 0x80;
  649. }
  650. if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
  651. header_len += 5;
  652. flags |= 0x40;
  653. }
  654. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  655. st->codec->codec_id == CODEC_ID_DIRAC) {
  656. /* set PES_extension_flag */
  657. pes_extension = 1;
  658. flags |= 0x01;
  659. /*
  660. * One byte for PES2 extension flag +
  661. * one byte for extension length +
  662. * one byte for extension id
  663. */
  664. header_len += 3;
  665. }
  666. len = payload_size + header_len + 3;
  667. if (private_code != 0)
  668. len++;
  669. if (len > 0xffff)
  670. len = 0;
  671. *q++ = len >> 8;
  672. *q++ = len;
  673. val = 0x80;
  674. /* data alignment indicator is required for subtitle data */
  675. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
  676. val |= 0x04;
  677. *q++ = val;
  678. *q++ = flags;
  679. *q++ = header_len;
  680. if (pts != AV_NOPTS_VALUE) {
  681. write_pts(q, flags >> 6, pts);
  682. q += 5;
  683. }
  684. if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
  685. write_pts(q, 1, dts);
  686. q += 5;
  687. }
  688. if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
  689. flags = 0x01; /* set PES_extension_flag_2 */
  690. *q++ = flags;
  691. *q++ = 0x80 | 0x01; /* marker bit + extension length */
  692. /*
  693. * Set the stream id extension flag bit to 0 and
  694. * write the extended stream id
  695. */
  696. *q++ = 0x00 | 0x60;
  697. }
  698. if (private_code != 0)
  699. *q++ = private_code;
  700. is_start = 0;
  701. }
  702. /* header size */
  703. header_len = q - buf;
  704. /* data len */
  705. len = TS_PACKET_SIZE - header_len;
  706. if (len > payload_size)
  707. len = payload_size;
  708. stuffing_len = TS_PACKET_SIZE - header_len - len;
  709. if (stuffing_len > 0) {
  710. /* add stuffing with AFC */
  711. if (buf[3] & 0x20) {
  712. /* stuffing already present: increase its size */
  713. afc_len = buf[4] + 1;
  714. memmove(buf + 4 + afc_len + stuffing_len,
  715. buf + 4 + afc_len,
  716. header_len - (4 + afc_len));
  717. buf[4] += stuffing_len;
  718. memset(buf + 4 + afc_len, 0xff, stuffing_len);
  719. } else {
  720. /* add stuffing */
  721. memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
  722. buf[3] |= 0x20;
  723. buf[4] = stuffing_len - 1;
  724. if (stuffing_len >= 2) {
  725. buf[5] = 0x00;
  726. memset(buf + 6, 0xff, stuffing_len - 2);
  727. }
  728. }
  729. }
  730. memcpy(buf + TS_PACKET_SIZE - len, payload, len);
  731. payload += len;
  732. payload_size -= len;
  733. put_buffer(s->pb, buf, TS_PACKET_SIZE);
  734. }
  735. put_flush_packet(s->pb);
  736. }
  737. static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
  738. {
  739. AVStream *st = s->streams[pkt->stream_index];
  740. int size = pkt->size;
  741. uint8_t *buf= pkt->data;
  742. uint8_t *data= NULL;
  743. MpegTSWriteStream *ts_st = st->priv_data;
  744. const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
  745. int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
  746. if (pkt->pts != AV_NOPTS_VALUE)
  747. pts = pkt->pts + delay;
  748. if (pkt->dts != AV_NOPTS_VALUE)
  749. dts = pkt->dts + delay;
  750. if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
  751. av_log(s, AV_LOG_ERROR, "first pts value must set\n");
  752. return -1;
  753. }
  754. ts_st->first_pts_check = 0;
  755. if (st->codec->codec_id == CODEC_ID_H264) {
  756. const uint8_t *p = buf, *buf_end = p+size;
  757. uint32_t state = -1;
  758. if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
  759. av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
  760. "no startcode found, use -vbsf h264_mp4toannexb\n");
  761. return -1;
  762. }
  763. do {
  764. p = ff_find_start_code(p, buf_end, &state);
  765. //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
  766. } while (p < buf_end && (state & 0x1f) != 9 &&
  767. (state & 0x1f) != 5 && (state & 0x1f) != 1);
  768. if ((state & 0x1f) != 9) { // AUD NAL
  769. data = av_malloc(pkt->size+6);
  770. if (!data)
  771. return -1;
  772. memcpy(data+6, pkt->data, pkt->size);
  773. AV_WB32(data, 0x00000001);
  774. data[4] = 0x09;
  775. data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
  776. buf = data;
  777. size = pkt->size+6;
  778. }
  779. } else if (st->codec->codec_id == CODEC_ID_AAC) {
  780. if (pkt->size < 2)
  781. return -1;
  782. if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
  783. ADTSContext *adts = ts_st->adts;
  784. int new_size;
  785. if (!adts) {
  786. av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
  787. "and extradata missing\n");
  788. return -1;
  789. }
  790. new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
  791. if ((unsigned)new_size >= INT_MAX)
  792. return -1;
  793. data = av_malloc(new_size);
  794. if (!data)
  795. return AVERROR(ENOMEM);
  796. ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
  797. if (adts->pce_size) {
  798. memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
  799. adts->pce_size = 0;
  800. }
  801. memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
  802. buf = data;
  803. size = new_size;
  804. }
  805. }
  806. if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
  807. // for video and subtitle, write a single pes packet
  808. mpegts_write_pes(s, st, buf, size, pts, dts);
  809. av_free(data);
  810. return 0;
  811. }
  812. if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
  813. mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
  814. ts_st->payload_pts, ts_st->payload_dts);
  815. ts_st->payload_index = 0;
  816. }
  817. if (!ts_st->payload_index) {
  818. ts_st->payload_pts = pts;
  819. ts_st->payload_dts = dts;
  820. }
  821. memcpy(ts_st->payload + ts_st->payload_index, buf, size);
  822. ts_st->payload_index += size;
  823. av_free(data);
  824. return 0;
  825. }
  826. static int mpegts_write_end(AVFormatContext *s)
  827. {
  828. MpegTSWrite *ts = s->priv_data;
  829. MpegTSWriteStream *ts_st;
  830. MpegTSService *service;
  831. AVStream *st;
  832. int i;
  833. /* flush current packets */
  834. for(i = 0; i < s->nb_streams; i++) {
  835. st = s->streams[i];
  836. ts_st = st->priv_data;
  837. if (ts_st->payload_index > 0) {
  838. mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
  839. ts_st->payload_pts, ts_st->payload_dts);
  840. }
  841. av_freep(&ts_st->adts);
  842. }
  843. put_flush_packet(s->pb);
  844. for(i = 0; i < ts->nb_services; i++) {
  845. service = ts->services[i];
  846. av_freep(&service->provider_name);
  847. av_freep(&service->name);
  848. av_free(service);
  849. }
  850. av_free(ts->services);
  851. return 0;
  852. }
  853. AVOutputFormat mpegts_muxer = {
  854. "mpegts",
  855. NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  856. "video/x-mpegts",
  857. "ts,m2t",
  858. sizeof(MpegTSWrite),
  859. CODEC_ID_MP2,
  860. CODEC_ID_MPEG2VIDEO,
  861. mpegts_write_header,
  862. mpegts_write_packet,
  863. mpegts_write_end,
  864. };