mpegtsenc.c 34 KB

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