mpegtsenc.c 32 KB

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