matroskaenc.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. /*
  2. * Matroska muxer
  3. * Copyright (c) 2007 David Conrad
  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 "avformat.h"
  22. #include "internal.h"
  23. #include "riff.h"
  24. #include "isom.h"
  25. #include "matroska.h"
  26. #include "avc.h"
  27. #include "flacenc.h"
  28. #include "avlanguage.h"
  29. #include "libavutil/samplefmt.h"
  30. #include "libavutil/intreadwrite.h"
  31. #include "libavutil/intfloat.h"
  32. #include "libavutil/mathematics.h"
  33. #include "libavutil/random_seed.h"
  34. #include "libavutil/lfg.h"
  35. #include "libavutil/dict.h"
  36. #include "libavutil/avstring.h"
  37. #include "libavcodec/xiph.h"
  38. #include "libavcodec/mpeg4audio.h"
  39. typedef struct ebml_master {
  40. int64_t pos; ///< absolute offset in the file where the master's elements start
  41. int sizebytes; ///< how many bytes were reserved for the size
  42. } ebml_master;
  43. typedef struct mkv_seekhead_entry {
  44. unsigned int elementid;
  45. uint64_t segmentpos;
  46. } mkv_seekhead_entry;
  47. typedef struct mkv_seekhead {
  48. int64_t filepos;
  49. int64_t segment_offset; ///< the file offset to the beginning of the segment
  50. int reserved_size; ///< -1 if appending to file
  51. int max_entries;
  52. mkv_seekhead_entry *entries;
  53. int num_entries;
  54. } mkv_seekhead;
  55. typedef struct {
  56. uint64_t pts;
  57. int tracknum;
  58. int64_t cluster_pos; ///< file offset of the cluster containing the block
  59. } mkv_cuepoint;
  60. typedef struct {
  61. int64_t segment_offset;
  62. mkv_cuepoint *entries;
  63. int num_entries;
  64. } mkv_cues;
  65. typedef struct {
  66. int write_dts;
  67. } mkv_track;
  68. #define MODE_MATROSKAv2 0x01
  69. #define MODE_WEBM 0x02
  70. typedef struct MatroskaMuxContext {
  71. int mode;
  72. AVIOContext *dyn_bc;
  73. ebml_master segment;
  74. int64_t segment_offset;
  75. ebml_master cluster;
  76. int64_t cluster_pos; ///< file offset of the current cluster
  77. int64_t cluster_pts;
  78. int64_t duration_offset;
  79. int64_t duration;
  80. mkv_seekhead *main_seekhead;
  81. mkv_cues *cues;
  82. mkv_track *tracks;
  83. unsigned int audio_buffer_size;
  84. AVPacket cur_audio_pkt;
  85. int have_attachments;
  86. } MatroskaMuxContext;
  87. /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
  88. * offset, 4 bytes for target EBML ID */
  89. #define MAX_SEEKENTRY_SIZE 21
  90. /** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
  91. * 8-byte uint max */
  92. #define MAX_CUETRACKPOS_SIZE 22
  93. /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
  94. #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
  95. static int ebml_id_size(unsigned int id)
  96. {
  97. return (av_log2(id+1)-1)/7+1;
  98. }
  99. static void put_ebml_id(AVIOContext *pb, unsigned int id)
  100. {
  101. int i = ebml_id_size(id);
  102. while (i--)
  103. avio_w8(pb, id >> (i*8));
  104. }
  105. /**
  106. * Write an EBML size meaning "unknown size".
  107. *
  108. * @param bytes The number of bytes the size should occupy (maximum: 8).
  109. */
  110. static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
  111. {
  112. assert(bytes <= 8);
  113. avio_w8(pb, 0x1ff >> bytes);
  114. while (--bytes)
  115. avio_w8(pb, 0xff);
  116. }
  117. /**
  118. * Calculate how many bytes are needed to represent a given number in EBML.
  119. */
  120. static int ebml_num_size(uint64_t num)
  121. {
  122. int bytes = 1;
  123. while ((num+1) >> bytes*7) bytes++;
  124. return bytes;
  125. }
  126. /**
  127. * Write a number in EBML variable length format.
  128. *
  129. * @param bytes The number of bytes that need to be used to write the number.
  130. * If zero, any number of bytes can be used.
  131. */
  132. static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
  133. {
  134. int i, needed_bytes = ebml_num_size(num);
  135. // sizes larger than this are currently undefined in EBML
  136. assert(num < (1ULL<<56)-1);
  137. if (bytes == 0)
  138. // don't care how many bytes are used, so use the min
  139. bytes = needed_bytes;
  140. // the bytes needed to write the given size would exceed the bytes
  141. // that we need to use, so write unknown size. This shouldn't happen.
  142. assert(bytes >= needed_bytes);
  143. num |= 1ULL << bytes*7;
  144. for (i = bytes - 1; i >= 0; i--)
  145. avio_w8(pb, num >> i*8);
  146. }
  147. static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
  148. {
  149. int i, bytes = 1;
  150. uint64_t tmp = val;
  151. while (tmp>>=8) bytes++;
  152. put_ebml_id(pb, elementid);
  153. put_ebml_num(pb, bytes, 0);
  154. for (i = bytes - 1; i >= 0; i--)
  155. avio_w8(pb, val >> i*8);
  156. }
  157. static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
  158. {
  159. put_ebml_id(pb, elementid);
  160. put_ebml_num(pb, 8, 0);
  161. avio_wb64(pb, av_double2int(val));
  162. }
  163. static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
  164. const void *buf, int size)
  165. {
  166. put_ebml_id(pb, elementid);
  167. put_ebml_num(pb, size, 0);
  168. avio_write(pb, buf, size);
  169. }
  170. static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
  171. {
  172. put_ebml_binary(pb, elementid, str, strlen(str));
  173. }
  174. /**
  175. * Write a void element of a given size. Useful for reserving space in
  176. * the file to be written to later.
  177. *
  178. * @param size The number of bytes to reserve, which must be at least 2.
  179. */
  180. static void put_ebml_void(AVIOContext *pb, uint64_t size)
  181. {
  182. int64_t currentpos = avio_tell(pb);
  183. assert(size >= 2);
  184. put_ebml_id(pb, EBML_ID_VOID);
  185. // we need to subtract the length needed to store the size from the
  186. // size we need to reserve so 2 cases, we use 8 bytes to store the
  187. // size if possible, 1 byte otherwise
  188. if (size < 10)
  189. put_ebml_num(pb, size-1, 0);
  190. else
  191. put_ebml_num(pb, size-9, 8);
  192. while(avio_tell(pb) < currentpos + size)
  193. avio_w8(pb, 0);
  194. }
  195. static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
  196. {
  197. int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
  198. put_ebml_id(pb, elementid);
  199. put_ebml_size_unknown(pb, bytes);
  200. return (ebml_master){ avio_tell(pb), bytes };
  201. }
  202. static void end_ebml_master(AVIOContext *pb, ebml_master master)
  203. {
  204. int64_t pos = avio_tell(pb);
  205. if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
  206. return;
  207. put_ebml_num(pb, pos - master.pos, master.sizebytes);
  208. avio_seek(pb, pos, SEEK_SET);
  209. }
  210. static void put_xiph_size(AVIOContext *pb, int size)
  211. {
  212. int i;
  213. for (i = 0; i < size / 255; i++)
  214. avio_w8(pb, 255);
  215. avio_w8(pb, size % 255);
  216. }
  217. /**
  218. * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
  219. * elements. If a maximum number of elements is specified, enough space
  220. * will be reserved at the current file location to write a seek head of
  221. * that size.
  222. *
  223. * @param segment_offset The absolute offset to the position in the file
  224. * where the segment begins.
  225. * @param numelements The maximum number of elements that will be indexed
  226. * by this seek head, 0 if unlimited.
  227. */
  228. static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
  229. {
  230. mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
  231. if (new_seekhead == NULL)
  232. return NULL;
  233. new_seekhead->segment_offset = segment_offset;
  234. if (numelements > 0) {
  235. new_seekhead->filepos = avio_tell(pb);
  236. // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
  237. // and size, and 3 bytes to guarantee that an EBML void element
  238. // will fit afterwards
  239. new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
  240. new_seekhead->max_entries = numelements;
  241. put_ebml_void(pb, new_seekhead->reserved_size);
  242. }
  243. return new_seekhead;
  244. }
  245. static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
  246. {
  247. mkv_seekhead_entry *entries = seekhead->entries;
  248. // don't store more elements than we reserved space for
  249. if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
  250. return -1;
  251. entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
  252. if (entries == NULL)
  253. return AVERROR(ENOMEM);
  254. entries[seekhead->num_entries ].elementid = elementid;
  255. entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
  256. seekhead->entries = entries;
  257. return 0;
  258. }
  259. /**
  260. * Write the seek head to the file and free it. If a maximum number of
  261. * elements was specified to mkv_start_seekhead(), the seek head will
  262. * be written at the location reserved for it. Otherwise, it is written
  263. * at the current location in the file.
  264. *
  265. * @return The file offset where the seekhead was written,
  266. * -1 if an error occurred.
  267. */
  268. static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
  269. {
  270. ebml_master metaseek, seekentry;
  271. int64_t currentpos;
  272. int i;
  273. currentpos = avio_tell(pb);
  274. if (seekhead->reserved_size > 0) {
  275. if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
  276. currentpos = -1;
  277. goto fail;
  278. }
  279. }
  280. metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
  281. for (i = 0; i < seekhead->num_entries; i++) {
  282. mkv_seekhead_entry *entry = &seekhead->entries[i];
  283. seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
  284. put_ebml_id(pb, MATROSKA_ID_SEEKID);
  285. put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
  286. put_ebml_id(pb, entry->elementid);
  287. put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
  288. end_ebml_master(pb, seekentry);
  289. }
  290. end_ebml_master(pb, metaseek);
  291. if (seekhead->reserved_size > 0) {
  292. uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
  293. put_ebml_void(pb, remaining);
  294. avio_seek(pb, currentpos, SEEK_SET);
  295. currentpos = seekhead->filepos;
  296. }
  297. fail:
  298. av_free(seekhead->entries);
  299. av_free(seekhead);
  300. return currentpos;
  301. }
  302. static mkv_cues * mkv_start_cues(int64_t segment_offset)
  303. {
  304. mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
  305. if (cues == NULL)
  306. return NULL;
  307. cues->segment_offset = segment_offset;
  308. return cues;
  309. }
  310. static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
  311. {
  312. mkv_cuepoint *entries = cues->entries;
  313. entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
  314. if (entries == NULL)
  315. return AVERROR(ENOMEM);
  316. if (ts < 0)
  317. return 0;
  318. entries[cues->num_entries ].pts = ts;
  319. entries[cues->num_entries ].tracknum = stream + 1;
  320. entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
  321. cues->entries = entries;
  322. return 0;
  323. }
  324. static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
  325. {
  326. ebml_master cues_element;
  327. int64_t currentpos;
  328. int i, j;
  329. currentpos = avio_tell(pb);
  330. cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
  331. for (i = 0; i < cues->num_entries; i++) {
  332. ebml_master cuepoint, track_positions;
  333. mkv_cuepoint *entry = &cues->entries[i];
  334. uint64_t pts = entry->pts;
  335. cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
  336. put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
  337. // put all the entries from different tracks that have the exact same
  338. // timestamp into the same CuePoint
  339. for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
  340. track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
  341. put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
  342. put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
  343. end_ebml_master(pb, track_positions);
  344. }
  345. i += j - 1;
  346. end_ebml_master(pb, cuepoint);
  347. }
  348. end_ebml_master(pb, cues_element);
  349. return currentpos;
  350. }
  351. static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
  352. {
  353. uint8_t *header_start[3];
  354. int header_len[3];
  355. int first_header_size;
  356. int j;
  357. if (codec->codec_id == CODEC_ID_VORBIS)
  358. first_header_size = 30;
  359. else
  360. first_header_size = 42;
  361. if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
  362. first_header_size, header_start, header_len) < 0) {
  363. av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
  364. return -1;
  365. }
  366. avio_w8(pb, 2); // number packets - 1
  367. for (j = 0; j < 2; j++) {
  368. put_xiph_size(pb, header_len[j]);
  369. }
  370. for (j = 0; j < 3; j++)
  371. avio_write(pb, header_start[j], header_len[j]);
  372. return 0;
  373. }
  374. static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
  375. {
  376. MPEG4AudioConfig mp4ac;
  377. if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
  378. codec->extradata_size * 8, 1) < 0) {
  379. av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
  380. return;
  381. }
  382. *sample_rate = mp4ac.sample_rate;
  383. *output_sample_rate = mp4ac.ext_sample_rate;
  384. }
  385. static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
  386. {
  387. AVIOContext *dyn_cp;
  388. uint8_t *codecpriv;
  389. int ret, codecpriv_size;
  390. ret = avio_open_dyn_buf(&dyn_cp);
  391. if(ret < 0)
  392. return ret;
  393. if (native_id) {
  394. if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA)
  395. ret = put_xiph_codecpriv(s, dyn_cp, codec);
  396. else if (codec->codec_id == CODEC_ID_FLAC)
  397. ret = ff_flac_write_header(dyn_cp, codec, 1);
  398. else if (codec->codec_id == CODEC_ID_H264)
  399. ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
  400. else if (codec->extradata_size)
  401. avio_write(dyn_cp, codec->extradata, codec->extradata_size);
  402. } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  403. if (qt_id) {
  404. if (!codec->codec_tag)
  405. codec->codec_tag = ff_codec_get_tag(codec_movvideo_tags, codec->codec_id);
  406. if (codec->extradata_size)
  407. avio_write(dyn_cp, codec->extradata, codec->extradata_size);
  408. } else {
  409. if (!codec->codec_tag)
  410. codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
  411. if (!codec->codec_tag) {
  412. av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
  413. ret = -1;
  414. }
  415. ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
  416. }
  417. } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  418. unsigned int tag;
  419. tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
  420. if (!tag) {
  421. av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
  422. ret = -1;
  423. }
  424. if (!codec->codec_tag)
  425. codec->codec_tag = tag;
  426. ff_put_wav_header(dyn_cp, codec);
  427. }
  428. codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
  429. if (codecpriv_size)
  430. put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
  431. av_free(codecpriv);
  432. return ret;
  433. }
  434. static int mkv_write_tracks(AVFormatContext *s)
  435. {
  436. MatroskaMuxContext *mkv = s->priv_data;
  437. AVIOContext *pb = s->pb;
  438. ebml_master tracks;
  439. int i, j, ret;
  440. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
  441. if (ret < 0) return ret;
  442. tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
  443. for (i = 0; i < s->nb_streams; i++) {
  444. AVStream *st = s->streams[i];
  445. AVCodecContext *codec = st->codec;
  446. ebml_master subinfo, track;
  447. int native_id = 0;
  448. int qt_id = 0;
  449. int bit_depth = av_get_bits_per_sample(codec->codec_id);
  450. int sample_rate = codec->sample_rate;
  451. int output_sample_rate = 0;
  452. AVDictionaryEntry *tag;
  453. if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
  454. mkv->have_attachments = 1;
  455. continue;
  456. }
  457. if (!bit_depth)
  458. bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
  459. if (codec->codec_id == CODEC_ID_AAC)
  460. get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
  461. track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
  462. put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
  463. put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
  464. put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
  465. if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
  466. put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
  467. tag = av_dict_get(st->metadata, "language", NULL, 0);
  468. put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
  469. if (st->disposition)
  470. put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
  471. // look for a codec ID string specific to mkv to use,
  472. // if none are found, use AVI codes
  473. for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
  474. if (ff_mkv_codec_tags[j].id == codec->codec_id) {
  475. put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
  476. native_id = 1;
  477. break;
  478. }
  479. }
  480. if (mkv->mode == MODE_WEBM && !(codec->codec_id == CODEC_ID_VP8 ||
  481. codec->codec_id == CODEC_ID_VORBIS)) {
  482. av_log(s, AV_LOG_ERROR,
  483. "Only VP8 video and Vorbis audio are supported for WebM.\n");
  484. return AVERROR(EINVAL);
  485. }
  486. switch (codec->codec_type) {
  487. case AVMEDIA_TYPE_VIDEO:
  488. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
  489. if(st->avg_frame_rate.num && st->avg_frame_rate.den && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
  490. put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9/av_q2d(st->avg_frame_rate));
  491. else
  492. put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
  493. if (!native_id &&
  494. ff_codec_get_tag(codec_movvideo_tags, codec->codec_id) &&
  495. (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
  496. || codec->codec_id == CODEC_ID_SVQ1
  497. || codec->codec_id == CODEC_ID_SVQ3
  498. || codec->codec_id == CODEC_ID_CINEPAK))
  499. qt_id = 1;
  500. if (qt_id)
  501. put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
  502. else if (!native_id) {
  503. // if there is no mkv-specific codec ID, use VFW mode
  504. put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
  505. mkv->tracks[i].write_dts = 1;
  506. }
  507. subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
  508. // XXX: interlace flag?
  509. put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
  510. put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
  511. if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
  512. (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
  513. // save stereo mode flag
  514. uint64_t st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;
  515. for (j=0; j<MATROSKA_VIDEO_STEREO_MODE_COUNT; j++)
  516. if (!strcmp(tag->value, matroska_video_stereo_mode[j])){
  517. st_mode = j;
  518. break;
  519. }
  520. if ((mkv->mode == MODE_WEBM && st_mode > 3 && st_mode != 11)
  521. || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {
  522. av_log(s, AV_LOG_ERROR,
  523. "The specified stereo mode is not valid.\n");
  524. return AVERROR(EINVAL);
  525. } else
  526. put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, st_mode);
  527. }
  528. if (st->sample_aspect_ratio.num) {
  529. int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
  530. put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
  531. put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
  532. put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3);
  533. }
  534. if (codec->codec_id == CODEC_ID_RAWVIDEO) {
  535. uint32_t color_space = av_le2ne32(codec->codec_tag);
  536. put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
  537. }
  538. end_ebml_master(pb, subinfo);
  539. break;
  540. case AVMEDIA_TYPE_AUDIO:
  541. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
  542. if (!native_id)
  543. // no mkv-specific ID, use ACM mode
  544. put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
  545. subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
  546. put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
  547. put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
  548. if (output_sample_rate)
  549. put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
  550. if (bit_depth)
  551. put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
  552. end_ebml_master(pb, subinfo);
  553. break;
  554. case AVMEDIA_TYPE_SUBTITLE:
  555. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
  556. if (!native_id) {
  557. av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
  558. return AVERROR(ENOSYS);
  559. }
  560. break;
  561. default:
  562. av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
  563. break;
  564. }
  565. ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
  566. if (ret < 0) return ret;
  567. end_ebml_master(pb, track);
  568. // ms precision is the de-facto standard timescale for mkv files
  569. avpriv_set_pts_info(st, 64, 1, 1000);
  570. }
  571. end_ebml_master(pb, tracks);
  572. return 0;
  573. }
  574. static int mkv_write_chapters(AVFormatContext *s)
  575. {
  576. MatroskaMuxContext *mkv = s->priv_data;
  577. AVIOContext *pb = s->pb;
  578. ebml_master chapters, editionentry;
  579. AVRational scale = {1, 1E9};
  580. int i, ret;
  581. if (!s->nb_chapters)
  582. return 0;
  583. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
  584. if (ret < 0) return ret;
  585. chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
  586. editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
  587. put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
  588. put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
  589. for (i = 0; i < s->nb_chapters; i++) {
  590. ebml_master chapteratom, chapterdisplay;
  591. AVChapter *c = s->chapters[i];
  592. AVDictionaryEntry *t = NULL;
  593. chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
  594. put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
  595. put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
  596. av_rescale_q(c->start, c->time_base, scale));
  597. put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
  598. av_rescale_q(c->end, c->time_base, scale));
  599. put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
  600. put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
  601. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  602. chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
  603. put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
  604. put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
  605. end_ebml_master(pb, chapterdisplay);
  606. }
  607. end_ebml_master(pb, chapteratom);
  608. }
  609. end_ebml_master(pb, editionentry);
  610. end_ebml_master(pb, chapters);
  611. return 0;
  612. }
  613. static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
  614. {
  615. uint8_t *key = av_strdup(t->key);
  616. uint8_t *p = key;
  617. const uint8_t *lang = NULL;
  618. ebml_master tag;
  619. if ((p = strrchr(p, '-')) &&
  620. (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
  621. *p = 0;
  622. p = key;
  623. while (*p) {
  624. if (*p == ' ')
  625. *p = '_';
  626. else if (*p >= 'a' && *p <= 'z')
  627. *p -= 'a' - 'A';
  628. p++;
  629. }
  630. tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
  631. put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
  632. if (lang)
  633. put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
  634. put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
  635. end_ebml_master(pb, tag);
  636. av_freep(&key);
  637. }
  638. static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
  639. unsigned int uid, ebml_master *tags)
  640. {
  641. MatroskaMuxContext *mkv = s->priv_data;
  642. ebml_master tag, targets;
  643. AVDictionaryEntry *t = NULL;
  644. int ret;
  645. if (!tags->pos) {
  646. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
  647. if (ret < 0) return ret;
  648. *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
  649. }
  650. tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
  651. targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
  652. if (elementid)
  653. put_ebml_uint(s->pb, elementid, uid);
  654. end_ebml_master(s->pb, targets);
  655. while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
  656. if (av_strcasecmp(t->key, "title") &&
  657. av_strcasecmp(t->key, "stereo_mode") &&
  658. av_strcasecmp(t->key, "encoding_tool"))
  659. mkv_write_simpletag(s->pb, t);
  660. end_ebml_master(s->pb, tag);
  661. return 0;
  662. }
  663. static int mkv_write_tags(AVFormatContext *s)
  664. {
  665. ebml_master tags = {0};
  666. int i, ret;
  667. ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
  668. if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
  669. ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
  670. if (ret < 0) return ret;
  671. }
  672. for (i = 0; i < s->nb_streams; i++) {
  673. AVStream *st = s->streams[i];
  674. if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
  675. continue;
  676. ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
  677. if (ret < 0) return ret;
  678. }
  679. for (i = 0; i < s->nb_chapters; i++) {
  680. AVChapter *ch = s->chapters[i];
  681. if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
  682. continue;
  683. ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
  684. if (ret < 0) return ret;
  685. }
  686. if (tags.pos)
  687. end_ebml_master(s->pb, tags);
  688. return 0;
  689. }
  690. static int mkv_write_attachments(AVFormatContext *s)
  691. {
  692. MatroskaMuxContext *mkv = s->priv_data;
  693. AVIOContext *pb = s->pb;
  694. ebml_master attachments;
  695. AVLFG c;
  696. int i, ret;
  697. if (!mkv->have_attachments)
  698. return 0;
  699. av_lfg_init(&c, av_get_random_seed());
  700. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
  701. if (ret < 0) return ret;
  702. attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
  703. for (i = 0; i < s->nb_streams; i++) {
  704. AVStream *st = s->streams[i];
  705. ebml_master attached_file;
  706. AVDictionaryEntry *t;
  707. const char *mimetype = NULL;
  708. if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
  709. continue;
  710. attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
  711. if (t = av_dict_get(st->metadata, "title", NULL, 0))
  712. put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
  713. if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
  714. av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
  715. return AVERROR(EINVAL);
  716. }
  717. put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
  718. if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
  719. mimetype = t->value;
  720. else if (st->codec->codec_id != CODEC_ID_NONE ) {
  721. int i;
  722. for (i = 0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++)
  723. if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
  724. mimetype = ff_mkv_mime_tags[i].str;
  725. break;
  726. }
  727. }
  728. if (!mimetype) {
  729. av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
  730. "it cannot be deduced from the codec id.\n", i);
  731. return AVERROR(EINVAL);
  732. }
  733. put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
  734. put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
  735. put_ebml_uint(pb, MATROSKA_ID_FILEUID, av_lfg_get(&c));
  736. end_ebml_master(pb, attached_file);
  737. }
  738. end_ebml_master(pb, attachments);
  739. return 0;
  740. }
  741. static int mkv_write_header(AVFormatContext *s)
  742. {
  743. MatroskaMuxContext *mkv = s->priv_data;
  744. AVIOContext *pb = s->pb;
  745. ebml_master ebml_header, segment_info;
  746. AVDictionaryEntry *tag;
  747. int ret, i;
  748. if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
  749. else mkv->mode = MODE_MATROSKAv2;
  750. mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
  751. if (!mkv->tracks)
  752. return AVERROR(ENOMEM);
  753. ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
  754. put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
  755. put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
  756. put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
  757. put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
  758. put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
  759. put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
  760. put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
  761. end_ebml_master(pb, ebml_header);
  762. mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
  763. mkv->segment_offset = avio_tell(pb);
  764. // we write 2 seek heads - one at the end of the file to point to each
  765. // cluster, and one at the beginning to point to all other level one
  766. // elements (including the seek head at the end of the file), which
  767. // isn't more than 10 elements if we only write one of each other
  768. // currently defined level 1 element
  769. mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
  770. if (!mkv->main_seekhead)
  771. return AVERROR(ENOMEM);
  772. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
  773. if (ret < 0) return ret;
  774. segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
  775. put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
  776. if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
  777. put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
  778. if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  779. uint32_t segment_uid[4];
  780. AVLFG lfg;
  781. av_lfg_init(&lfg, av_get_random_seed());
  782. for (i = 0; i < 4; i++)
  783. segment_uid[i] = av_lfg_get(&lfg);
  784. put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
  785. if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
  786. put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
  787. else
  788. put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
  789. put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
  790. }
  791. // reserve space for the duration
  792. mkv->duration = 0;
  793. mkv->duration_offset = avio_tell(pb);
  794. put_ebml_void(pb, 11); // assumes double-precision float to be written
  795. end_ebml_master(pb, segment_info);
  796. ret = mkv_write_tracks(s);
  797. if (ret < 0) return ret;
  798. if (mkv->mode != MODE_WEBM) {
  799. ret = mkv_write_chapters(s);
  800. if (ret < 0) return ret;
  801. ret = mkv_write_tags(s);
  802. if (ret < 0) return ret;
  803. ret = mkv_write_attachments(s);
  804. if (ret < 0) return ret;
  805. }
  806. if (!s->pb->seekable)
  807. mkv_write_seekhead(pb, mkv->main_seekhead);
  808. mkv->cues = mkv_start_cues(mkv->segment_offset);
  809. if (mkv->cues == NULL)
  810. return AVERROR(ENOMEM);
  811. av_init_packet(&mkv->cur_audio_pkt);
  812. mkv->cur_audio_pkt.size = 0;
  813. mkv->audio_buffer_size = 0;
  814. avio_flush(pb);
  815. return 0;
  816. }
  817. static int mkv_blockgroup_size(int pkt_size)
  818. {
  819. int size = pkt_size + 4;
  820. size += ebml_num_size(size);
  821. size += 2; // EBML ID for block and block duration
  822. size += 8; // max size of block duration
  823. size += ebml_num_size(size);
  824. size += 1; // blockgroup EBML ID
  825. return size;
  826. }
  827. static int ass_get_duration(const uint8_t *p)
  828. {
  829. int sh, sm, ss, sc, eh, em, es, ec;
  830. uint64_t start, end;
  831. if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
  832. &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
  833. return 0;
  834. start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
  835. end = 3600000*eh + 60000*em + 1000*es + 10*ec;
  836. return end - start;
  837. }
  838. static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
  839. {
  840. MatroskaMuxContext *mkv = s->priv_data;
  841. int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
  842. uint8_t *start, *end, *data = pkt->data;
  843. ebml_master blockgroup;
  844. char buffer[2048];
  845. while (data_size) {
  846. int duration = ass_get_duration(data);
  847. max_duration = FFMAX(duration, max_duration);
  848. end = memchr(data, '\n', data_size);
  849. size = line_size = end ? end-data+1 : data_size;
  850. size -= end ? (end[-1]=='\r')+1 : 0;
  851. start = data;
  852. for (i=0; i<3; i++, start++)
  853. if (!(start = memchr(start, ',', size-(start-data))))
  854. return max_duration;
  855. size -= start - data;
  856. sscanf(data, "Dialogue: %d,", &layer);
  857. i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
  858. s->streams[pkt->stream_index]->nb_frames, layer);
  859. size = FFMIN(i+size, sizeof(buffer));
  860. memcpy(buffer+i, start, size-i);
  861. av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
  862. "pts %" PRId64 ", duration %d\n",
  863. avio_tell(pb), size, pkt->pts, duration);
  864. blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
  865. put_ebml_id(pb, MATROSKA_ID_BLOCK);
  866. put_ebml_num(pb, size+4, 0);
  867. avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
  868. avio_wb16(pb, pkt->pts - mkv->cluster_pts);
  869. avio_w8(pb, 0);
  870. avio_write(pb, buffer, size);
  871. put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
  872. end_ebml_master(pb, blockgroup);
  873. data += line_size;
  874. data_size -= line_size;
  875. }
  876. return max_duration;
  877. }
  878. static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
  879. unsigned int blockid, AVPacket *pkt, int flags)
  880. {
  881. MatroskaMuxContext *mkv = s->priv_data;
  882. AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
  883. uint8_t *data = NULL;
  884. int size = pkt->size;
  885. int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
  886. av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
  887. "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
  888. avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
  889. if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
  890. (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
  891. ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
  892. else
  893. data = pkt->data;
  894. put_ebml_id(pb, blockid);
  895. put_ebml_num(pb, size+4, 0);
  896. avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
  897. avio_wb16(pb, ts - mkv->cluster_pts);
  898. avio_w8(pb, flags);
  899. avio_write(pb, data, size);
  900. if (data != pkt->data)
  901. av_free(data);
  902. }
  903. static int srt_get_duration(uint8_t **buf)
  904. {
  905. int i, duration = 0;
  906. for (i=0; i<2 && !duration; i++) {
  907. int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
  908. if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
  909. &s_hour, &s_min, &s_sec, &s_hsec,
  910. &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
  911. s_min += 60*s_hour; e_min += 60*e_hour;
  912. s_sec += 60*s_min; e_sec += 60*e_min;
  913. s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
  914. duration = e_hsec - s_hsec;
  915. }
  916. *buf += strcspn(*buf, "\n") + 1;
  917. }
  918. return duration;
  919. }
  920. static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
  921. {
  922. ebml_master blockgroup;
  923. AVPacket pkt2 = *pkt;
  924. int64_t duration = srt_get_duration(&pkt2.data);
  925. pkt2.size -= pkt2.data - pkt->data;
  926. blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
  927. mkv_blockgroup_size(pkt2.size));
  928. mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
  929. put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
  930. end_ebml_master(pb, blockgroup);
  931. return duration;
  932. }
  933. static void mkv_flush_dynbuf(AVFormatContext *s)
  934. {
  935. MatroskaMuxContext *mkv = s->priv_data;
  936. int bufsize;
  937. uint8_t *dyn_buf;
  938. if (!mkv->dyn_bc)
  939. return;
  940. bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
  941. avio_write(s->pb, dyn_buf, bufsize);
  942. av_free(dyn_buf);
  943. mkv->dyn_bc = NULL;
  944. }
  945. static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
  946. {
  947. MatroskaMuxContext *mkv = s->priv_data;
  948. AVIOContext *pb = s->pb;
  949. AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
  950. int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
  951. int duration = pkt->duration;
  952. int ret;
  953. int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
  954. if (ts == AV_NOPTS_VALUE) {
  955. av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
  956. return AVERROR(EINVAL);
  957. }
  958. if (!s->pb->seekable) {
  959. if (!mkv->dyn_bc)
  960. avio_open_dyn_buf(&mkv->dyn_bc);
  961. pb = mkv->dyn_bc;
  962. }
  963. if (!mkv->cluster_pos) {
  964. mkv->cluster_pos = avio_tell(s->pb);
  965. mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
  966. put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
  967. mkv->cluster_pts = FFMAX(0, ts);
  968. }
  969. if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
  970. mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
  971. } else if (codec->codec_id == CODEC_ID_SSA) {
  972. duration = mkv_write_ass_blocks(s, pb, pkt);
  973. } else if (codec->codec_id == CODEC_ID_SRT) {
  974. duration = mkv_write_srt_blocks(s, pb, pkt);
  975. } else {
  976. ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
  977. duration = pkt->convergence_duration;
  978. mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
  979. put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
  980. end_ebml_master(pb, blockgroup);
  981. }
  982. if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
  983. ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
  984. if (ret < 0) return ret;
  985. }
  986. mkv->duration = FFMAX(mkv->duration, ts + duration);
  987. return 0;
  988. }
  989. static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
  990. {
  991. uint8_t *data = mkv->cur_audio_pkt.data;
  992. mkv->cur_audio_pkt = *pkt;
  993. mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
  994. if (!mkv->cur_audio_pkt.data)
  995. return AVERROR(ENOMEM);
  996. memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
  997. mkv->cur_audio_pkt.size = pkt->size;
  998. return 0;
  999. }
  1000. static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
  1001. {
  1002. MatroskaMuxContext *mkv = s->priv_data;
  1003. AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
  1004. AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
  1005. int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
  1006. int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
  1007. int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
  1008. // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
  1009. // after 4k and on a keyframe
  1010. if (mkv->cluster_pos &&
  1011. ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
  1012. || cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
  1013. || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
  1014. av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
  1015. " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
  1016. end_ebml_master(pb, mkv->cluster);
  1017. mkv->cluster_pos = 0;
  1018. if (mkv->dyn_bc)
  1019. mkv_flush_dynbuf(s);
  1020. }
  1021. // check if we have an audio packet cached
  1022. if (mkv->cur_audio_pkt.size > 0) {
  1023. ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
  1024. mkv->cur_audio_pkt.size = 0;
  1025. if (ret < 0) {
  1026. av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
  1027. return ret;
  1028. }
  1029. }
  1030. // buffer an audio packet to ensure the packet containing the video
  1031. // keyframe's timecode is contained in the same cluster for WebM
  1032. if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1033. ret = mkv_copy_packet(mkv, pkt);
  1034. else
  1035. ret = mkv_write_packet_internal(s, pkt);
  1036. return ret;
  1037. }
  1038. static int mkv_write_trailer(AVFormatContext *s)
  1039. {
  1040. MatroskaMuxContext *mkv = s->priv_data;
  1041. AVIOContext *pb = s->pb;
  1042. int64_t currentpos, cuespos;
  1043. int ret;
  1044. // check if we have an audio packet cached
  1045. if (mkv->cur_audio_pkt.size > 0) {
  1046. ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
  1047. mkv->cur_audio_pkt.size = 0;
  1048. if (ret < 0) {
  1049. av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
  1050. return ret;
  1051. }
  1052. }
  1053. if (mkv->dyn_bc) {
  1054. end_ebml_master(mkv->dyn_bc, mkv->cluster);
  1055. mkv_flush_dynbuf(s);
  1056. } else if (mkv->cluster_pos) {
  1057. end_ebml_master(pb, mkv->cluster);
  1058. }
  1059. if (pb->seekable) {
  1060. if (mkv->cues->num_entries) {
  1061. cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
  1062. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
  1063. if (ret < 0) return ret;
  1064. }
  1065. mkv_write_seekhead(pb, mkv->main_seekhead);
  1066. // update the duration
  1067. av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
  1068. currentpos = avio_tell(pb);
  1069. avio_seek(pb, mkv->duration_offset, SEEK_SET);
  1070. put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
  1071. avio_seek(pb, currentpos, SEEK_SET);
  1072. }
  1073. end_ebml_master(pb, mkv->segment);
  1074. av_free(mkv->tracks);
  1075. av_freep(&mkv->cues->entries);
  1076. av_freep(&mkv->cues);
  1077. av_destruct_packet(&mkv->cur_audio_pkt);
  1078. avio_flush(pb);
  1079. return 0;
  1080. }
  1081. static int mkv_query_codec(enum CodecID codec_id, int std_compliance)
  1082. {
  1083. int i;
  1084. for (i = 0; ff_mkv_codec_tags[i].id != CODEC_ID_NONE; i++)
  1085. if (ff_mkv_codec_tags[i].id == codec_id)
  1086. return 1;
  1087. if (std_compliance < FF_COMPLIANCE_NORMAL) { // mkv theoretically supports any
  1088. enum AVMediaType type = avcodec_get_type(codec_id); // video/audio through VFW/ACM
  1089. if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
  1090. return 1;
  1091. }
  1092. return 0;
  1093. }
  1094. const AVCodecTag additional_audio_tags[] = {
  1095. { CODEC_ID_ALAC, 0XFFFFFFFF },
  1096. { CODEC_ID_EAC3, 0XFFFFFFFF },
  1097. { CODEC_ID_MLP, 0xFFFFFFFF },
  1098. { CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
  1099. { CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
  1100. { CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
  1101. { CODEC_ID_QDM2, 0xFFFFFFFF },
  1102. { CODEC_ID_RA_144, 0xFFFFFFFF },
  1103. { CODEC_ID_RA_288, 0xFFFFFFFF },
  1104. { CODEC_ID_COOK, 0xFFFFFFFF },
  1105. { CODEC_ID_TRUEHD, 0xFFFFFFFF },
  1106. { CODEC_ID_TTA, 0xFFFFFFFF },
  1107. { CODEC_ID_WAVPACK, 0xFFFFFFFF },
  1108. { CODEC_ID_NONE, 0xFFFFFFFF }
  1109. };
  1110. const AVCodecTag additional_video_tags[] = {
  1111. { CODEC_ID_PRORES, 0xFFFFFFFF },
  1112. { CODEC_ID_RV10, 0xFFFFFFFF },
  1113. { CODEC_ID_RV20, 0xFFFFFFFF },
  1114. { CODEC_ID_RV30, 0xFFFFFFFF },
  1115. { CODEC_ID_RV40, 0xFFFFFFFF },
  1116. { CODEC_ID_NONE, 0xFFFFFFFF }
  1117. };
  1118. #if CONFIG_MATROSKA_MUXER
  1119. AVOutputFormat ff_matroska_muxer = {
  1120. .name = "matroska",
  1121. .long_name = NULL_IF_CONFIG_SMALL("Matroska file format"),
  1122. .mime_type = "video/x-matroska",
  1123. .extensions = "mkv",
  1124. .priv_data_size = sizeof(MatroskaMuxContext),
  1125. #if CONFIG_LIBVORBIS_ENCODER
  1126. .audio_codec = CODEC_ID_VORBIS,
  1127. #else
  1128. .audio_codec = CODEC_ID_AC3,
  1129. #endif
  1130. #if CONFIG_LIBX264_ENCODER
  1131. .video_codec = CODEC_ID_H264,
  1132. #else
  1133. .video_codec = CODEC_ID_MPEG4,
  1134. #endif
  1135. .write_header = mkv_write_header,
  1136. .write_packet = mkv_write_packet,
  1137. .write_trailer = mkv_write_trailer,
  1138. .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
  1139. .codec_tag = (const AVCodecTag* const []){
  1140. ff_codec_bmp_tags, ff_codec_wav_tags,
  1141. additional_audio_tags, additional_video_tags, 0
  1142. },
  1143. .subtitle_codec = CODEC_ID_SSA,
  1144. .query_codec = mkv_query_codec,
  1145. };
  1146. #endif
  1147. #if CONFIG_WEBM_MUXER
  1148. AVOutputFormat ff_webm_muxer = {
  1149. .name = "webm",
  1150. .long_name = NULL_IF_CONFIG_SMALL("WebM file format"),
  1151. .mime_type = "video/webm",
  1152. .extensions = "webm",
  1153. .priv_data_size = sizeof(MatroskaMuxContext),
  1154. .audio_codec = CODEC_ID_VORBIS,
  1155. .video_codec = CODEC_ID_VP8,
  1156. .write_header = mkv_write_header,
  1157. .write_packet = mkv_write_packet,
  1158. .write_trailer = mkv_write_trailer,
  1159. .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS | AVFMT_TS_NONSTRICT,
  1160. };
  1161. #endif
  1162. #if CONFIG_MATROSKA_AUDIO_MUXER
  1163. AVOutputFormat ff_matroska_audio_muxer = {
  1164. .name = "matroska",
  1165. .long_name = NULL_IF_CONFIG_SMALL("Matroska file format"),
  1166. .mime_type = "audio/x-matroska",
  1167. .extensions = "mka",
  1168. .priv_data_size = sizeof(MatroskaMuxContext),
  1169. #if CONFIG_LIBVORBIS_ENCODER
  1170. .audio_codec = CODEC_ID_VORBIS,
  1171. #else
  1172. .audio_codec = CODEC_ID_AC3,
  1173. #endif
  1174. .video_codec = CODEC_ID_NONE,
  1175. .write_header = mkv_write_header,
  1176. .write_packet = mkv_write_packet,
  1177. .write_trailer = mkv_write_trailer,
  1178. .flags = AVFMT_GLOBALHEADER,
  1179. .codec_tag = (const AVCodecTag* const []){
  1180. ff_codec_wav_tags, additional_audio_tags, 0
  1181. },
  1182. };
  1183. #endif