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.

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