mpegtsenc.c 32 KB

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