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.

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