You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

813 lines
28KB

  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 "md5.h"
  23. #include "riff.h"
  24. #include "xiph.h"
  25. #include "matroska.h"
  26. typedef struct ebml_master {
  27. offset_t pos; ///< absolute offset in the file where the master's elements start
  28. int sizebytes; ///< how many bytes were reserved for the size
  29. } ebml_master;
  30. typedef struct mkv_seekhead_entry {
  31. unsigned int elementid;
  32. uint64_t segmentpos;
  33. } mkv_seekhead_entry;
  34. typedef struct mkv_seekhead {
  35. offset_t filepos;
  36. offset_t segment_offset; ///< the file offset to the beginning of the segment
  37. int reserved_size; ///< -1 if appending to file
  38. int max_entries;
  39. mkv_seekhead_entry *entries;
  40. int num_entries;
  41. } mkv_seekhead;
  42. typedef struct {
  43. uint64_t pts;
  44. int tracknum;
  45. offset_t cluster_pos; ///< file offset of the cluster containing the block
  46. } mkv_cuepoint;
  47. typedef struct {
  48. offset_t segment_offset;
  49. mkv_cuepoint *entries;
  50. int num_entries;
  51. } mkv_cues;
  52. typedef struct MatroskaMuxContext {
  53. ebml_master segment;
  54. offset_t segment_offset;
  55. offset_t segment_uid;
  56. ebml_master cluster;
  57. offset_t cluster_pos; ///< file offset of the current cluster
  58. uint64_t cluster_pts;
  59. offset_t duration_offset;
  60. uint64_t duration;
  61. mkv_seekhead *main_seekhead;
  62. mkv_seekhead *cluster_seekhead;
  63. mkv_cues *cues;
  64. struct AVMD5 *md5_ctx;
  65. } MatroskaMuxContext;
  66. // 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
  67. // offset, 4 bytes for target EBML ID
  68. #define MAX_SEEKENTRY_SIZE 21
  69. // per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
  70. // 8-byte uint max
  71. #define MAX_CUETRACKPOS_SIZE 22
  72. // per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max
  73. #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
  74. static int ebml_id_size(unsigned int id)
  75. {
  76. return (av_log2(id+1)-1)/7+1;
  77. }
  78. static void put_ebml_id(ByteIOContext *pb, unsigned int id)
  79. {
  80. int i = ebml_id_size(id);
  81. while (i--)
  82. put_byte(pb, id >> (i*8));
  83. }
  84. /**
  85. * Write an EBML size meaning "unknown size"
  86. *
  87. * @param bytes The number of bytes the size should occupy. Maximum of 8.
  88. */
  89. static void put_ebml_size_unknown(ByteIOContext *pb, int bytes)
  90. {
  91. assert(bytes <= 8);
  92. put_byte(pb, 0x1ff >> bytes);
  93. while (--bytes)
  94. put_byte(pb, 0xff);
  95. }
  96. /**
  97. * Calculate how many bytes are needed to represent a given size in EBML.
  98. */
  99. static int ebml_size_bytes(uint64_t size)
  100. {
  101. int bytes = 1;
  102. while ((size+1) >> bytes*7) bytes++;
  103. return bytes;
  104. }
  105. /**
  106. * Write a size in EBML variable length format.
  107. *
  108. * @param bytes The number of bytes that need to be used to write the size.
  109. * If zero, any number of bytes can be used.
  110. */
  111. static void put_ebml_size(ByteIOContext *pb, uint64_t size, int bytes)
  112. {
  113. int i, needed_bytes = ebml_size_bytes(size);
  114. // sizes larger than this are currently undefined in EBML
  115. // so write "unknown" size
  116. if (size >= (1ULL<<56)-1) {
  117. put_ebml_size_unknown(pb, 1);
  118. return;
  119. }
  120. if (bytes == 0)
  121. // don't care how many bytes are used, so use the min
  122. bytes = needed_bytes;
  123. // the bytes needed to write the given size would exceed the bytes
  124. // that we need to use, so write unknown size. This shouldn't happen.
  125. assert(bytes >= needed_bytes);
  126. size |= 1ULL << bytes*7;
  127. for (i = bytes - 1; i >= 0; i--)
  128. put_byte(pb, size >> i*8);
  129. }
  130. static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
  131. {
  132. int i, bytes = 1;
  133. while (val >> bytes*8) bytes++;
  134. put_ebml_id(pb, elementid);
  135. put_ebml_size(pb, bytes, 0);
  136. for (i = bytes - 1; i >= 0; i--)
  137. put_byte(pb, val >> i*8);
  138. }
  139. static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
  140. {
  141. put_ebml_id(pb, elementid);
  142. put_ebml_size(pb, 8, 0);
  143. put_be64(pb, av_dbl2int(val));
  144. }
  145. static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
  146. const uint8_t *buf, int size)
  147. {
  148. put_ebml_id(pb, elementid);
  149. put_ebml_size(pb, size, 0);
  150. put_buffer(pb, buf, size);
  151. }
  152. static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
  153. {
  154. put_ebml_binary(pb, elementid, str, strlen(str));
  155. }
  156. /**
  157. * Writes a void element of a given size. Useful for reserving space in
  158. * the file to be written to later.
  159. *
  160. * @param size The number of bytes to reserve, which must be at least 2.
  161. */
  162. static void put_ebml_void(ByteIOContext *pb, uint64_t size)
  163. {
  164. offset_t currentpos = url_ftell(pb);
  165. assert(size >= 2);
  166. put_ebml_id(pb, EBML_ID_VOID);
  167. // we need to subtract the length needed to store the size from the
  168. // size we need to reserve so 2 cases, we use 8 bytes to store the
  169. // size if possible, 1 byte otherwise
  170. if (size < 10)
  171. put_ebml_size(pb, size-1, 0);
  172. else
  173. put_ebml_size(pb, size-9, 8);
  174. url_fseek(pb, currentpos + size, SEEK_SET);
  175. }
  176. static ebml_master start_ebml_master(ByteIOContext *pb, unsigned int elementid, uint64_t expectedsize)
  177. {
  178. int bytes = expectedsize ? ebml_size_bytes(expectedsize) : 8;
  179. put_ebml_id(pb, elementid);
  180. put_ebml_size_unknown(pb, bytes);
  181. return (ebml_master){ url_ftell(pb), bytes };
  182. }
  183. static void end_ebml_master(ByteIOContext *pb, ebml_master master)
  184. {
  185. offset_t pos = url_ftell(pb);
  186. url_fseek(pb, master.pos - master.sizebytes, SEEK_SET);
  187. put_ebml_size(pb, pos - master.pos, master.sizebytes);
  188. url_fseek(pb, pos, SEEK_SET);
  189. }
  190. static void put_xiph_size(ByteIOContext *pb, int size)
  191. {
  192. int i;
  193. for (i = 0; i < size / 255; i++)
  194. put_byte(pb, 255);
  195. put_byte(pb, size % 255);
  196. }
  197. /**
  198. * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
  199. * elements. If a maximum number of elements is specified, enough space
  200. * will be reserved at the current file location to write a seek head of
  201. * that size.
  202. *
  203. * @param segment_offset The absolute offset to the position in the file
  204. * where the segment begins
  205. * @param numelements the maximum number of elements that will be indexed
  206. * by this seek head, 0 if unlimited.
  207. */
  208. static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, offset_t segment_offset, int numelements)
  209. {
  210. mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
  211. if (new_seekhead == NULL)
  212. return NULL;
  213. new_seekhead->segment_offset = segment_offset;
  214. if (numelements > 0) {
  215. new_seekhead->filepos = url_ftell(pb);
  216. // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
  217. // and size, and 3 bytes to guarantee that an EBML void element
  218. // will fit afterwards
  219. new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
  220. new_seekhead->max_entries = numelements;
  221. put_ebml_void(pb, new_seekhead->reserved_size);
  222. }
  223. return new_seekhead;
  224. }
  225. static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
  226. {
  227. mkv_seekhead_entry *entries = seekhead->entries;
  228. int new_entry = seekhead->num_entries;
  229. // don't store more elements than we reserved space for
  230. if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
  231. return -1;
  232. entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
  233. if (entries == NULL)
  234. return AVERROR(ENOMEM);
  235. entries[new_entry].elementid = elementid;
  236. entries[new_entry].segmentpos = filepos - seekhead->segment_offset;
  237. seekhead->entries = entries;
  238. seekhead->num_entries++;
  239. return 0;
  240. }
  241. /**
  242. * Write the seek head to the file and free it. If a maximum number of
  243. * elements was specified to mkv_start_seekhead(), the seek head will
  244. * be written at the location reserved for it. Otherwise, it is written
  245. * at the current location in the file.
  246. *
  247. * @return the file offset where the seekhead was written
  248. */
  249. static offset_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
  250. {
  251. ebml_master metaseek, seekentry;
  252. offset_t currentpos;
  253. int i;
  254. currentpos = url_ftell(pb);
  255. if (seekhead->reserved_size > 0)
  256. url_fseek(pb, seekhead->filepos, SEEK_SET);
  257. metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
  258. for (i = 0; i < seekhead->num_entries; i++) {
  259. mkv_seekhead_entry *entry = &seekhead->entries[i];
  260. seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
  261. put_ebml_id(pb, MATROSKA_ID_SEEKID);
  262. put_ebml_size(pb, ebml_id_size(entry->elementid), 0);
  263. put_ebml_id(pb, entry->elementid);
  264. put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
  265. end_ebml_master(pb, seekentry);
  266. }
  267. end_ebml_master(pb, metaseek);
  268. if (seekhead->reserved_size > 0) {
  269. uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
  270. put_ebml_void(pb, remaining);
  271. url_fseek(pb, currentpos, SEEK_SET);
  272. currentpos = seekhead->filepos;
  273. }
  274. av_free(seekhead->entries);
  275. av_free(seekhead);
  276. return currentpos;
  277. }
  278. static mkv_cues * mkv_start_cues(offset_t segment_offset)
  279. {
  280. mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
  281. if (cues == NULL)
  282. return NULL;
  283. cues->segment_offset = segment_offset;
  284. return cues;
  285. }
  286. static int mkv_add_cuepoint(mkv_cues *cues, AVPacket *pkt, offset_t cluster_pos)
  287. {
  288. mkv_cuepoint *entries = cues->entries;
  289. int new_entry = cues->num_entries;
  290. entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
  291. if (entries == NULL)
  292. return AVERROR(ENOMEM);
  293. entries[new_entry].pts = pkt->pts;
  294. entries[new_entry].tracknum = pkt->stream_index + 1;
  295. entries[new_entry].cluster_pos = cluster_pos - cues->segment_offset;
  296. cues->entries = entries;
  297. cues->num_entries++;
  298. return 0;
  299. }
  300. static offset_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues, int num_tracks)
  301. {
  302. ebml_master cues_element;
  303. offset_t currentpos;
  304. int i, j;
  305. currentpos = url_ftell(pb);
  306. cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
  307. for (i = 0; i < cues->num_entries; i++) {
  308. ebml_master cuepoint, track_positions;
  309. mkv_cuepoint *entry = &cues->entries[i];
  310. uint64_t pts = entry->pts;
  311. cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
  312. put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
  313. // put all the entries from different tracks that have the exact same
  314. // timestamp into the same CuePoint
  315. for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
  316. track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
  317. put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
  318. put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
  319. end_ebml_master(pb, track_positions);
  320. }
  321. i += j - 1;
  322. end_ebml_master(pb, cuepoint);
  323. }
  324. end_ebml_master(pb, cues_element);
  325. av_free(cues->entries);
  326. av_free(cues);
  327. return currentpos;
  328. }
  329. static int put_xiph_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
  330. {
  331. ebml_master codecprivate;
  332. uint8_t *header_start[3];
  333. int header_len[3];
  334. int first_header_size;
  335. int j;
  336. if (codec->codec_id == CODEC_ID_VORBIS)
  337. first_header_size = 30;
  338. else
  339. first_header_size = 42;
  340. if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
  341. first_header_size, header_start, header_len) < 0) {
  342. av_log(codec, AV_LOG_ERROR, "Extradata corrupt.\n");
  343. return -1;
  344. }
  345. codecprivate = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE, 0);
  346. put_byte(pb, 2); // number packets - 1
  347. for (j = 0; j < 2; j++) {
  348. put_xiph_size(pb, header_len[j]);
  349. }
  350. for (j = 0; j < 3; j++)
  351. put_buffer(pb, header_start[j], header_len[j]);
  352. end_ebml_master(pb, codecprivate);
  353. return 0;
  354. }
  355. #define FLAC_STREAMINFO_SIZE 34
  356. static int put_flac_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
  357. {
  358. ebml_master codecpriv = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE, 0);
  359. // if the extradata_size is greater than FLAC_STREAMINFO_SIZE,
  360. // assume that it's in Matroska's format already
  361. if (codec->extradata_size < FLAC_STREAMINFO_SIZE) {
  362. av_log(codec, AV_LOG_ERROR, "Invalid FLAC extradata\n");
  363. return -1;
  364. } else if (codec->extradata_size == FLAC_STREAMINFO_SIZE) {
  365. // only the streaminfo packet
  366. put_byte(pb, 0);
  367. put_xiph_size(pb, codec->extradata_size);
  368. av_log(codec, AV_LOG_ERROR, "Only one packet\n");
  369. }
  370. put_buffer(pb, codec->extradata, codec->extradata_size);
  371. end_ebml_master(pb, codecpriv);
  372. return 0;
  373. }
  374. static void get_aac_sample_rates(AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
  375. {
  376. static const int aac_sample_rates[] = {
  377. 96000, 88200, 64000, 48000, 44100, 32000,
  378. 24000, 22050, 16000, 12000, 11025, 8000,
  379. };
  380. int sri;
  381. if (codec->extradata_size < 2) {
  382. av_log(codec, AV_LOG_WARNING, "no AAC extradata, unable to determine samplerate\n");
  383. return;
  384. }
  385. sri = ((codec->extradata[0] << 1) & 0xE) | (codec->extradata[1] >> 7);
  386. if (sri > 12) {
  387. av_log(codec, AV_LOG_WARNING, "AAC samplerate index out of bounds\n");
  388. return;
  389. }
  390. *sample_rate = aac_sample_rates[sri];
  391. // if sbr, get output sample rate as well
  392. if (codec->extradata_size == 5) {
  393. sri = (codec->extradata[4] >> 3) & 0xF;
  394. if (sri > 12) {
  395. av_log(codec, AV_LOG_WARNING, "AAC output samplerate index out of bounds\n");
  396. return;
  397. }
  398. *output_sample_rate = aac_sample_rates[sri];
  399. }
  400. }
  401. static int mkv_write_tracks(AVFormatContext *s)
  402. {
  403. MatroskaMuxContext *mkv = s->priv_data;
  404. ByteIOContext *pb = &s->pb;
  405. ebml_master tracks;
  406. int i, j;
  407. if (mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb)) < 0)
  408. return -1;
  409. tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
  410. for (i = 0; i < s->nb_streams; i++) {
  411. AVStream *st = s->streams[i];
  412. AVCodecContext *codec = st->codec;
  413. ebml_master subinfo, track;
  414. int native_id = 0;
  415. int bit_depth = av_get_bits_per_sample(codec->codec_id);
  416. int sample_rate = codec->sample_rate;
  417. int output_sample_rate = 0;
  418. if (!bit_depth)
  419. bit_depth = av_get_bits_per_sample_format(codec->sample_fmt);
  420. if (codec->codec_id == CODEC_ID_AAC)
  421. get_aac_sample_rates(codec, &sample_rate, &output_sample_rate);
  422. track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
  423. put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
  424. put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
  425. put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
  426. if (st->language[0])
  427. put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, st->language);
  428. else
  429. put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, "und");
  430. // look for a codec id string specific to mkv to use,
  431. // if none are found, use AVI codes
  432. for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
  433. if (ff_mkv_codec_tags[j].id == codec->codec_id) {
  434. put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
  435. native_id = 1;
  436. break;
  437. }
  438. }
  439. if (native_id) {
  440. if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA) {
  441. if (put_xiph_codecpriv(pb, codec) < 0)
  442. return -1;
  443. } else if (codec->codec_id == CODEC_ID_FLAC) {
  444. if (put_flac_codecpriv(pb, codec) < 0)
  445. return -1;
  446. } else if (codec->extradata_size) {
  447. put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codec->extradata, codec->extradata_size);
  448. }
  449. }
  450. switch (codec->codec_type) {
  451. case CODEC_TYPE_VIDEO:
  452. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
  453. if (!native_id) {
  454. ebml_master bmp_header;
  455. // if there is no mkv-specific codec id, use VFW mode
  456. if (!codec->codec_tag)
  457. codec->codec_tag = codec_get_tag(codec_bmp_tags, codec->codec_id);
  458. put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC);
  459. bmp_header = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE, 0);
  460. put_bmp_header(pb, codec, codec_bmp_tags, 0);
  461. end_ebml_master(pb, bmp_header);
  462. }
  463. subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
  464. // XXX: interlace flag?
  465. put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
  466. put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
  467. if (codec->sample_aspect_ratio.num) {
  468. AVRational dar = av_mul_q(codec->sample_aspect_ratio, (AVRational){codec->width, codec->height});
  469. put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , dar.num);
  470. put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, dar.den);
  471. }
  472. end_ebml_master(pb, subinfo);
  473. break;
  474. case CODEC_TYPE_AUDIO:
  475. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
  476. if (!native_id) {
  477. ebml_master wav_header;
  478. // no mkv-specific ID, use ACM mode
  479. codec->codec_tag = codec_get_tag(codec_wav_tags, codec->codec_id);
  480. if (!codec->codec_tag) {
  481. av_log(s, AV_LOG_ERROR, "no codec id found for stream %d", i);
  482. return -1;
  483. }
  484. put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_AUDIO_ACM);
  485. wav_header = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE, 0);
  486. put_wav_header(pb, codec);
  487. end_ebml_master(pb, wav_header);
  488. }
  489. subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
  490. put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
  491. put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
  492. if (output_sample_rate)
  493. put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
  494. if (bit_depth)
  495. put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
  496. end_ebml_master(pb, subinfo);
  497. break;
  498. case CODEC_TYPE_SUBTITLE:
  499. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
  500. break;
  501. default:
  502. av_log(s, AV_LOG_ERROR, "Only audio and video are supported for Matroska.");
  503. break;
  504. }
  505. end_ebml_master(pb, track);
  506. // ms precision is the de-facto standard timescale for mkv files
  507. av_set_pts_info(st, 64, 1, 1000);
  508. }
  509. end_ebml_master(pb, tracks);
  510. return 0;
  511. }
  512. static int mkv_write_header(AVFormatContext *s)
  513. {
  514. MatroskaMuxContext *mkv = s->priv_data;
  515. ByteIOContext *pb = &s->pb;
  516. ebml_master ebml_header, segment_info;
  517. mkv->md5_ctx = av_mallocz(av_md5_size);
  518. av_md5_init(mkv->md5_ctx);
  519. ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
  520. put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
  521. put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
  522. put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
  523. put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
  524. put_ebml_string (pb, EBML_ID_DOCTYPE , "matroska");
  525. put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
  526. put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
  527. end_ebml_master(pb, ebml_header);
  528. mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
  529. mkv->segment_offset = url_ftell(pb);
  530. // we write 2 seek heads - one at the end of the file to point to each
  531. // cluster, and one at the beginning to point to all other level one
  532. // elements (including the seek head at the end of the file), which
  533. // isn't more than 10 elements if we only write one of each other
  534. // currently defined level 1 element
  535. mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
  536. mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
  537. if (mkv->main_seekhead == NULL || mkv->cluster_seekhead == NULL)
  538. return AVERROR(ENOMEM);
  539. if (mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb)) < 0)
  540. return -1;
  541. segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
  542. put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
  543. if (strlen(s->title))
  544. put_ebml_string(pb, MATROSKA_ID_TITLE, s->title);
  545. if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  546. put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
  547. put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
  548. // reserve space to write the segment UID later
  549. mkv->segment_uid = url_ftell(pb);
  550. put_ebml_void(pb, 19);
  551. }
  552. // reserve space for the duration
  553. mkv->duration = 0;
  554. mkv->duration_offset = url_ftell(pb);
  555. put_ebml_void(pb, 11); // assumes double-precision float to be written
  556. end_ebml_master(pb, segment_info);
  557. if (mkv_write_tracks(s) < 0)
  558. return -1;
  559. if (mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb)) < 0)
  560. return -1;
  561. mkv->cluster_pos = url_ftell(pb);
  562. mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
  563. put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, 0);
  564. mkv->cluster_pts = 0;
  565. mkv->cues = mkv_start_cues(mkv->segment_offset);
  566. if (mkv->cues == NULL)
  567. return AVERROR(ENOMEM);
  568. return 0;
  569. }
  570. static int mkv_block_size(AVPacket *pkt)
  571. {
  572. int size = 4; // track num + timecode + flags
  573. return size + pkt->size;
  574. }
  575. static int mkv_blockgroup_size(AVPacket *pkt)
  576. {
  577. int size = mkv_block_size(pkt);
  578. size += ebml_size_bytes(size);
  579. size += 2; // EBML ID for block and block duration
  580. size += 8; // max size of block duration
  581. size += ebml_size_bytes(size);
  582. size += 1; // blockgroup EBML ID
  583. return size;
  584. }
  585. static void mkv_write_block(AVFormatContext *s, unsigned int blockid, AVPacket *pkt, int flags)
  586. {
  587. MatroskaMuxContext *mkv = s->priv_data;
  588. ByteIOContext *pb = &s->pb;
  589. av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
  590. url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
  591. put_ebml_id(pb, blockid);
  592. put_ebml_size(pb, mkv_block_size(pkt), 0);
  593. put_byte(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
  594. put_be16(pb, pkt->pts - mkv->cluster_pts);
  595. put_byte(pb, flags);
  596. put_buffer(pb, pkt->data, pkt->size);
  597. }
  598. static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
  599. {
  600. MatroskaMuxContext *mkv = s->priv_data;
  601. ByteIOContext *pb = &s->pb;
  602. AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
  603. int keyframe = !!(pkt->flags & PKT_FLAG_KEY);
  604. // start a new cluster every 5 MB or 5 sec
  605. if (url_ftell(pb) > mkv->cluster_pos + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
  606. av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64 " bytes, pts %" PRIu64 "\n", url_ftell(pb), pkt->pts);
  607. end_ebml_master(pb, mkv->cluster);
  608. if (mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb)) < 0)
  609. return -1;
  610. mkv->cluster_pos = url_ftell(pb);
  611. mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
  612. put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
  613. mkv->cluster_pts = pkt->pts;
  614. av_md5_update(mkv->md5_ctx, pkt->data, FFMIN(200, pkt->size));
  615. }
  616. if (codec->codec_type != CODEC_TYPE_SUBTITLE) {
  617. mkv_write_block(s, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
  618. } else {
  619. ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt));
  620. mkv_write_block(s, MATROSKA_ID_BLOCK, pkt, 0);
  621. put_ebml_uint(pb, MATROSKA_ID_DURATION, pkt->duration);
  622. end_ebml_master(pb, blockgroup);
  623. }
  624. if (codec->codec_type == CODEC_TYPE_VIDEO && keyframe) {
  625. if (mkv_add_cuepoint(mkv->cues, pkt, mkv->cluster_pos) < 0)
  626. return -1;
  627. }
  628. mkv->duration = pkt->pts + pkt->duration;
  629. return 0;
  630. }
  631. static int mkv_write_trailer(AVFormatContext *s)
  632. {
  633. MatroskaMuxContext *mkv = s->priv_data;
  634. ByteIOContext *pb = &s->pb;
  635. offset_t currentpos, second_seekhead, cuespos;
  636. end_ebml_master(pb, mkv->cluster);
  637. cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
  638. second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
  639. mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES , cuespos);
  640. mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
  641. mkv_write_seekhead(pb, mkv->main_seekhead);
  642. // update the duration
  643. av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
  644. currentpos = url_ftell(pb);
  645. url_fseek(pb, mkv->duration_offset, SEEK_SET);
  646. put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
  647. // write the md5sum of some frames as the segment UID
  648. if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  649. uint8_t segment_uid[16];
  650. av_md5_final(mkv->md5_ctx, segment_uid);
  651. url_fseek(pb, mkv->segment_uid, SEEK_SET);
  652. put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
  653. }
  654. url_fseek(pb, currentpos, SEEK_SET);
  655. end_ebml_master(pb, mkv->segment);
  656. av_free(mkv->md5_ctx);
  657. return 0;
  658. }
  659. AVOutputFormat matroska_muxer = {
  660. "matroska",
  661. "Matroska File Format",
  662. "video/x-matroska",
  663. "mkv",
  664. sizeof(MatroskaMuxContext),
  665. CODEC_ID_MP2,
  666. CODEC_ID_MPEG4,
  667. mkv_write_header,
  668. mkv_write_packet,
  669. mkv_write_trailer,
  670. .codec_tag = (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
  671. .subtitle_codec = CODEC_ID_TEXT,
  672. };
  673. AVOutputFormat matroska_audio_muxer = {
  674. "matroska",
  675. "Matroska File Format",
  676. "audio/x-matroska",
  677. "mka",
  678. sizeof(MatroskaMuxContext),
  679. CODEC_ID_MP2,
  680. CODEC_ID_NONE,
  681. mkv_write_header,
  682. mkv_write_packet,
  683. mkv_write_trailer,
  684. .codec_tag = (const AVCodecTag*[]){codec_wav_tags, 0},
  685. };