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.

963 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. 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. }
  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 AVMEDIA_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 AVMEDIA_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. if(st->codec->extradata_size == 4) {
  247. memcpy(q, st->codec->extradata, 4);
  248. q += 4;
  249. } else {
  250. put16(&q, 1); /* page id */
  251. put16(&q, 1); /* ancillary page id */
  252. }
  253. }
  254. break;
  255. case AVMEDIA_TYPE_VIDEO:
  256. if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
  257. *q++ = 0x05; /*MPEG-2 registration descriptor*/
  258. *q++ = 4;
  259. *q++ = 'd';
  260. *q++ = 'r';
  261. *q++ = 'a';
  262. *q++ = 'c';
  263. }
  264. break;
  265. }
  266. val = 0xf000 | (q - desc_length_ptr - 2);
  267. desc_length_ptr[0] = val >> 8;
  268. desc_length_ptr[1] = val;
  269. }
  270. mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
  271. data, q - data);
  272. }
  273. /* NOTE: str == NULL is accepted for an empty string */
  274. static void putstr8(uint8_t **q_ptr, const char *str)
  275. {
  276. uint8_t *q;
  277. int len;
  278. q = *q_ptr;
  279. if (!str)
  280. len = 0;
  281. else
  282. len = strlen(str);
  283. *q++ = len;
  284. memcpy(q, str, len);
  285. q += len;
  286. *q_ptr = q;
  287. }
  288. static void mpegts_write_sdt(AVFormatContext *s)
  289. {
  290. MpegTSWrite *ts = s->priv_data;
  291. MpegTSService *service;
  292. uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
  293. int i, running_status, free_ca_mode, val;
  294. q = data;
  295. put16(&q, ts->onid);
  296. *q++ = 0xff;
  297. for(i = 0; i < ts->nb_services; i++) {
  298. service = ts->services[i];
  299. put16(&q, service->sid);
  300. *q++ = 0xfc | 0x00; /* currently no EIT info */
  301. desc_list_len_ptr = q;
  302. q += 2;
  303. running_status = 4; /* running */
  304. free_ca_mode = 0;
  305. /* write only one descriptor for the service name and provider */
  306. *q++ = 0x48;
  307. desc_len_ptr = q;
  308. q++;
  309. *q++ = 0x01; /* digital television service */
  310. putstr8(&q, service->provider_name);
  311. putstr8(&q, service->name);
  312. desc_len_ptr[0] = q - desc_len_ptr - 1;
  313. /* fill descriptor length */
  314. val = (running_status << 13) | (free_ca_mode << 12) |
  315. (q - desc_list_len_ptr - 2);
  316. desc_list_len_ptr[0] = val >> 8;
  317. desc_list_len_ptr[1] = val;
  318. }
  319. mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
  320. data, q - data);
  321. }
  322. static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
  323. int sid,
  324. const char *provider_name,
  325. const char *name)
  326. {
  327. MpegTSService *service;
  328. service = av_mallocz(sizeof(MpegTSService));
  329. if (!service)
  330. return NULL;
  331. service->pmt.pid = DEFAULT_PMT_START_PID + ts->nb_services - 1;
  332. service->sid = sid;
  333. service->provider_name = av_strdup(provider_name);
  334. service->name = av_strdup(name);
  335. service->pcr_pid = 0x1fff;
  336. dynarray_add(&ts->services, &ts->nb_services, service);
  337. return service;
  338. }
  339. static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
  340. {
  341. AVFormatContext *ctx = s->opaque;
  342. put_buffer(ctx->pb, packet, TS_PACKET_SIZE);
  343. }
  344. static int mpegts_write_header(AVFormatContext *s)
  345. {
  346. MpegTSWrite *ts = s->priv_data;
  347. MpegTSWriteStream *ts_st;
  348. MpegTSService *service;
  349. AVStream *st, *pcr_st = NULL;
  350. AVMetadataTag *title, *provider;
  351. int i, j;
  352. const char *service_name;
  353. const char *provider_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, "service_name", NULL, 0);
  359. if (!title)
  360. title = av_metadata_get(s->metadata, "title", NULL, 0);
  361. service_name = title ? title->value : DEFAULT_SERVICE_NAME;
  362. provider = av_metadata_get(s->metadata, "service_provider", NULL, 0);
  363. provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
  364. service = mpegts_add_service(ts, DEFAULT_SID, provider_name, service_name);
  365. service->pmt.write_packet = section_write_packet;
  366. service->pmt.opaque = s;
  367. service->pmt.cc = 15;
  368. ts->pat.pid = PAT_PID;
  369. ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
  370. ts->pat.write_packet = section_write_packet;
  371. ts->pat.opaque = s;
  372. ts->sdt.pid = SDT_PID;
  373. ts->sdt.cc = 15;
  374. ts->sdt.write_packet = section_write_packet;
  375. ts->sdt.opaque = s;
  376. pids = av_malloc(s->nb_streams * sizeof(*pids));
  377. if (!pids)
  378. return AVERROR(ENOMEM);
  379. /* assign pids to each stream */
  380. for(i = 0;i < s->nb_streams; i++) {
  381. st = s->streams[i];
  382. ts_st = av_mallocz(sizeof(MpegTSWriteStream));
  383. if (!ts_st)
  384. goto fail;
  385. st->priv_data = ts_st;
  386. ts_st->service = service;
  387. /* MPEG pid values < 16 are reserved. Applications which set st->id in
  388. * this range are assigned a calculated pid. */
  389. if (st->id < 16) {
  390. ts_st->pid = DEFAULT_START_PID + i;
  391. } else if (st->id < 0x1FFF) {
  392. ts_st->pid = st->id;
  393. } else {
  394. av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
  395. goto fail;
  396. }
  397. if (ts_st->pid == service->pmt.pid) {
  398. av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
  399. goto fail;
  400. }
  401. for (j = 0; j < i; j++)
  402. if (pids[j] == ts_st->pid) {
  403. av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
  404. goto fail;
  405. }
  406. pids[i] = ts_st->pid;
  407. ts_st->payload_pts = AV_NOPTS_VALUE;
  408. ts_st->payload_dts = AV_NOPTS_VALUE;
  409. ts_st->first_pts_check = 1;
  410. ts_st->cc = 15;
  411. /* update PCR pid by using the first video stream */
  412. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  413. service->pcr_pid == 0x1fff) {
  414. service->pcr_pid = ts_st->pid;
  415. pcr_st = st;
  416. }
  417. if (st->codec->codec_id == CODEC_ID_AAC &&
  418. st->codec->extradata_size > 0) {
  419. ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
  420. if (!ts_st->adts)
  421. return AVERROR(ENOMEM);
  422. if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
  423. st->codec->extradata_size) < 0)
  424. return -1;
  425. }
  426. }
  427. av_free(pids);
  428. /* if no video stream, use the first stream as PCR */
  429. if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
  430. pcr_st = s->streams[0];
  431. ts_st = pcr_st->priv_data;
  432. service->pcr_pid = ts_st->pid;
  433. }
  434. ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
  435. if (ts->mux_rate > 1) {
  436. service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
  437. (TS_PACKET_SIZE * 8 * 1000);
  438. ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
  439. (TS_PACKET_SIZE * 8 * 1000);
  440. ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
  441. (TS_PACKET_SIZE * 8 * 1000);
  442. ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
  443. } else {
  444. /* Arbitrary values, PAT/PMT could be written on key frames */
  445. ts->sdt_packet_period = 200;
  446. ts->pat_packet_period = 40;
  447. if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  448. if (!pcr_st->codec->frame_size) {
  449. av_log(s, AV_LOG_WARNING, "frame size not set\n");
  450. service->pcr_packet_period =
  451. pcr_st->codec->sample_rate/(10*512);
  452. } else {
  453. service->pcr_packet_period =
  454. pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
  455. }
  456. } else {
  457. // max delta PCR 0.1s
  458. service->pcr_packet_period =
  459. pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
  460. }
  461. }
  462. // output a PCR as soon as possible
  463. service->pcr_packet_count = service->pcr_packet_period;
  464. ts->pat_packet_count = ts->pat_packet_period-1;
  465. ts->sdt_packet_count = ts->sdt_packet_period-1;
  466. if (ts->mux_rate == 1)
  467. av_log(s, AV_LOG_INFO, "muxrate VBR, ");
  468. else
  469. av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
  470. av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
  471. "sdt every %d, pat/pmt every %d pkts\n",
  472. service->pcr_packet_period,
  473. ts->sdt_packet_period, ts->pat_packet_period);
  474. put_flush_packet(s->pb);
  475. return 0;
  476. fail:
  477. av_free(pids);
  478. for(i = 0;i < s->nb_streams; i++) {
  479. st = s->streams[i];
  480. av_free(st->priv_data);
  481. }
  482. return -1;
  483. }
  484. /* send SDT, PAT and PMT tables regulary */
  485. static void retransmit_si_info(AVFormatContext *s)
  486. {
  487. MpegTSWrite *ts = s->priv_data;
  488. int i;
  489. if (++ts->sdt_packet_count == ts->sdt_packet_period) {
  490. ts->sdt_packet_count = 0;
  491. mpegts_write_sdt(s);
  492. }
  493. if (++ts->pat_packet_count == ts->pat_packet_period) {
  494. ts->pat_packet_count = 0;
  495. mpegts_write_pat(s);
  496. for(i = 0; i < ts->nb_services; i++) {
  497. mpegts_write_pmt(s, ts->services[i]);
  498. }
  499. }
  500. }
  501. static int64_t get_pcr(const MpegTSWrite *ts, ByteIOContext *pb)
  502. {
  503. return av_rescale(url_ftell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
  504. ts->first_pcr;
  505. }
  506. static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
  507. {
  508. int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
  509. *buf++ = pcr_high >> 25;
  510. *buf++ = pcr_high >> 17;
  511. *buf++ = pcr_high >> 9;
  512. *buf++ = pcr_high >> 1;
  513. *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
  514. *buf++ = pcr_low;
  515. return buf;
  516. }
  517. /* Write a single null transport stream packet */
  518. static void mpegts_insert_null_packet(AVFormatContext *s)
  519. {
  520. uint8_t *q;
  521. uint8_t buf[TS_PACKET_SIZE];
  522. q = buf;
  523. *q++ = 0x47;
  524. *q++ = 0x00 | 0x1f;
  525. *q++ = 0xff;
  526. *q++ = 0x10;
  527. memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
  528. put_buffer(s->pb, buf, TS_PACKET_SIZE);
  529. }
  530. /* Write a single transport stream packet with a PCR and no payload */
  531. static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
  532. {
  533. MpegTSWrite *ts = s->priv_data;
  534. MpegTSWriteStream *ts_st = st->priv_data;
  535. uint8_t *q;
  536. uint8_t buf[TS_PACKET_SIZE];
  537. q = buf;
  538. *q++ = 0x47;
  539. *q++ = ts_st->pid >> 8;
  540. *q++ = ts_st->pid;
  541. *q++ = 0x20 | ts_st->cc; /* Adaptation only */
  542. /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
  543. *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
  544. *q++ = 0x10; /* Adaptation flags: PCR present */
  545. /* PCR coded into 6 bytes */
  546. q = write_pcr_bits(q, get_pcr(ts, s->pb));
  547. /* stuffing bytes */
  548. memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
  549. put_buffer(s->pb, buf, TS_PACKET_SIZE);
  550. }
  551. static void write_pts(uint8_t *q, int fourbits, int64_t pts)
  552. {
  553. int val;
  554. val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
  555. *q++ = val;
  556. val = (((pts >> 15) & 0x7fff) << 1) | 1;
  557. *q++ = val >> 8;
  558. *q++ = val;
  559. val = (((pts) & 0x7fff) << 1) | 1;
  560. *q++ = val >> 8;
  561. *q++ = val;
  562. }
  563. /* Add a pes header to the front of payload, and segment into an integer number of
  564. * ts packets. The final ts packet is padded using an over-sized adaptation header
  565. * to exactly fill the last ts packet.
  566. * NOTE: 'payload' contains a complete PES payload.
  567. */
  568. static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
  569. const uint8_t *payload, int payload_size,
  570. int64_t pts, int64_t dts)
  571. {
  572. MpegTSWriteStream *ts_st = st->priv_data;
  573. MpegTSWrite *ts = s->priv_data;
  574. uint8_t buf[TS_PACKET_SIZE];
  575. uint8_t *q;
  576. int val, is_start, len, header_len, write_pcr, private_code, flags;
  577. int afc_len, stuffing_len;
  578. int64_t pcr = -1; /* avoid warning */
  579. int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
  580. is_start = 1;
  581. while (payload_size > 0) {
  582. retransmit_si_info(s);
  583. write_pcr = 0;
  584. if (ts_st->pid == ts_st->service->pcr_pid) {
  585. if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
  586. ts_st->service->pcr_packet_count++;
  587. if (ts_st->service->pcr_packet_count >=
  588. ts_st->service->pcr_packet_period) {
  589. ts_st->service->pcr_packet_count = 0;
  590. write_pcr = 1;
  591. }
  592. }
  593. if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
  594. (dts - get_pcr(ts, s->pb)/300) > delay) {
  595. /* pcr insert gets priority over null packet insert */
  596. if (write_pcr)
  597. mpegts_insert_pcr_only(s, st);
  598. else
  599. mpegts_insert_null_packet(s);
  600. continue; /* recalculate write_pcr and possibly retransmit si_info */
  601. }
  602. /* prepare packet header */
  603. q = buf;
  604. *q++ = 0x47;
  605. val = (ts_st->pid >> 8);
  606. if (is_start)
  607. val |= 0x40;
  608. *q++ = val;
  609. *q++ = ts_st->pid;
  610. ts_st->cc = (ts_st->cc + 1) & 0xf;
  611. *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
  612. if (write_pcr) {
  613. // add 11, pcr references the last byte of program clock reference base
  614. if (ts->mux_rate > 1)
  615. pcr = get_pcr(ts, s->pb);
  616. else
  617. pcr = (dts - delay)*300;
  618. if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
  619. av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
  620. *q++ = 7; /* AFC length */
  621. *q++ = 0x10; /* flags: PCR present */
  622. q = write_pcr_bits(q, pcr);
  623. }
  624. if (is_start) {
  625. int pes_extension = 0;
  626. /* write PES header */
  627. *q++ = 0x00;
  628. *q++ = 0x00;
  629. *q++ = 0x01;
  630. private_code = 0;
  631. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  632. if (st->codec->codec_id == CODEC_ID_DIRAC) {
  633. *q++ = 0xfd;
  634. } else
  635. *q++ = 0xe0;
  636. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  637. (st->codec->codec_id == CODEC_ID_MP2 ||
  638. st->codec->codec_id == CODEC_ID_MP3)) {
  639. *q++ = 0xc0;
  640. } else {
  641. *q++ = 0xbd;
  642. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  643. private_code = 0x20;
  644. }
  645. }
  646. header_len = 0;
  647. flags = 0;
  648. if (pts != AV_NOPTS_VALUE) {
  649. header_len += 5;
  650. flags |= 0x80;
  651. }
  652. if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
  653. header_len += 5;
  654. flags |= 0x40;
  655. }
  656. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  657. st->codec->codec_id == CODEC_ID_DIRAC) {
  658. /* set PES_extension_flag */
  659. pes_extension = 1;
  660. flags |= 0x01;
  661. /*
  662. * One byte for PES2 extension flag +
  663. * one byte for extension length +
  664. * one byte for extension id
  665. */
  666. header_len += 3;
  667. }
  668. len = payload_size + header_len + 3;
  669. if (private_code != 0)
  670. len++;
  671. if (len > 0xffff)
  672. len = 0;
  673. *q++ = len >> 8;
  674. *q++ = len;
  675. val = 0x80;
  676. /* data alignment indicator is required for subtitle data */
  677. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
  678. val |= 0x04;
  679. *q++ = val;
  680. *q++ = flags;
  681. *q++ = header_len;
  682. if (pts != AV_NOPTS_VALUE) {
  683. write_pts(q, flags >> 6, pts);
  684. q += 5;
  685. }
  686. if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
  687. write_pts(q, 1, dts);
  688. q += 5;
  689. }
  690. if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
  691. flags = 0x01; /* set PES_extension_flag_2 */
  692. *q++ = flags;
  693. *q++ = 0x80 | 0x01; /* marker bit + extension length */
  694. /*
  695. * Set the stream id extension flag bit to 0 and
  696. * write the extended stream id
  697. */
  698. *q++ = 0x00 | 0x60;
  699. }
  700. if (private_code != 0)
  701. *q++ = private_code;
  702. is_start = 0;
  703. }
  704. /* header size */
  705. header_len = q - buf;
  706. /* data len */
  707. len = TS_PACKET_SIZE - header_len;
  708. if (len > payload_size)
  709. len = payload_size;
  710. stuffing_len = TS_PACKET_SIZE - header_len - len;
  711. if (stuffing_len > 0) {
  712. /* add stuffing with AFC */
  713. if (buf[3] & 0x20) {
  714. /* stuffing already present: increase its size */
  715. afc_len = buf[4] + 1;
  716. memmove(buf + 4 + afc_len + stuffing_len,
  717. buf + 4 + afc_len,
  718. header_len - (4 + afc_len));
  719. buf[4] += stuffing_len;
  720. memset(buf + 4 + afc_len, 0xff, stuffing_len);
  721. } else {
  722. /* add stuffing */
  723. memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
  724. buf[3] |= 0x20;
  725. buf[4] = stuffing_len - 1;
  726. if (stuffing_len >= 2) {
  727. buf[5] = 0x00;
  728. memset(buf + 6, 0xff, stuffing_len - 2);
  729. }
  730. }
  731. }
  732. memcpy(buf + TS_PACKET_SIZE - len, payload, len);
  733. payload += len;
  734. payload_size -= len;
  735. put_buffer(s->pb, buf, TS_PACKET_SIZE);
  736. }
  737. put_flush_packet(s->pb);
  738. }
  739. static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
  740. {
  741. AVStream *st = s->streams[pkt->stream_index];
  742. int size = pkt->size;
  743. uint8_t *buf= pkt->data;
  744. uint8_t *data= NULL;
  745. MpegTSWriteStream *ts_st = st->priv_data;
  746. const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
  747. int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
  748. if (pkt->pts != AV_NOPTS_VALUE)
  749. pts = pkt->pts + delay;
  750. if (pkt->dts != AV_NOPTS_VALUE)
  751. dts = pkt->dts + delay;
  752. if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
  753. av_log(s, AV_LOG_ERROR, "first pts value must set\n");
  754. return -1;
  755. }
  756. ts_st->first_pts_check = 0;
  757. if (st->codec->codec_id == CODEC_ID_H264) {
  758. const uint8_t *p = buf, *buf_end = p+size;
  759. uint32_t state = -1;
  760. if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
  761. av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
  762. "no startcode found, use -vbsf h264_mp4toannexb\n");
  763. return -1;
  764. }
  765. do {
  766. p = ff_find_start_code(p, buf_end, &state);
  767. //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
  768. } while (p < buf_end && (state & 0x1f) != 9 &&
  769. (state & 0x1f) != 5 && (state & 0x1f) != 1);
  770. if ((state & 0x1f) != 9) { // AUD NAL
  771. data = av_malloc(pkt->size+6);
  772. if (!data)
  773. return -1;
  774. memcpy(data+6, pkt->data, pkt->size);
  775. AV_WB32(data, 0x00000001);
  776. data[4] = 0x09;
  777. data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
  778. buf = data;
  779. size = pkt->size+6;
  780. }
  781. } else if (st->codec->codec_id == CODEC_ID_AAC) {
  782. if (pkt->size < 2)
  783. return -1;
  784. if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
  785. ADTSContext *adts = ts_st->adts;
  786. int new_size;
  787. if (!adts) {
  788. av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
  789. "and extradata missing\n");
  790. return -1;
  791. }
  792. new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
  793. if ((unsigned)new_size >= INT_MAX)
  794. return -1;
  795. data = av_malloc(new_size);
  796. if (!data)
  797. return AVERROR(ENOMEM);
  798. ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
  799. if (adts->pce_size) {
  800. memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
  801. adts->pce_size = 0;
  802. }
  803. memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
  804. buf = data;
  805. size = new_size;
  806. }
  807. }
  808. if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
  809. // for video and subtitle, write a single pes packet
  810. mpegts_write_pes(s, st, buf, size, pts, dts);
  811. av_free(data);
  812. return 0;
  813. }
  814. if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
  815. mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
  816. ts_st->payload_pts, ts_st->payload_dts);
  817. ts_st->payload_index = 0;
  818. }
  819. if (!ts_st->payload_index) {
  820. ts_st->payload_pts = pts;
  821. ts_st->payload_dts = dts;
  822. }
  823. memcpy(ts_st->payload + ts_st->payload_index, buf, size);
  824. ts_st->payload_index += size;
  825. av_free(data);
  826. return 0;
  827. }
  828. static int mpegts_write_end(AVFormatContext *s)
  829. {
  830. MpegTSWrite *ts = s->priv_data;
  831. MpegTSWriteStream *ts_st;
  832. MpegTSService *service;
  833. AVStream *st;
  834. int i;
  835. /* flush current packets */
  836. for(i = 0; i < s->nb_streams; i++) {
  837. st = s->streams[i];
  838. ts_st = st->priv_data;
  839. if (ts_st->payload_index > 0) {
  840. mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
  841. ts_st->payload_pts, ts_st->payload_dts);
  842. }
  843. av_freep(&ts_st->adts);
  844. }
  845. put_flush_packet(s->pb);
  846. for(i = 0; i < ts->nb_services; i++) {
  847. service = ts->services[i];
  848. av_freep(&service->provider_name);
  849. av_freep(&service->name);
  850. av_free(service);
  851. }
  852. av_free(ts->services);
  853. return 0;
  854. }
  855. AVOutputFormat mpegts_muxer = {
  856. "mpegts",
  857. NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  858. "video/x-mpegts",
  859. "ts,m2t",
  860. sizeof(MpegTSWrite),
  861. CODEC_ID_MP2,
  862. CODEC_ID_MPEG2VIDEO,
  863. mpegts_write_header,
  864. mpegts_write_packet,
  865. mpegts_write_end,
  866. };