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.

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