mpegtsenc.c 41 KB

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