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.

991 lines
31KB

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