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.

3444 lines
122KB

  1. /*
  2. * Matroska file demuxer
  3. * Copyright (c) 2003-2008 The FFmpeg Project
  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. /**
  22. * @file
  23. * Matroska file demuxer
  24. * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * @see specs available on the Matroska project page: http://www.matroska.org/
  28. */
  29. #include "config.h"
  30. #include <inttypes.h>
  31. #include <stdio.h>
  32. #include "libavutil/avstring.h"
  33. #include "libavutil/base64.h"
  34. #include "libavutil/dict.h"
  35. #include "libavutil/intfloat.h"
  36. #include "libavutil/intreadwrite.h"
  37. #include "libavutil/lzo.h"
  38. #include "libavutil/mathematics.h"
  39. #include "libavutil/time_internal.h"
  40. #include "libavcodec/bytestream.h"
  41. #include "libavcodec/flac.h"
  42. #include "libavcodec/mpeg4audio.h"
  43. #include "avformat.h"
  44. #include "avio_internal.h"
  45. #include "internal.h"
  46. #include "isom.h"
  47. #include "matroska.h"
  48. #include "oggdec.h"
  49. /* For ff_codec_get_id(). */
  50. #include "riff.h"
  51. #include "rmsipr.h"
  52. #if CONFIG_BZLIB
  53. #include <bzlib.h>
  54. #endif
  55. #if CONFIG_ZLIB
  56. #include <zlib.h>
  57. #endif
  58. typedef enum {
  59. EBML_NONE,
  60. EBML_UINT,
  61. EBML_FLOAT,
  62. EBML_STR,
  63. EBML_UTF8,
  64. EBML_BIN,
  65. EBML_NEST,
  66. EBML_LEVEL1,
  67. EBML_PASS,
  68. EBML_STOP,
  69. EBML_SINT,
  70. EBML_TYPE_COUNT
  71. } EbmlType;
  72. typedef const struct EbmlSyntax {
  73. uint32_t id;
  74. EbmlType type;
  75. int list_elem_size;
  76. int data_offset;
  77. union {
  78. uint64_t u;
  79. double f;
  80. const char *s;
  81. const struct EbmlSyntax *n;
  82. } def;
  83. } EbmlSyntax;
  84. typedef struct EbmlList {
  85. int nb_elem;
  86. void *elem;
  87. } EbmlList;
  88. typedef struct EbmlBin {
  89. int size;
  90. uint8_t *data;
  91. int64_t pos;
  92. } EbmlBin;
  93. typedef struct Ebml {
  94. uint64_t version;
  95. uint64_t max_size;
  96. uint64_t id_length;
  97. char *doctype;
  98. uint64_t doctype_version;
  99. } Ebml;
  100. typedef struct MatroskaTrackCompression {
  101. uint64_t algo;
  102. EbmlBin settings;
  103. } MatroskaTrackCompression;
  104. typedef struct MatroskaTrackEncryption {
  105. uint64_t algo;
  106. EbmlBin key_id;
  107. } MatroskaTrackEncryption;
  108. typedef struct MatroskaTrackEncoding {
  109. uint64_t scope;
  110. uint64_t type;
  111. MatroskaTrackCompression compression;
  112. MatroskaTrackEncryption encryption;
  113. } MatroskaTrackEncoding;
  114. typedef struct MatroskaTrackVideo {
  115. double frame_rate;
  116. uint64_t display_width;
  117. uint64_t display_height;
  118. uint64_t pixel_width;
  119. uint64_t pixel_height;
  120. EbmlBin color_space;
  121. uint64_t stereo_mode;
  122. uint64_t alpha_mode;
  123. } MatroskaTrackVideo;
  124. typedef struct MatroskaTrackAudio {
  125. double samplerate;
  126. double out_samplerate;
  127. uint64_t bitdepth;
  128. uint64_t channels;
  129. /* real audio header (extracted from extradata) */
  130. int coded_framesize;
  131. int sub_packet_h;
  132. int frame_size;
  133. int sub_packet_size;
  134. int sub_packet_cnt;
  135. int pkt_cnt;
  136. uint64_t buf_timecode;
  137. uint8_t *buf;
  138. } MatroskaTrackAudio;
  139. typedef struct MatroskaTrackPlane {
  140. uint64_t uid;
  141. uint64_t type;
  142. } MatroskaTrackPlane;
  143. typedef struct MatroskaTrackOperation {
  144. EbmlList combine_planes;
  145. } MatroskaTrackOperation;
  146. typedef struct MatroskaTrack {
  147. uint64_t num;
  148. uint64_t uid;
  149. uint64_t type;
  150. char *name;
  151. char *codec_id;
  152. EbmlBin codec_priv;
  153. char *language;
  154. double time_scale;
  155. uint64_t default_duration;
  156. uint64_t flag_default;
  157. uint64_t flag_forced;
  158. uint64_t seek_preroll;
  159. MatroskaTrackVideo video;
  160. MatroskaTrackAudio audio;
  161. MatroskaTrackOperation operation;
  162. EbmlList encodings;
  163. uint64_t codec_delay;
  164. AVStream *stream;
  165. int64_t end_timecode;
  166. int ms_compat;
  167. uint64_t max_block_additional_id;
  168. } MatroskaTrack;
  169. typedef struct MatroskaAttachment {
  170. uint64_t uid;
  171. char *filename;
  172. char *mime;
  173. EbmlBin bin;
  174. AVStream *stream;
  175. } MatroskaAttachment;
  176. typedef struct MatroskaChapter {
  177. uint64_t start;
  178. uint64_t end;
  179. uint64_t uid;
  180. char *title;
  181. AVChapter *chapter;
  182. } MatroskaChapter;
  183. typedef struct MatroskaIndexPos {
  184. uint64_t track;
  185. uint64_t pos;
  186. } MatroskaIndexPos;
  187. typedef struct MatroskaIndex {
  188. uint64_t time;
  189. EbmlList pos;
  190. } MatroskaIndex;
  191. typedef struct MatroskaTag {
  192. char *name;
  193. char *string;
  194. char *lang;
  195. uint64_t def;
  196. EbmlList sub;
  197. } MatroskaTag;
  198. typedef struct MatroskaTagTarget {
  199. char *type;
  200. uint64_t typevalue;
  201. uint64_t trackuid;
  202. uint64_t chapteruid;
  203. uint64_t attachuid;
  204. } MatroskaTagTarget;
  205. typedef struct MatroskaTags {
  206. MatroskaTagTarget target;
  207. EbmlList tag;
  208. } MatroskaTags;
  209. typedef struct MatroskaSeekhead {
  210. uint64_t id;
  211. uint64_t pos;
  212. } MatroskaSeekhead;
  213. typedef struct MatroskaLevel {
  214. uint64_t start;
  215. uint64_t length;
  216. } MatroskaLevel;
  217. typedef struct MatroskaCluster {
  218. uint64_t timecode;
  219. EbmlList blocks;
  220. } MatroskaCluster;
  221. typedef struct MatroskaLevel1Element {
  222. uint64_t id;
  223. uint64_t pos;
  224. int parsed;
  225. } MatroskaLevel1Element;
  226. typedef struct MatroskaDemuxContext {
  227. AVFormatContext *ctx;
  228. /* EBML stuff */
  229. int num_levels;
  230. MatroskaLevel levels[EBML_MAX_DEPTH];
  231. int level_up;
  232. uint32_t current_id;
  233. uint64_t time_scale;
  234. double duration;
  235. char *title;
  236. char *muxingapp;
  237. EbmlBin date_utc;
  238. EbmlList tracks;
  239. EbmlList attachments;
  240. EbmlList chapters;
  241. EbmlList index;
  242. EbmlList tags;
  243. EbmlList seekhead;
  244. /* byte position of the segment inside the stream */
  245. int64_t segment_start;
  246. /* the packet queue */
  247. AVPacket **packets;
  248. int num_packets;
  249. AVPacket *prev_pkt;
  250. int done;
  251. /* What to skip before effectively reading a packet. */
  252. int skip_to_keyframe;
  253. uint64_t skip_to_timecode;
  254. /* File has a CUES element, but we defer parsing until it is needed. */
  255. int cues_parsing_deferred;
  256. /* Level1 elements and whether they were read yet */
  257. MatroskaLevel1Element level1_elems[64];
  258. int num_level1_elems;
  259. int current_cluster_num_blocks;
  260. int64_t current_cluster_pos;
  261. MatroskaCluster current_cluster;
  262. /* File has SSA subtitles which prevent incremental cluster parsing. */
  263. int contains_ssa;
  264. } MatroskaDemuxContext;
  265. typedef struct MatroskaBlock {
  266. uint64_t duration;
  267. int64_t reference;
  268. uint64_t non_simple;
  269. EbmlBin bin;
  270. uint64_t additional_id;
  271. EbmlBin additional;
  272. int64_t discard_padding;
  273. } MatroskaBlock;
  274. static EbmlSyntax ebml_header[] = {
  275. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml, version), { .u = EBML_VERSION } },
  276. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml, max_size), { .u = 8 } },
  277. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml, id_length), { .u = 4 } },
  278. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml, doctype), { .s = "(none)" } },
  279. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml, doctype_version), { .u = 1 } },
  280. { EBML_ID_EBMLVERSION, EBML_NONE },
  281. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  282. { 0 }
  283. };
  284. static EbmlSyntax ebml_syntax[] = {
  285. { EBML_ID_HEADER, EBML_NEST, 0, 0, { .n = ebml_header } },
  286. { 0 }
  287. };
  288. static EbmlSyntax matroska_info[] = {
  289. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext, time_scale), { .u = 1000000 } },
  290. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext, duration) },
  291. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext, title) },
  292. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  293. { MATROSKA_ID_MUXINGAPP, EBML_UTF8, 0, offsetof(MatroskaDemuxContext, muxingapp) },
  294. { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext, date_utc) },
  295. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  296. { 0 }
  297. };
  298. static EbmlSyntax matroska_track_video[] = {
  299. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT, 0, offsetof(MatroskaTrackVideo, frame_rate) },
  300. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_width), { .u=-1 } },
  301. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_height), { .u=-1 } },
  302. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo, pixel_width) },
  303. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, pixel_height) },
  304. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo, color_space) },
  305. { MATROSKA_ID_VIDEOALPHAMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo, alpha_mode) },
  306. { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
  307. { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
  308. { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
  309. { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
  310. { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
  311. { MATROSKA_ID_VIDEOFLAGINTERLACED, EBML_NONE },
  312. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo, stereo_mode), { .u = MATROSKA_VIDEO_STEREOMODE_TYPE_NB } },
  313. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  314. { 0 }
  315. };
  316. static EbmlSyntax matroska_track_audio[] = {
  317. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, samplerate), { .f = 8000.0 } },
  318. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, out_samplerate) },
  319. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio, bitdepth) },
  320. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio, channels), { .u = 1 } },
  321. { 0 }
  322. };
  323. static EbmlSyntax matroska_track_encoding_compression[] = {
  324. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression, algo), { .u = 0 } },
  325. { MATROSKA_ID_ENCODINGCOMPSETTINGS, EBML_BIN, 0, offsetof(MatroskaTrackCompression, settings) },
  326. { 0 }
  327. };
  328. static EbmlSyntax matroska_track_encoding_encryption[] = {
  329. { MATROSKA_ID_ENCODINGENCALGO, EBML_UINT, 0, offsetof(MatroskaTrackEncryption,algo), {.u = 0} },
  330. { MATROSKA_ID_ENCODINGENCKEYID, EBML_BIN, 0, offsetof(MatroskaTrackEncryption,key_id) },
  331. { MATROSKA_ID_ENCODINGENCAESSETTINGS, EBML_NONE },
  332. { MATROSKA_ID_ENCODINGSIGALGO, EBML_NONE },
  333. { MATROSKA_ID_ENCODINGSIGHASHALGO, EBML_NONE },
  334. { MATROSKA_ID_ENCODINGSIGKEYID, EBML_NONE },
  335. { MATROSKA_ID_ENCODINGSIGNATURE, EBML_NONE },
  336. { 0 }
  337. };
  338. static EbmlSyntax matroska_track_encoding[] = {
  339. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding, scope), { .u = 1 } },
  340. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding, type), { .u = 0 } },
  341. { MATROSKA_ID_ENCODINGCOMPRESSION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, compression), { .n = matroska_track_encoding_compression } },
  342. { MATROSKA_ID_ENCODINGENCRYPTION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, encryption), { .n = matroska_track_encoding_encryption } },
  343. { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
  344. { 0 }
  345. };
  346. static EbmlSyntax matroska_track_encodings[] = {
  347. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack, encodings), { .n = matroska_track_encoding } },
  348. { 0 }
  349. };
  350. static EbmlSyntax matroska_track_plane[] = {
  351. { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
  352. { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
  353. { 0 }
  354. };
  355. static EbmlSyntax matroska_track_combine_planes[] = {
  356. { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n = matroska_track_plane} },
  357. { 0 }
  358. };
  359. static EbmlSyntax matroska_track_operation[] = {
  360. { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n = matroska_track_combine_planes} },
  361. { 0 }
  362. };
  363. static EbmlSyntax matroska_track[] = {
  364. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack, num) },
  365. { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack, name) },
  366. { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack, uid) },
  367. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack, type) },
  368. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack, codec_id) },
  369. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack, codec_priv) },
  370. { MATROSKA_ID_CODECDELAY, EBML_UINT, 0, offsetof(MatroskaTrack, codec_delay) },
  371. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack, language), { .s = "eng" } },
  372. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack, default_duration) },
  373. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT, 0, offsetof(MatroskaTrack, time_scale), { .f = 1.0 } },
  374. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack, flag_default), { .u = 1 } },
  375. { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack, flag_forced), { .u = 0 } },
  376. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack, video), { .n = matroska_track_video } },
  377. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack, audio), { .n = matroska_track_audio } },
  378. { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack, operation), { .n = matroska_track_operation } },
  379. { MATROSKA_ID_TRACKCONTENTENCODINGS, EBML_NEST, 0, 0, { .n = matroska_track_encodings } },
  380. { MATROSKA_ID_TRACKMAXBLKADDID, EBML_UINT, 0, offsetof(MatroskaTrack, max_block_additional_id) },
  381. { MATROSKA_ID_SEEKPREROLL, EBML_UINT, 0, offsetof(MatroskaTrack, seek_preroll) },
  382. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  383. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  384. { MATROSKA_ID_CODECNAME, EBML_NONE },
  385. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  386. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  387. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  388. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  389. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  390. { 0 }
  391. };
  392. static EbmlSyntax matroska_tracks[] = {
  393. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
  394. { 0 }
  395. };
  396. static EbmlSyntax matroska_attachment[] = {
  397. { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachment, uid) },
  398. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachment, filename) },
  399. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachment, mime) },
  400. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachment, bin) },
  401. { MATROSKA_ID_FILEDESC, EBML_NONE },
  402. { 0 }
  403. };
  404. static EbmlSyntax matroska_attachments[] = {
  405. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
  406. { 0 }
  407. };
  408. static EbmlSyntax matroska_chapter_display[] = {
  409. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter, title) },
  410. { MATROSKA_ID_CHAPLANG, EBML_NONE },
  411. { 0 }
  412. };
  413. static EbmlSyntax matroska_chapter_entry[] = {
  414. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter, start), { .u = AV_NOPTS_VALUE } },
  415. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter, end), { .u = AV_NOPTS_VALUE } },
  416. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter, uid) },
  417. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, { .n = matroska_chapter_display } },
  418. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  419. { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  420. { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
  421. { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
  422. { 0 }
  423. };
  424. static EbmlSyntax matroska_chapter[] = {
  425. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
  426. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  427. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  428. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  429. { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  430. { 0 }
  431. };
  432. static EbmlSyntax matroska_chapters[] = {
  433. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, { .n = matroska_chapter } },
  434. { 0 }
  435. };
  436. static EbmlSyntax matroska_index_pos[] = {
  437. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos, track) },
  438. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos, pos) },
  439. { MATROSKA_ID_CUERELATIVEPOSITION,EBML_NONE },
  440. { MATROSKA_ID_CUEDURATION, EBML_NONE },
  441. { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
  442. { 0 }
  443. };
  444. static EbmlSyntax matroska_index_entry[] = {
  445. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex, time) },
  446. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex, pos), { .n = matroska_index_pos } },
  447. { 0 }
  448. };
  449. static EbmlSyntax matroska_index[] = {
  450. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext, index), { .n = matroska_index_entry } },
  451. { 0 }
  452. };
  453. static EbmlSyntax matroska_simpletag[] = {
  454. { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag, name) },
  455. { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag, string) },
  456. { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag, lang), { .s = "und" } },
  457. { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag, def) },
  458. { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag, def) },
  459. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag, sub), { .n = matroska_simpletag } },
  460. { 0 }
  461. };
  462. static EbmlSyntax matroska_tagtargets[] = {
  463. { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget, type) },
  464. { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget, typevalue), { .u = 50 } },
  465. { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, trackuid) },
  466. { MATROSKA_ID_TAGTARGETS_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, chapteruid) },
  467. { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, attachuid) },
  468. { 0 }
  469. };
  470. static EbmlSyntax matroska_tag[] = {
  471. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags, tag), { .n = matroska_simpletag } },
  472. { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags, target), { .n = matroska_tagtargets } },
  473. { 0 }
  474. };
  475. static EbmlSyntax matroska_tags[] = {
  476. { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
  477. { 0 }
  478. };
  479. static EbmlSyntax matroska_seekhead_entry[] = {
  480. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead, id) },
  481. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
  482. { 0 }
  483. };
  484. static EbmlSyntax matroska_seekhead[] = {
  485. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
  486. { 0 }
  487. };
  488. static EbmlSyntax matroska_segment[] = {
  489. { MATROSKA_ID_INFO, EBML_LEVEL1, 0, 0, { .n = matroska_info } },
  490. { MATROSKA_ID_TRACKS, EBML_LEVEL1, 0, 0, { .n = matroska_tracks } },
  491. { MATROSKA_ID_ATTACHMENTS, EBML_LEVEL1, 0, 0, { .n = matroska_attachments } },
  492. { MATROSKA_ID_CHAPTERS, EBML_LEVEL1, 0, 0, { .n = matroska_chapters } },
  493. { MATROSKA_ID_CUES, EBML_LEVEL1, 0, 0, { .n = matroska_index } },
  494. { MATROSKA_ID_TAGS, EBML_LEVEL1, 0, 0, { .n = matroska_tags } },
  495. { MATROSKA_ID_SEEKHEAD, EBML_LEVEL1, 0, 0, { .n = matroska_seekhead } },
  496. { MATROSKA_ID_CLUSTER, EBML_STOP },
  497. { 0 }
  498. };
  499. static EbmlSyntax matroska_segments[] = {
  500. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, { .n = matroska_segment } },
  501. { 0 }
  502. };
  503. static EbmlSyntax matroska_blockmore[] = {
  504. { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
  505. { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, offsetof(MatroskaBlock,additional) },
  506. { 0 }
  507. };
  508. static EbmlSyntax matroska_blockadditions[] = {
  509. { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n = matroska_blockmore} },
  510. { 0 }
  511. };
  512. static EbmlSyntax matroska_blockgroup[] = {
  513. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) },
  514. { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, { .n = matroska_blockadditions} },
  515. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) },
  516. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock, duration) },
  517. { MATROSKA_ID_DISCARDPADDING, EBML_SINT, 0, offsetof(MatroskaBlock, discard_padding) },
  518. { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 0, offsetof(MatroskaBlock, reference) },
  519. { MATROSKA_ID_CODECSTATE, EBML_NONE },
  520. { 1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
  521. { 0 }
  522. };
  523. static EbmlSyntax matroska_cluster[] = {
  524. { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
  525. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  526. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  527. { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  528. { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  529. { 0 }
  530. };
  531. static EbmlSyntax matroska_clusters[] = {
  532. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, { .n = matroska_cluster } },
  533. { MATROSKA_ID_INFO, EBML_NONE },
  534. { MATROSKA_ID_CUES, EBML_NONE },
  535. { MATROSKA_ID_TAGS, EBML_NONE },
  536. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  537. { 0 }
  538. };
  539. static EbmlSyntax matroska_cluster_incremental_parsing[] = {
  540. { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
  541. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  542. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  543. { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  544. { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  545. { MATROSKA_ID_INFO, EBML_NONE },
  546. { MATROSKA_ID_CUES, EBML_NONE },
  547. { MATROSKA_ID_TAGS, EBML_NONE },
  548. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  549. { MATROSKA_ID_CLUSTER, EBML_STOP },
  550. { 0 }
  551. };
  552. static EbmlSyntax matroska_cluster_incremental[] = {
  553. { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
  554. { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
  555. { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
  556. { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  557. { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  558. { 0 }
  559. };
  560. static EbmlSyntax matroska_clusters_incremental[] = {
  561. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, { .n = matroska_cluster_incremental } },
  562. { MATROSKA_ID_INFO, EBML_NONE },
  563. { MATROSKA_ID_CUES, EBML_NONE },
  564. { MATROSKA_ID_TAGS, EBML_NONE },
  565. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  566. { 0 }
  567. };
  568. static const char *const matroska_doctypes[] = { "matroska", "webm" };
  569. static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
  570. {
  571. AVIOContext *pb = matroska->ctx->pb;
  572. uint32_t id;
  573. matroska->current_id = 0;
  574. matroska->num_levels = 0;
  575. /* seek to next position to resync from */
  576. if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
  577. goto eof;
  578. id = avio_rb32(pb);
  579. // try to find a toplevel element
  580. while (!avio_feof(pb)) {
  581. if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
  582. id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
  583. id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
  584. id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
  585. matroska->current_id = id;
  586. return 0;
  587. }
  588. id = (id << 8) | avio_r8(pb);
  589. }
  590. eof:
  591. matroska->done = 1;
  592. return AVERROR_EOF;
  593. }
  594. /*
  595. * Return: Whether we reached the end of a level in the hierarchy or not.
  596. */
  597. static int ebml_level_end(MatroskaDemuxContext *matroska)
  598. {
  599. AVIOContext *pb = matroska->ctx->pb;
  600. int64_t pos = avio_tell(pb);
  601. if (matroska->num_levels > 0) {
  602. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  603. if (pos - level->start >= level->length || matroska->current_id) {
  604. matroska->num_levels--;
  605. return 1;
  606. }
  607. }
  608. return 0;
  609. }
  610. /*
  611. * Read: an "EBML number", which is defined as a variable-length
  612. * array of bytes. The first byte indicates the length by giving a
  613. * number of 0-bits followed by a one. The position of the first
  614. * "one" bit inside the first byte indicates the length of this
  615. * number.
  616. * Returns: number of bytes read, < 0 on error
  617. */
  618. static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  619. int max_size, uint64_t *number)
  620. {
  621. int read = 1, n = 1;
  622. uint64_t total = 0;
  623. /* The first byte tells us the length in bytes - avio_r8() can normally
  624. * return 0, but since that's not a valid first ebmlID byte, we can
  625. * use it safely here to catch EOS. */
  626. if (!(total = avio_r8(pb))) {
  627. /* we might encounter EOS here */
  628. if (!avio_feof(pb)) {
  629. int64_t pos = avio_tell(pb);
  630. av_log(matroska->ctx, AV_LOG_ERROR,
  631. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  632. pos, pos);
  633. return pb->error ? pb->error : AVERROR(EIO);
  634. }
  635. return AVERROR_EOF;
  636. }
  637. /* get the length of the EBML number */
  638. read = 8 - ff_log2_tab[total];
  639. if (read > max_size) {
  640. int64_t pos = avio_tell(pb) - 1;
  641. av_log(matroska->ctx, AV_LOG_ERROR,
  642. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  643. (uint8_t) total, pos, pos);
  644. return AVERROR_INVALIDDATA;
  645. }
  646. /* read out length */
  647. total ^= 1 << ff_log2_tab[total];
  648. while (n++ < read)
  649. total = (total << 8) | avio_r8(pb);
  650. *number = total;
  651. return read;
  652. }
  653. /**
  654. * Read a EBML length value.
  655. * This needs special handling for the "unknown length" case which has multiple
  656. * encodings.
  657. */
  658. static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  659. uint64_t *number)
  660. {
  661. int res = ebml_read_num(matroska, pb, 8, number);
  662. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  663. *number = 0xffffffffffffffULL;
  664. return res;
  665. }
  666. /*
  667. * Read the next element as an unsigned int.
  668. * 0 is success, < 0 is failure.
  669. */
  670. static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  671. {
  672. int n = 0;
  673. if (size > 8)
  674. return AVERROR_INVALIDDATA;
  675. /* big-endian ordering; build up number */
  676. *num = 0;
  677. while (n++ < size)
  678. *num = (*num << 8) | avio_r8(pb);
  679. return 0;
  680. }
  681. /*
  682. * Read the next element as a signed int.
  683. * 0 is success, < 0 is failure.
  684. */
  685. static int ebml_read_sint(AVIOContext *pb, int size, int64_t *num)
  686. {
  687. int n = 1;
  688. if (size > 8)
  689. return AVERROR_INVALIDDATA;
  690. if (size == 0) {
  691. *num = 0;
  692. } else {
  693. *num = sign_extend(avio_r8(pb), 8);
  694. /* big-endian ordering; build up number */
  695. while (n++ < size)
  696. *num = (*num << 8) | avio_r8(pb);
  697. }
  698. return 0;
  699. }
  700. /*
  701. * Read the next element as a float.
  702. * 0 is success, < 0 is failure.
  703. */
  704. static int ebml_read_float(AVIOContext *pb, int size, double *num)
  705. {
  706. if (size == 0)
  707. *num = 0;
  708. else if (size == 4)
  709. *num = av_int2float(avio_rb32(pb));
  710. else if (size == 8)
  711. *num = av_int2double(avio_rb64(pb));
  712. else
  713. return AVERROR_INVALIDDATA;
  714. return 0;
  715. }
  716. /*
  717. * Read the next element as an ASCII string.
  718. * 0 is success, < 0 is failure.
  719. */
  720. static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  721. {
  722. char *res;
  723. /* EBML strings are usually not 0-terminated, so we allocate one
  724. * byte more, read the string and NULL-terminate it ourselves. */
  725. if (!(res = av_malloc(size + 1)))
  726. return AVERROR(ENOMEM);
  727. if (avio_read(pb, (uint8_t *) res, size) != size) {
  728. av_free(res);
  729. return AVERROR(EIO);
  730. }
  731. (res)[size] = '\0';
  732. av_free(*str);
  733. *str = res;
  734. return 0;
  735. }
  736. /*
  737. * Read the next element as binary data.
  738. * 0 is success, < 0 is failure.
  739. */
  740. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  741. {
  742. av_fast_padded_malloc(&bin->data, &bin->size, length);
  743. if (!bin->data)
  744. return AVERROR(ENOMEM);
  745. bin->size = length;
  746. bin->pos = avio_tell(pb);
  747. if (avio_read(pb, bin->data, length) != length) {
  748. av_freep(&bin->data);
  749. bin->size = 0;
  750. return AVERROR(EIO);
  751. }
  752. return 0;
  753. }
  754. /*
  755. * Read the next element, but only the header. The contents
  756. * are supposed to be sub-elements which can be read separately.
  757. * 0 is success, < 0 is failure.
  758. */
  759. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  760. {
  761. AVIOContext *pb = matroska->ctx->pb;
  762. MatroskaLevel *level;
  763. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  764. av_log(matroska->ctx, AV_LOG_ERROR,
  765. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  766. return AVERROR(ENOSYS);
  767. }
  768. level = &matroska->levels[matroska->num_levels++];
  769. level->start = avio_tell(pb);
  770. level->length = length;
  771. return 0;
  772. }
  773. /*
  774. * Read signed/unsigned "EBML" numbers.
  775. * Return: number of bytes processed, < 0 on error
  776. */
  777. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  778. uint8_t *data, uint32_t size, uint64_t *num)
  779. {
  780. AVIOContext pb;
  781. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  782. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  783. }
  784. /*
  785. * Same as above, but signed.
  786. */
  787. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  788. uint8_t *data, uint32_t size, int64_t *num)
  789. {
  790. uint64_t unum;
  791. int res;
  792. /* read as unsigned number first */
  793. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  794. return res;
  795. /* make signed (weird way) */
  796. *num = unum - ((1LL << (7 * res - 1)) - 1);
  797. return res;
  798. }
  799. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  800. EbmlSyntax *syntax, void *data);
  801. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  802. uint32_t id, void *data)
  803. {
  804. int i;
  805. for (i = 0; syntax[i].id; i++)
  806. if (id == syntax[i].id)
  807. break;
  808. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  809. matroska->num_levels > 0 &&
  810. matroska->levels[matroska->num_levels - 1].length == 0xffffffffffffff)
  811. return 0; // we reached the end of an unknown size cluster
  812. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
  813. av_log(matroska->ctx, AV_LOG_DEBUG, "Unknown entry 0x%"PRIX32"\n", id);
  814. }
  815. return ebml_parse_elem(matroska, &syntax[i], data);
  816. }
  817. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  818. void *data)
  819. {
  820. if (!matroska->current_id) {
  821. uint64_t id;
  822. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  823. if (res < 0)
  824. return res;
  825. matroska->current_id = id | 1 << 7 * res;
  826. }
  827. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  828. }
  829. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  830. void *data)
  831. {
  832. int i, res = 0;
  833. for (i = 0; syntax[i].id; i++)
  834. switch (syntax[i].type) {
  835. case EBML_UINT:
  836. *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u;
  837. break;
  838. case EBML_FLOAT:
  839. *(double *) ((char *) data + syntax[i].data_offset) = syntax[i].def.f;
  840. break;
  841. case EBML_STR:
  842. case EBML_UTF8:
  843. // the default may be NULL
  844. if (syntax[i].def.s) {
  845. uint8_t **dst = (uint8_t **) ((uint8_t *) data + syntax[i].data_offset);
  846. *dst = av_strdup(syntax[i].def.s);
  847. if (!*dst)
  848. return AVERROR(ENOMEM);
  849. }
  850. break;
  851. }
  852. while (!res && !ebml_level_end(matroska))
  853. res = ebml_parse(matroska, syntax, data);
  854. return res;
  855. }
  856. /*
  857. * Allocate and return the entry for the level1 element with the given ID. If
  858. * an entry already exists, return the existing entry.
  859. */
  860. static MatroskaLevel1Element *matroska_find_level1_elem(MatroskaDemuxContext *matroska,
  861. uint32_t id)
  862. {
  863. int i;
  864. MatroskaLevel1Element *elem;
  865. // Some files link to all clusters; useless.
  866. if (id == MATROSKA_ID_CLUSTER)
  867. return NULL;
  868. // There can be multiple seekheads.
  869. if (id != MATROSKA_ID_SEEKHEAD) {
  870. for (i = 0; i < matroska->num_level1_elems; i++) {
  871. if (matroska->level1_elems[i].id == id)
  872. return &matroska->level1_elems[i];
  873. }
  874. }
  875. // Only a completely broken file would have more elements.
  876. // It also provides a low-effort way to escape from circular seekheads
  877. // (every iteration will add a level1 entry).
  878. if (matroska->num_level1_elems >= FF_ARRAY_ELEMS(matroska->level1_elems)) {
  879. av_log(matroska->ctx, AV_LOG_ERROR, "Too many level1 elements or circular seekheads.\n");
  880. return NULL;
  881. }
  882. elem = &matroska->level1_elems[matroska->num_level1_elems++];
  883. *elem = (MatroskaLevel1Element){.id = id};
  884. return elem;
  885. }
  886. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  887. EbmlSyntax *syntax, void *data)
  888. {
  889. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  890. [EBML_UINT] = 8,
  891. [EBML_FLOAT] = 8,
  892. // max. 16 MB for strings
  893. [EBML_STR] = 0x1000000,
  894. [EBML_UTF8] = 0x1000000,
  895. // max. 256 MB for binary data
  896. [EBML_BIN] = 0x10000000,
  897. // no limits for anything else
  898. };
  899. AVIOContext *pb = matroska->ctx->pb;
  900. uint32_t id = syntax->id;
  901. uint64_t length;
  902. int res;
  903. void *newelem;
  904. MatroskaLevel1Element *level1_elem;
  905. data = (char *) data + syntax->data_offset;
  906. if (syntax->list_elem_size) {
  907. EbmlList *list = data;
  908. newelem = av_realloc_array(list->elem, list->nb_elem + 1, syntax->list_elem_size);
  909. if (!newelem)
  910. return AVERROR(ENOMEM);
  911. list->elem = newelem;
  912. data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
  913. memset(data, 0, syntax->list_elem_size);
  914. list->nb_elem++;
  915. }
  916. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  917. matroska->current_id = 0;
  918. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  919. return res;
  920. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  921. av_log(matroska->ctx, AV_LOG_ERROR,
  922. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  923. length, max_lengths[syntax->type], syntax->type);
  924. return AVERROR_INVALIDDATA;
  925. }
  926. }
  927. switch (syntax->type) {
  928. case EBML_UINT:
  929. res = ebml_read_uint(pb, length, data);
  930. break;
  931. case EBML_SINT:
  932. res = ebml_read_sint(pb, length, data);
  933. break;
  934. case EBML_FLOAT:
  935. res = ebml_read_float(pb, length, data);
  936. break;
  937. case EBML_STR:
  938. case EBML_UTF8:
  939. res = ebml_read_ascii(pb, length, data);
  940. break;
  941. case EBML_BIN:
  942. res = ebml_read_binary(pb, length, data);
  943. break;
  944. case EBML_LEVEL1:
  945. case EBML_NEST:
  946. if ((res = ebml_read_master(matroska, length)) < 0)
  947. return res;
  948. if (id == MATROSKA_ID_SEGMENT)
  949. matroska->segment_start = avio_tell(matroska->ctx->pb);
  950. if (id == MATROSKA_ID_CUES)
  951. matroska->cues_parsing_deferred = 0;
  952. if (syntax->type == EBML_LEVEL1 &&
  953. (level1_elem = matroska_find_level1_elem(matroska, syntax->id))) {
  954. if (level1_elem->parsed)
  955. av_log(matroska->ctx, AV_LOG_ERROR, "Duplicate element\n");
  956. level1_elem->parsed = 1;
  957. }
  958. return ebml_parse_nest(matroska, syntax->def.n, data);
  959. case EBML_PASS:
  960. return ebml_parse_id(matroska, syntax->def.n, id, data);
  961. case EBML_STOP:
  962. return 1;
  963. default:
  964. if (ffio_limit(pb, length) != length)
  965. return AVERROR(EIO);
  966. return avio_skip(pb, length) < 0 ? AVERROR(EIO) : 0;
  967. }
  968. if (res == AVERROR_INVALIDDATA)
  969. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  970. else if (res == AVERROR(EIO))
  971. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  972. return res;
  973. }
  974. static void ebml_free(EbmlSyntax *syntax, void *data)
  975. {
  976. int i, j;
  977. for (i = 0; syntax[i].id; i++) {
  978. void *data_off = (char *) data + syntax[i].data_offset;
  979. switch (syntax[i].type) {
  980. case EBML_STR:
  981. case EBML_UTF8:
  982. av_freep(data_off);
  983. break;
  984. case EBML_BIN:
  985. av_freep(&((EbmlBin *) data_off)->data);
  986. break;
  987. case EBML_LEVEL1:
  988. case EBML_NEST:
  989. if (syntax[i].list_elem_size) {
  990. EbmlList *list = data_off;
  991. char *ptr = list->elem;
  992. for (j = 0; j < list->nb_elem;
  993. j++, ptr += syntax[i].list_elem_size)
  994. ebml_free(syntax[i].def.n, ptr);
  995. av_freep(&list->elem);
  996. } else
  997. ebml_free(syntax[i].def.n, data_off);
  998. default:
  999. break;
  1000. }
  1001. }
  1002. }
  1003. /*
  1004. * Autodetecting...
  1005. */
  1006. static int matroska_probe(AVProbeData *p)
  1007. {
  1008. uint64_t total = 0;
  1009. int len_mask = 0x80, size = 1, n = 1, i;
  1010. /* EBML header? */
  1011. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  1012. return 0;
  1013. /* length of header */
  1014. total = p->buf[4];
  1015. while (size <= 8 && !(total & len_mask)) {
  1016. size++;
  1017. len_mask >>= 1;
  1018. }
  1019. if (size > 8)
  1020. return 0;
  1021. total &= (len_mask - 1);
  1022. while (n < size)
  1023. total = (total << 8) | p->buf[4 + n++];
  1024. /* Does the probe data contain the whole header? */
  1025. if (p->buf_size < 4 + size + total)
  1026. return 0;
  1027. /* The header should contain a known document type. For now,
  1028. * we don't parse the whole header but simply check for the
  1029. * availability of that array of characters inside the header.
  1030. * Not fully fool-proof, but good enough. */
  1031. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  1032. int probelen = strlen(matroska_doctypes[i]);
  1033. if (total < probelen)
  1034. continue;
  1035. for (n = 4 + size; n <= 4 + size + total - probelen; n++)
  1036. if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
  1037. return AVPROBE_SCORE_MAX;
  1038. }
  1039. // probably valid EBML header but no recognized doctype
  1040. return AVPROBE_SCORE_EXTENSION;
  1041. }
  1042. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  1043. int num)
  1044. {
  1045. MatroskaTrack *tracks = matroska->tracks.elem;
  1046. int i;
  1047. for (i = 0; i < matroska->tracks.nb_elem; i++)
  1048. if (tracks[i].num == num)
  1049. return &tracks[i];
  1050. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  1051. return NULL;
  1052. }
  1053. static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
  1054. MatroskaTrack *track)
  1055. {
  1056. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1057. uint8_t *data = *buf;
  1058. int isize = *buf_size;
  1059. uint8_t *pkt_data = NULL;
  1060. uint8_t av_unused *newpktdata;
  1061. int pkt_size = isize;
  1062. int result = 0;
  1063. int olen;
  1064. if (pkt_size >= 10000000U)
  1065. return AVERROR_INVALIDDATA;
  1066. switch (encodings[0].compression.algo) {
  1067. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  1068. {
  1069. int header_size = encodings[0].compression.settings.size;
  1070. uint8_t *header = encodings[0].compression.settings.data;
  1071. if (header_size && !header) {
  1072. av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
  1073. return -1;
  1074. }
  1075. if (!header_size)
  1076. return 0;
  1077. pkt_size = isize + header_size;
  1078. pkt_data = av_malloc(pkt_size);
  1079. if (!pkt_data)
  1080. return AVERROR(ENOMEM);
  1081. memcpy(pkt_data, header, header_size);
  1082. memcpy(pkt_data + header_size, data, isize);
  1083. break;
  1084. }
  1085. #if CONFIG_LZO
  1086. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  1087. do {
  1088. olen = pkt_size *= 3;
  1089. newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
  1090. if (!newpktdata) {
  1091. result = AVERROR(ENOMEM);
  1092. goto failed;
  1093. }
  1094. pkt_data = newpktdata;
  1095. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  1096. } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
  1097. if (result) {
  1098. result = AVERROR_INVALIDDATA;
  1099. goto failed;
  1100. }
  1101. pkt_size -= olen;
  1102. break;
  1103. #endif
  1104. #if CONFIG_ZLIB
  1105. case MATROSKA_TRACK_ENCODING_COMP_ZLIB:
  1106. {
  1107. z_stream zstream = { 0 };
  1108. if (inflateInit(&zstream) != Z_OK)
  1109. return -1;
  1110. zstream.next_in = data;
  1111. zstream.avail_in = isize;
  1112. do {
  1113. pkt_size *= 3;
  1114. newpktdata = av_realloc(pkt_data, pkt_size);
  1115. if (!newpktdata) {
  1116. inflateEnd(&zstream);
  1117. goto failed;
  1118. }
  1119. pkt_data = newpktdata;
  1120. zstream.avail_out = pkt_size - zstream.total_out;
  1121. zstream.next_out = pkt_data + zstream.total_out;
  1122. if (pkt_data) {
  1123. result = inflate(&zstream, Z_NO_FLUSH);
  1124. } else
  1125. result = Z_MEM_ERROR;
  1126. } while (result == Z_OK && pkt_size < 10000000);
  1127. pkt_size = zstream.total_out;
  1128. inflateEnd(&zstream);
  1129. if (result != Z_STREAM_END) {
  1130. if (result == Z_MEM_ERROR)
  1131. result = AVERROR(ENOMEM);
  1132. else
  1133. result = AVERROR_INVALIDDATA;
  1134. goto failed;
  1135. }
  1136. break;
  1137. }
  1138. #endif
  1139. #if CONFIG_BZLIB
  1140. case MATROSKA_TRACK_ENCODING_COMP_BZLIB:
  1141. {
  1142. bz_stream bzstream = { 0 };
  1143. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  1144. return -1;
  1145. bzstream.next_in = data;
  1146. bzstream.avail_in = isize;
  1147. do {
  1148. pkt_size *= 3;
  1149. newpktdata = av_realloc(pkt_data, pkt_size);
  1150. if (!newpktdata) {
  1151. BZ2_bzDecompressEnd(&bzstream);
  1152. goto failed;
  1153. }
  1154. pkt_data = newpktdata;
  1155. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  1156. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  1157. if (pkt_data) {
  1158. result = BZ2_bzDecompress(&bzstream);
  1159. } else
  1160. result = BZ_MEM_ERROR;
  1161. } while (result == BZ_OK && pkt_size < 10000000);
  1162. pkt_size = bzstream.total_out_lo32;
  1163. BZ2_bzDecompressEnd(&bzstream);
  1164. if (result != BZ_STREAM_END) {
  1165. if (result == BZ_MEM_ERROR)
  1166. result = AVERROR(ENOMEM);
  1167. else
  1168. result = AVERROR_INVALIDDATA;
  1169. goto failed;
  1170. }
  1171. break;
  1172. }
  1173. #endif
  1174. default:
  1175. return AVERROR_INVALIDDATA;
  1176. }
  1177. *buf = pkt_data;
  1178. *buf_size = pkt_size;
  1179. return 0;
  1180. failed:
  1181. av_free(pkt_data);
  1182. return result;
  1183. }
  1184. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  1185. AVDictionary **metadata, char *prefix)
  1186. {
  1187. MatroskaTag *tags = list->elem;
  1188. char key[1024];
  1189. int i;
  1190. for (i = 0; i < list->nb_elem; i++) {
  1191. const char *lang = tags[i].lang &&
  1192. strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  1193. if (!tags[i].name) {
  1194. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1195. continue;
  1196. }
  1197. if (prefix)
  1198. snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1199. else
  1200. av_strlcpy(key, tags[i].name, sizeof(key));
  1201. if (tags[i].def || !lang) {
  1202. av_dict_set(metadata, key, tags[i].string, 0);
  1203. if (tags[i].sub.nb_elem)
  1204. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1205. }
  1206. if (lang) {
  1207. av_strlcat(key, "-", sizeof(key));
  1208. av_strlcat(key, lang, sizeof(key));
  1209. av_dict_set(metadata, key, tags[i].string, 0);
  1210. if (tags[i].sub.nb_elem)
  1211. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1212. }
  1213. }
  1214. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1215. }
  1216. static void matroska_convert_tags(AVFormatContext *s)
  1217. {
  1218. MatroskaDemuxContext *matroska = s->priv_data;
  1219. MatroskaTags *tags = matroska->tags.elem;
  1220. int i, j;
  1221. for (i = 0; i < matroska->tags.nb_elem; i++) {
  1222. if (tags[i].target.attachuid) {
  1223. MatroskaAttachment *attachment = matroska->attachments.elem;
  1224. for (j = 0; j < matroska->attachments.nb_elem; j++)
  1225. if (attachment[j].uid == tags[i].target.attachuid &&
  1226. attachment[j].stream)
  1227. matroska_convert_tag(s, &tags[i].tag,
  1228. &attachment[j].stream->metadata, NULL);
  1229. } else if (tags[i].target.chapteruid) {
  1230. MatroskaChapter *chapter = matroska->chapters.elem;
  1231. for (j = 0; j < matroska->chapters.nb_elem; j++)
  1232. if (chapter[j].uid == tags[i].target.chapteruid &&
  1233. chapter[j].chapter)
  1234. matroska_convert_tag(s, &tags[i].tag,
  1235. &chapter[j].chapter->metadata, NULL);
  1236. } else if (tags[i].target.trackuid) {
  1237. MatroskaTrack *track = matroska->tracks.elem;
  1238. for (j = 0; j < matroska->tracks.nb_elem; j++)
  1239. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1240. matroska_convert_tag(s, &tags[i].tag,
  1241. &track[j].stream->metadata, NULL);
  1242. } else {
  1243. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1244. tags[i].target.type);
  1245. }
  1246. }
  1247. }
  1248. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
  1249. uint64_t pos)
  1250. {
  1251. uint32_t level_up = matroska->level_up;
  1252. uint32_t saved_id = matroska->current_id;
  1253. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1254. MatroskaLevel level;
  1255. int64_t offset;
  1256. int ret = 0;
  1257. /* seek */
  1258. offset = pos + matroska->segment_start;
  1259. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1260. /* We don't want to lose our seekhead level, so we add
  1261. * a dummy. This is a crude hack. */
  1262. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1263. av_log(matroska->ctx, AV_LOG_INFO,
  1264. "Max EBML element depth (%d) reached, "
  1265. "cannot parse further.\n", EBML_MAX_DEPTH);
  1266. ret = AVERROR_INVALIDDATA;
  1267. } else {
  1268. level.start = 0;
  1269. level.length = (uint64_t) -1;
  1270. matroska->levels[matroska->num_levels] = level;
  1271. matroska->num_levels++;
  1272. matroska->current_id = 0;
  1273. ret = ebml_parse(matroska, matroska_segment, matroska);
  1274. /* remove dummy level */
  1275. while (matroska->num_levels) {
  1276. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1277. if (length == (uint64_t) -1)
  1278. break;
  1279. }
  1280. }
  1281. }
  1282. /* seek back */
  1283. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1284. matroska->level_up = level_up;
  1285. matroska->current_id = saved_id;
  1286. return ret;
  1287. }
  1288. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1289. {
  1290. EbmlList *seekhead_list = &matroska->seekhead;
  1291. int i;
  1292. // we should not do any seeking in the streaming case
  1293. if (!matroska->ctx->pb->seekable)
  1294. return;
  1295. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1296. MatroskaSeekhead *seekheads = seekhead_list->elem;
  1297. uint32_t id = seekheads[i].id;
  1298. uint64_t pos = seekheads[i].pos;
  1299. MatroskaLevel1Element *elem = matroska_find_level1_elem(matroska, id);
  1300. if (!elem || elem->parsed)
  1301. continue;
  1302. elem->pos = pos;
  1303. // defer cues parsing until we actually need cue data.
  1304. if (id == MATROSKA_ID_CUES)
  1305. continue;
  1306. if (matroska_parse_seekhead_entry(matroska, pos) < 0) {
  1307. // mark index as broken
  1308. matroska->cues_parsing_deferred = -1;
  1309. break;
  1310. }
  1311. elem->parsed = 1;
  1312. }
  1313. }
  1314. static void matroska_add_index_entries(MatroskaDemuxContext *matroska)
  1315. {
  1316. EbmlList *index_list;
  1317. MatroskaIndex *index;
  1318. int index_scale = 1;
  1319. int i, j;
  1320. if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
  1321. return;
  1322. index_list = &matroska->index;
  1323. index = index_list->elem;
  1324. if (index_list->nb_elem &&
  1325. index[0].time > 1E14 / matroska->time_scale) {
  1326. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1327. index_scale = matroska->time_scale;
  1328. }
  1329. for (i = 0; i < index_list->nb_elem; i++) {
  1330. EbmlList *pos_list = &index[i].pos;
  1331. MatroskaIndexPos *pos = pos_list->elem;
  1332. for (j = 0; j < pos_list->nb_elem; j++) {
  1333. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1334. pos[j].track);
  1335. if (track && track->stream)
  1336. av_add_index_entry(track->stream,
  1337. pos[j].pos + matroska->segment_start,
  1338. index[i].time / index_scale, 0, 0,
  1339. AVINDEX_KEYFRAME);
  1340. }
  1341. }
  1342. }
  1343. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1344. int i;
  1345. if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
  1346. return;
  1347. for (i = 0; i < matroska->num_level1_elems; i++) {
  1348. MatroskaLevel1Element *elem = &matroska->level1_elems[i];
  1349. if (elem->id == MATROSKA_ID_CUES && !elem->parsed) {
  1350. if (matroska_parse_seekhead_entry(matroska, elem->pos) < 0)
  1351. matroska->cues_parsing_deferred = -1;
  1352. elem->parsed = 1;
  1353. break;
  1354. }
  1355. }
  1356. matroska_add_index_entries(matroska);
  1357. }
  1358. static int matroska_aac_profile(char *codec_id)
  1359. {
  1360. static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1361. int profile;
  1362. for (profile = 0; profile < FF_ARRAY_ELEMS(aac_profiles); profile++)
  1363. if (strstr(codec_id, aac_profiles[profile]))
  1364. break;
  1365. return profile + 1;
  1366. }
  1367. static int matroska_aac_sri(int samplerate)
  1368. {
  1369. int sri;
  1370. for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1371. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1372. break;
  1373. return sri;
  1374. }
  1375. static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
  1376. {
  1377. char buffer[32];
  1378. /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
  1379. time_t creation_time = date_utc / 1000000000 + 978307200;
  1380. struct tm tmpbuf, *ptm = gmtime_r(&creation_time, &tmpbuf);
  1381. if (!ptm) return;
  1382. if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
  1383. av_dict_set(metadata, "creation_time", buffer, 0);
  1384. }
  1385. static int matroska_parse_flac(AVFormatContext *s,
  1386. MatroskaTrack *track,
  1387. int *offset)
  1388. {
  1389. AVStream *st = track->stream;
  1390. uint8_t *p = track->codec_priv.data;
  1391. int size = track->codec_priv.size;
  1392. if (size < 8 + FLAC_STREAMINFO_SIZE || p[4] & 0x7f) {
  1393. av_log(s, AV_LOG_WARNING, "Invalid FLAC private data\n");
  1394. track->codec_priv.size = 0;
  1395. return 0;
  1396. }
  1397. *offset = 8;
  1398. track->codec_priv.size = 8 + FLAC_STREAMINFO_SIZE;
  1399. p += track->codec_priv.size;
  1400. size -= track->codec_priv.size;
  1401. /* parse the remaining metadata blocks if present */
  1402. while (size >= 4) {
  1403. int block_last, block_type, block_size;
  1404. flac_parse_block_header(p, &block_last, &block_type, &block_size);
  1405. p += 4;
  1406. size -= 4;
  1407. if (block_size > size)
  1408. return 0;
  1409. /* check for the channel mask */
  1410. if (block_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
  1411. AVDictionary *dict = NULL;
  1412. AVDictionaryEntry *chmask;
  1413. ff_vorbis_comment(s, &dict, p, block_size, 0);
  1414. chmask = av_dict_get(dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
  1415. if (chmask) {
  1416. uint64_t mask = strtol(chmask->value, NULL, 0);
  1417. if (!mask || mask & ~0x3ffffULL) {
  1418. av_log(s, AV_LOG_WARNING,
  1419. "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
  1420. } else
  1421. st->codec->channel_layout = mask;
  1422. }
  1423. av_dict_free(&dict);
  1424. }
  1425. p += block_size;
  1426. size -= block_size;
  1427. }
  1428. return 0;
  1429. }
  1430. static int matroska_parse_tracks(AVFormatContext *s)
  1431. {
  1432. MatroskaDemuxContext *matroska = s->priv_data;
  1433. MatroskaTrack *tracks = matroska->tracks.elem;
  1434. AVStream *st;
  1435. int i, j, ret;
  1436. int k;
  1437. for (i = 0; i < matroska->tracks.nb_elem; i++) {
  1438. MatroskaTrack *track = &tracks[i];
  1439. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1440. EbmlList *encodings_list = &track->encodings;
  1441. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1442. uint8_t *extradata = NULL;
  1443. int extradata_size = 0;
  1444. int extradata_offset = 0;
  1445. uint32_t fourcc = 0;
  1446. AVIOContext b;
  1447. char* key_id_base64 = NULL;
  1448. int bit_depth = -1;
  1449. /* Apply some sanity checks. */
  1450. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1451. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1452. track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
  1453. track->type != MATROSKA_TRACK_TYPE_METADATA) {
  1454. av_log(matroska->ctx, AV_LOG_INFO,
  1455. "Unknown or unsupported track type %"PRIu64"\n",
  1456. track->type);
  1457. continue;
  1458. }
  1459. if (!track->codec_id)
  1460. continue;
  1461. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1462. if (!track->default_duration && track->video.frame_rate > 0)
  1463. track->default_duration = 1000000000 / track->video.frame_rate;
  1464. if (track->video.display_width == -1)
  1465. track->video.display_width = track->video.pixel_width;
  1466. if (track->video.display_height == -1)
  1467. track->video.display_height = track->video.pixel_height;
  1468. if (track->video.color_space.size == 4)
  1469. fourcc = AV_RL32(track->video.color_space.data);
  1470. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1471. if (!track->audio.out_samplerate)
  1472. track->audio.out_samplerate = track->audio.samplerate;
  1473. }
  1474. if (encodings_list->nb_elem > 1) {
  1475. av_log(matroska->ctx, AV_LOG_ERROR,
  1476. "Multiple combined encodings not supported");
  1477. } else if (encodings_list->nb_elem == 1) {
  1478. if (encodings[0].type) {
  1479. if (encodings[0].encryption.key_id.size > 0) {
  1480. /* Save the encryption key id to be stored later as a
  1481. metadata tag. */
  1482. const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
  1483. key_id_base64 = av_malloc(b64_size);
  1484. if (key_id_base64 == NULL)
  1485. return AVERROR(ENOMEM);
  1486. av_base64_encode(key_id_base64, b64_size,
  1487. encodings[0].encryption.key_id.data,
  1488. encodings[0].encryption.key_id.size);
  1489. } else {
  1490. encodings[0].scope = 0;
  1491. av_log(matroska->ctx, AV_LOG_ERROR,
  1492. "Unsupported encoding type");
  1493. }
  1494. } else if (
  1495. #if CONFIG_ZLIB
  1496. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1497. #endif
  1498. #if CONFIG_BZLIB
  1499. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1500. #endif
  1501. #if CONFIG_LZO
  1502. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1503. #endif
  1504. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
  1505. encodings[0].scope = 0;
  1506. av_log(matroska->ctx, AV_LOG_ERROR,
  1507. "Unsupported encoding type");
  1508. } else if (track->codec_priv.size && encodings[0].scope & 2) {
  1509. uint8_t *codec_priv = track->codec_priv.data;
  1510. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1511. &track->codec_priv.size,
  1512. track);
  1513. if (ret < 0) {
  1514. track->codec_priv.data = NULL;
  1515. track->codec_priv.size = 0;
  1516. av_log(matroska->ctx, AV_LOG_ERROR,
  1517. "Failed to decode codec private data\n");
  1518. }
  1519. if (codec_priv != track->codec_priv.data)
  1520. av_free(codec_priv);
  1521. }
  1522. }
  1523. for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
  1524. if (!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1525. strlen(ff_mkv_codec_tags[j].str))) {
  1526. codec_id = ff_mkv_codec_tags[j].id;
  1527. break;
  1528. }
  1529. }
  1530. st = track->stream = avformat_new_stream(s, NULL);
  1531. if (!st) {
  1532. av_free(key_id_base64);
  1533. return AVERROR(ENOMEM);
  1534. }
  1535. if (key_id_base64) {
  1536. /* export encryption key id as base64 metadata tag */
  1537. av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
  1538. av_freep(&key_id_base64);
  1539. }
  1540. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
  1541. track->codec_priv.size >= 40 &&
  1542. track->codec_priv.data) {
  1543. track->ms_compat = 1;
  1544. bit_depth = AV_RL16(track->codec_priv.data + 14);
  1545. fourcc = AV_RL32(track->codec_priv.data + 16);
  1546. codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  1547. fourcc);
  1548. if (!codec_id)
  1549. codec_id = ff_codec_get_id(ff_codec_movvideo_tags,
  1550. fourcc);
  1551. extradata_offset = 40;
  1552. } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
  1553. track->codec_priv.size >= 14 &&
  1554. track->codec_priv.data) {
  1555. int ret;
  1556. ffio_init_context(&b, track->codec_priv.data,
  1557. track->codec_priv.size,
  1558. 0, NULL, NULL, NULL, NULL);
  1559. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size, 0);
  1560. if (ret < 0)
  1561. return ret;
  1562. codec_id = st->codec->codec_id;
  1563. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1564. } else if (!strcmp(track->codec_id, "A_QUICKTIME")
  1565. && (track->codec_priv.size >= 86)
  1566. && (track->codec_priv.data)) {
  1567. fourcc = AV_RL32(track->codec_priv.data + 4);
  1568. codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
  1569. if (ff_codec_get_id(ff_codec_movaudio_tags, AV_RL32(track->codec_priv.data))) {
  1570. fourcc = AV_RL32(track->codec_priv.data);
  1571. codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
  1572. }
  1573. } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
  1574. (track->codec_priv.size >= 21) &&
  1575. (track->codec_priv.data)) {
  1576. fourcc = AV_RL32(track->codec_priv.data + 4);
  1577. codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
  1578. if (ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(track->codec_priv.data))) {
  1579. fourcc = AV_RL32(track->codec_priv.data);
  1580. codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
  1581. }
  1582. if (codec_id == AV_CODEC_ID_NONE && AV_RL32(track->codec_priv.data+4) == AV_RL32("SMI "))
  1583. codec_id = AV_CODEC_ID_SVQ3;
  1584. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1585. switch (track->audio.bitdepth) {
  1586. case 8:
  1587. codec_id = AV_CODEC_ID_PCM_U8;
  1588. break;
  1589. case 24:
  1590. codec_id = AV_CODEC_ID_PCM_S24BE;
  1591. break;
  1592. case 32:
  1593. codec_id = AV_CODEC_ID_PCM_S32BE;
  1594. break;
  1595. }
  1596. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1597. switch (track->audio.bitdepth) {
  1598. case 8:
  1599. codec_id = AV_CODEC_ID_PCM_U8;
  1600. break;
  1601. case 24:
  1602. codec_id = AV_CODEC_ID_PCM_S24LE;
  1603. break;
  1604. case 32:
  1605. codec_id = AV_CODEC_ID_PCM_S32LE;
  1606. break;
  1607. }
  1608. } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
  1609. track->audio.bitdepth == 64) {
  1610. codec_id = AV_CODEC_ID_PCM_F64LE;
  1611. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1612. int profile = matroska_aac_profile(track->codec_id);
  1613. int sri = matroska_aac_sri(track->audio.samplerate);
  1614. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1615. if (!extradata)
  1616. return AVERROR(ENOMEM);
  1617. extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
  1618. extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
  1619. if (strstr(track->codec_id, "SBR")) {
  1620. sri = matroska_aac_sri(track->audio.out_samplerate);
  1621. extradata[2] = 0x56;
  1622. extradata[3] = 0xE5;
  1623. extradata[4] = 0x80 | (sri << 3);
  1624. extradata_size = 5;
  1625. } else
  1626. extradata_size = 2;
  1627. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - FF_INPUT_BUFFER_PADDING_SIZE) {
  1628. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1629. * Create the "atom size", "tag", and "tag version" fields the
  1630. * decoder expects manually. */
  1631. extradata_size = 12 + track->codec_priv.size;
  1632. extradata = av_mallocz(extradata_size +
  1633. FF_INPUT_BUFFER_PADDING_SIZE);
  1634. if (!extradata)
  1635. return AVERROR(ENOMEM);
  1636. AV_WB32(extradata, extradata_size);
  1637. memcpy(&extradata[4], "alac", 4);
  1638. AV_WB32(&extradata[8], 0);
  1639. memcpy(&extradata[12], track->codec_priv.data,
  1640. track->codec_priv.size);
  1641. } else if (codec_id == AV_CODEC_ID_TTA) {
  1642. extradata_size = 30;
  1643. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1644. if (!extradata)
  1645. return AVERROR(ENOMEM);
  1646. ffio_init_context(&b, extradata, extradata_size, 1,
  1647. NULL, NULL, NULL, NULL);
  1648. avio_write(&b, "TTA1", 4);
  1649. avio_wl16(&b, 1);
  1650. avio_wl16(&b, track->audio.channels);
  1651. avio_wl16(&b, track->audio.bitdepth);
  1652. if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
  1653. return AVERROR_INVALIDDATA;
  1654. avio_wl32(&b, track->audio.out_samplerate);
  1655. avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale),
  1656. track->audio.out_samplerate,
  1657. AV_TIME_BASE * 1000));
  1658. } else if (codec_id == AV_CODEC_ID_RV10 ||
  1659. codec_id == AV_CODEC_ID_RV20 ||
  1660. codec_id == AV_CODEC_ID_RV30 ||
  1661. codec_id == AV_CODEC_ID_RV40) {
  1662. extradata_offset = 26;
  1663. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1664. track->audio.out_samplerate = 8000;
  1665. track->audio.channels = 1;
  1666. } else if ((codec_id == AV_CODEC_ID_RA_288 ||
  1667. codec_id == AV_CODEC_ID_COOK ||
  1668. codec_id == AV_CODEC_ID_ATRAC3 ||
  1669. codec_id == AV_CODEC_ID_SIPR)
  1670. && track->codec_priv.data) {
  1671. int flavor;
  1672. ffio_init_context(&b, track->codec_priv.data,
  1673. track->codec_priv.size,
  1674. 0, NULL, NULL, NULL, NULL);
  1675. avio_skip(&b, 22);
  1676. flavor = avio_rb16(&b);
  1677. track->audio.coded_framesize = avio_rb32(&b);
  1678. avio_skip(&b, 12);
  1679. track->audio.sub_packet_h = avio_rb16(&b);
  1680. track->audio.frame_size = avio_rb16(&b);
  1681. track->audio.sub_packet_size = avio_rb16(&b);
  1682. if (flavor < 0 ||
  1683. track->audio.coded_framesize <= 0 ||
  1684. track->audio.sub_packet_h <= 0 ||
  1685. track->audio.frame_size <= 0 ||
  1686. track->audio.sub_packet_size <= 0)
  1687. return AVERROR_INVALIDDATA;
  1688. track->audio.buf = av_malloc_array(track->audio.sub_packet_h,
  1689. track->audio.frame_size);
  1690. if (!track->audio.buf)
  1691. return AVERROR(ENOMEM);
  1692. if (codec_id == AV_CODEC_ID_RA_288) {
  1693. st->codec->block_align = track->audio.coded_framesize;
  1694. track->codec_priv.size = 0;
  1695. } else {
  1696. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1697. static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1698. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1699. st->codec->bit_rate = sipr_bit_rate[flavor];
  1700. }
  1701. st->codec->block_align = track->audio.sub_packet_size;
  1702. extradata_offset = 78;
  1703. }
  1704. } else if (codec_id == AV_CODEC_ID_FLAC && track->codec_priv.size) {
  1705. ret = matroska_parse_flac(s, track, &extradata_offset);
  1706. if (ret < 0)
  1707. return ret;
  1708. } else if (codec_id == AV_CODEC_ID_PRORES && track->codec_priv.size == 4) {
  1709. fourcc = AV_RL32(track->codec_priv.data);
  1710. }
  1711. track->codec_priv.size -= extradata_offset;
  1712. if (codec_id == AV_CODEC_ID_NONE)
  1713. av_log(matroska->ctx, AV_LOG_INFO,
  1714. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1715. if (track->time_scale < 0.01)
  1716. track->time_scale = 1.0;
  1717. avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
  1718. 1000 * 1000 * 1000); /* 64 bit pts in ns */
  1719. /* convert the delay from ns to the track timebase */
  1720. track->codec_delay = av_rescale_q(track->codec_delay,
  1721. (AVRational){ 1, 1000000000 },
  1722. st->time_base);
  1723. st->codec->codec_id = codec_id;
  1724. if (strcmp(track->language, "und"))
  1725. av_dict_set(&st->metadata, "language", track->language, 0);
  1726. av_dict_set(&st->metadata, "title", track->name, 0);
  1727. if (track->flag_default)
  1728. st->disposition |= AV_DISPOSITION_DEFAULT;
  1729. if (track->flag_forced)
  1730. st->disposition |= AV_DISPOSITION_FORCED;
  1731. if (!st->codec->extradata) {
  1732. if (extradata) {
  1733. st->codec->extradata = extradata;
  1734. st->codec->extradata_size = extradata_size;
  1735. } else if (track->codec_priv.data && track->codec_priv.size > 0) {
  1736. if (ff_alloc_extradata(st->codec, track->codec_priv.size))
  1737. return AVERROR(ENOMEM);
  1738. memcpy(st->codec->extradata,
  1739. track->codec_priv.data + extradata_offset,
  1740. track->codec_priv.size);
  1741. }
  1742. }
  1743. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1744. MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
  1745. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1746. st->codec->codec_tag = fourcc;
  1747. if (bit_depth >= 0)
  1748. st->codec->bits_per_coded_sample = bit_depth;
  1749. st->codec->width = track->video.pixel_width;
  1750. st->codec->height = track->video.pixel_height;
  1751. av_reduce(&st->sample_aspect_ratio.num,
  1752. &st->sample_aspect_ratio.den,
  1753. st->codec->height * track->video.display_width,
  1754. st->codec->width * track->video.display_height,
  1755. 255);
  1756. if (st->codec->codec_id != AV_CODEC_ID_HEVC)
  1757. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1758. if (track->default_duration) {
  1759. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1760. 1000000000, track->default_duration, 30000);
  1761. #if FF_API_R_FRAME_RATE
  1762. if ( st->avg_frame_rate.num < st->avg_frame_rate.den * 1000LL
  1763. && st->avg_frame_rate.num > st->avg_frame_rate.den * 5LL)
  1764. st->r_frame_rate = st->avg_frame_rate;
  1765. #endif
  1766. }
  1767. /* export stereo mode flag as metadata tag */
  1768. if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
  1769. av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
  1770. /* export alpha mode flag as metadata tag */
  1771. if (track->video.alpha_mode)
  1772. av_dict_set(&st->metadata, "alpha_mode", "1", 0);
  1773. /* if we have virtual track, mark the real tracks */
  1774. for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
  1775. char buf[32];
  1776. if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
  1777. continue;
  1778. snprintf(buf, sizeof(buf), "%s_%d",
  1779. ff_matroska_video_stereo_plane[planes[j].type], i);
  1780. for (k=0; k < matroska->tracks.nb_elem; k++)
  1781. if (planes[j].uid == tracks[k].uid) {
  1782. av_dict_set(&s->streams[k]->metadata,
  1783. "stereo_mode", buf, 0);
  1784. break;
  1785. }
  1786. }
  1787. // add stream level stereo3d side data if it is a supported format
  1788. if (track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
  1789. track->video.stereo_mode != 10 && track->video.stereo_mode != 12) {
  1790. int ret = ff_mkv_stereo3d_conv(st, track->video.stereo_mode);
  1791. if (ret < 0)
  1792. return ret;
  1793. }
  1794. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1795. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1796. st->codec->sample_rate = track->audio.out_samplerate;
  1797. st->codec->channels = track->audio.channels;
  1798. if (!st->codec->bits_per_coded_sample)
  1799. st->codec->bits_per_coded_sample = track->audio.bitdepth;
  1800. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1801. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1802. if (track->codec_delay > 0) {
  1803. st->codec->delay = av_rescale_q(track->codec_delay,
  1804. st->time_base,
  1805. (AVRational){1, st->codec->sample_rate});
  1806. }
  1807. if (track->seek_preroll > 0) {
  1808. av_codec_set_seek_preroll(st->codec,
  1809. av_rescale_q(track->seek_preroll,
  1810. (AVRational){1, 1000000000},
  1811. (AVRational){1, st->codec->sample_rate}));
  1812. }
  1813. } else if (codec_id == AV_CODEC_ID_WEBVTT) {
  1814. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1815. if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
  1816. st->disposition |= AV_DISPOSITION_CAPTIONS;
  1817. } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
  1818. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1819. } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
  1820. st->disposition |= AV_DISPOSITION_METADATA;
  1821. }
  1822. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1823. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1824. if (st->codec->codec_id == AV_CODEC_ID_ASS)
  1825. matroska->contains_ssa = 1;
  1826. }
  1827. }
  1828. return 0;
  1829. }
  1830. static int matroska_read_header(AVFormatContext *s)
  1831. {
  1832. MatroskaDemuxContext *matroska = s->priv_data;
  1833. EbmlList *attachments_list = &matroska->attachments;
  1834. EbmlList *chapters_list = &matroska->chapters;
  1835. MatroskaAttachment *attachments;
  1836. MatroskaChapter *chapters;
  1837. uint64_t max_start = 0;
  1838. int64_t pos;
  1839. Ebml ebml = { 0 };
  1840. int i, j, res;
  1841. matroska->ctx = s;
  1842. matroska->cues_parsing_deferred = 1;
  1843. /* First read the EBML header. */
  1844. if (ebml_parse(matroska, ebml_syntax, &ebml) ||
  1845. ebml.version > EBML_VERSION ||
  1846. ebml.max_size > sizeof(uint64_t) ||
  1847. ebml.id_length > sizeof(uint32_t) ||
  1848. ebml.doctype_version > 3 ||
  1849. !ebml.doctype) {
  1850. av_log(matroska->ctx, AV_LOG_ERROR,
  1851. "EBML header using unsupported features\n"
  1852. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1853. ebml.version, ebml.doctype, ebml.doctype_version);
  1854. ebml_free(ebml_syntax, &ebml);
  1855. return AVERROR_PATCHWELCOME;
  1856. } else if (ebml.doctype_version == 3) {
  1857. av_log(matroska->ctx, AV_LOG_WARNING,
  1858. "EBML header using unsupported features\n"
  1859. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1860. ebml.version, ebml.doctype, ebml.doctype_version);
  1861. }
  1862. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1863. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1864. break;
  1865. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1866. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1867. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1868. ebml_free(ebml_syntax, &ebml);
  1869. return AVERROR_INVALIDDATA;
  1870. }
  1871. }
  1872. ebml_free(ebml_syntax, &ebml);
  1873. /* The next thing is a segment. */
  1874. pos = avio_tell(matroska->ctx->pb);
  1875. res = ebml_parse(matroska, matroska_segments, matroska);
  1876. // try resyncing until we find a EBML_STOP type element.
  1877. while (res != 1) {
  1878. res = matroska_resync(matroska, pos);
  1879. if (res < 0)
  1880. return res;
  1881. pos = avio_tell(matroska->ctx->pb);
  1882. res = ebml_parse(matroska, matroska_segment, matroska);
  1883. }
  1884. matroska_execute_seekhead(matroska);
  1885. if (!matroska->time_scale)
  1886. matroska->time_scale = 1000000;
  1887. if (matroska->duration)
  1888. matroska->ctx->duration = matroska->duration * matroska->time_scale *
  1889. 1000 / AV_TIME_BASE;
  1890. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1891. av_dict_set(&s->metadata, "encoder", matroska->muxingapp, 0);
  1892. if (matroska->date_utc.size == 8)
  1893. matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
  1894. res = matroska_parse_tracks(s);
  1895. if (res < 0)
  1896. return res;
  1897. attachments = attachments_list->elem;
  1898. for (j = 0; j < attachments_list->nb_elem; j++) {
  1899. if (!(attachments[j].filename && attachments[j].mime &&
  1900. attachments[j].bin.data && attachments[j].bin.size > 0)) {
  1901. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1902. } else {
  1903. AVStream *st = avformat_new_stream(s, NULL);
  1904. if (!st)
  1905. break;
  1906. av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
  1907. av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
  1908. st->codec->codec_id = AV_CODEC_ID_NONE;
  1909. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1910. if (ff_alloc_extradata(st->codec, attachments[j].bin.size))
  1911. break;
  1912. memcpy(st->codec->extradata, attachments[j].bin.data,
  1913. attachments[j].bin.size);
  1914. for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1915. if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
  1916. strlen(ff_mkv_mime_tags[i].str))) {
  1917. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1918. break;
  1919. }
  1920. }
  1921. attachments[j].stream = st;
  1922. }
  1923. }
  1924. chapters = chapters_list->elem;
  1925. for (i = 0; i < chapters_list->nb_elem; i++)
  1926. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
  1927. (max_start == 0 || chapters[i].start > max_start)) {
  1928. chapters[i].chapter =
  1929. avpriv_new_chapter(s, chapters[i].uid,
  1930. (AVRational) { 1, 1000000000 },
  1931. chapters[i].start, chapters[i].end,
  1932. chapters[i].title);
  1933. if (chapters[i].chapter) {
  1934. av_dict_set(&chapters[i].chapter->metadata,
  1935. "title", chapters[i].title, 0);
  1936. }
  1937. max_start = chapters[i].start;
  1938. }
  1939. matroska_add_index_entries(matroska);
  1940. matroska_convert_tags(s);
  1941. return 0;
  1942. }
  1943. /*
  1944. * Put one packet in an application-supplied AVPacket struct.
  1945. * Returns 0 on success or -1 on failure.
  1946. */
  1947. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1948. AVPacket *pkt)
  1949. {
  1950. if (matroska->num_packets > 0) {
  1951. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1952. av_freep(&matroska->packets[0]);
  1953. if (matroska->num_packets > 1) {
  1954. void *newpackets;
  1955. memmove(&matroska->packets[0], &matroska->packets[1],
  1956. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1957. newpackets = av_realloc(matroska->packets,
  1958. (matroska->num_packets - 1) *
  1959. sizeof(AVPacket *));
  1960. if (newpackets)
  1961. matroska->packets = newpackets;
  1962. } else {
  1963. av_freep(&matroska->packets);
  1964. matroska->prev_pkt = NULL;
  1965. }
  1966. matroska->num_packets--;
  1967. return 0;
  1968. }
  1969. return -1;
  1970. }
  1971. /*
  1972. * Free all packets in our internal queue.
  1973. */
  1974. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1975. {
  1976. matroska->prev_pkt = NULL;
  1977. if (matroska->packets) {
  1978. int n;
  1979. for (n = 0; n < matroska->num_packets; n++) {
  1980. av_free_packet(matroska->packets[n]);
  1981. av_freep(&matroska->packets[n]);
  1982. }
  1983. av_freep(&matroska->packets);
  1984. matroska->num_packets = 0;
  1985. }
  1986. }
  1987. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1988. int *buf_size, int type,
  1989. uint32_t **lace_buf, int *laces)
  1990. {
  1991. int res = 0, n, size = *buf_size;
  1992. uint8_t *data = *buf;
  1993. uint32_t *lace_size;
  1994. if (!type) {
  1995. *laces = 1;
  1996. *lace_buf = av_mallocz(sizeof(int));
  1997. if (!*lace_buf)
  1998. return AVERROR(ENOMEM);
  1999. *lace_buf[0] = size;
  2000. return 0;
  2001. }
  2002. av_assert0(size > 0);
  2003. *laces = *data + 1;
  2004. data += 1;
  2005. size -= 1;
  2006. lace_size = av_mallocz(*laces * sizeof(int));
  2007. if (!lace_size)
  2008. return AVERROR(ENOMEM);
  2009. switch (type) {
  2010. case 0x1: /* Xiph lacing */
  2011. {
  2012. uint8_t temp;
  2013. uint32_t total = 0;
  2014. for (n = 0; res == 0 && n < *laces - 1; n++) {
  2015. while (1) {
  2016. if (size <= total) {
  2017. res = AVERROR_INVALIDDATA;
  2018. break;
  2019. }
  2020. temp = *data;
  2021. total += temp;
  2022. lace_size[n] += temp;
  2023. data += 1;
  2024. size -= 1;
  2025. if (temp != 0xff)
  2026. break;
  2027. }
  2028. }
  2029. if (size <= total) {
  2030. res = AVERROR_INVALIDDATA;
  2031. break;
  2032. }
  2033. lace_size[n] = size - total;
  2034. break;
  2035. }
  2036. case 0x2: /* fixed-size lacing */
  2037. if (size % (*laces)) {
  2038. res = AVERROR_INVALIDDATA;
  2039. break;
  2040. }
  2041. for (n = 0; n < *laces; n++)
  2042. lace_size[n] = size / *laces;
  2043. break;
  2044. case 0x3: /* EBML lacing */
  2045. {
  2046. uint64_t num;
  2047. uint64_t total;
  2048. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  2049. if (n < 0 || num > INT_MAX) {
  2050. av_log(matroska->ctx, AV_LOG_INFO,
  2051. "EBML block data error\n");
  2052. res = n<0 ? n : AVERROR_INVALIDDATA;
  2053. break;
  2054. }
  2055. data += n;
  2056. size -= n;
  2057. total = lace_size[0] = num;
  2058. for (n = 1; res == 0 && n < *laces - 1; n++) {
  2059. int64_t snum;
  2060. int r;
  2061. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  2062. if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
  2063. av_log(matroska->ctx, AV_LOG_INFO,
  2064. "EBML block data error\n");
  2065. res = r<0 ? r : AVERROR_INVALIDDATA;
  2066. break;
  2067. }
  2068. data += r;
  2069. size -= r;
  2070. lace_size[n] = lace_size[n - 1] + snum;
  2071. total += lace_size[n];
  2072. }
  2073. if (size <= total) {
  2074. res = AVERROR_INVALIDDATA;
  2075. break;
  2076. }
  2077. lace_size[*laces - 1] = size - total;
  2078. break;
  2079. }
  2080. }
  2081. *buf = data;
  2082. *lace_buf = lace_size;
  2083. *buf_size = size;
  2084. return res;
  2085. }
  2086. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  2087. MatroskaTrack *track, AVStream *st,
  2088. uint8_t *data, int size, uint64_t timecode,
  2089. int64_t pos)
  2090. {
  2091. int a = st->codec->block_align;
  2092. int sps = track->audio.sub_packet_size;
  2093. int cfs = track->audio.coded_framesize;
  2094. int h = track->audio.sub_packet_h;
  2095. int y = track->audio.sub_packet_cnt;
  2096. int w = track->audio.frame_size;
  2097. int x;
  2098. if (!track->audio.pkt_cnt) {
  2099. if (track->audio.sub_packet_cnt == 0)
  2100. track->audio.buf_timecode = timecode;
  2101. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  2102. if (size < cfs * h / 2) {
  2103. av_log(matroska->ctx, AV_LOG_ERROR,
  2104. "Corrupt int4 RM-style audio packet size\n");
  2105. return AVERROR_INVALIDDATA;
  2106. }
  2107. for (x = 0; x < h / 2; x++)
  2108. memcpy(track->audio.buf + x * 2 * w + y * cfs,
  2109. data + x * cfs, cfs);
  2110. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  2111. if (size < w) {
  2112. av_log(matroska->ctx, AV_LOG_ERROR,
  2113. "Corrupt sipr RM-style audio packet size\n");
  2114. return AVERROR_INVALIDDATA;
  2115. }
  2116. memcpy(track->audio.buf + y * w, data, w);
  2117. } else {
  2118. if (size < sps * w / sps || h<=0 || w%sps) {
  2119. av_log(matroska->ctx, AV_LOG_ERROR,
  2120. "Corrupt generic RM-style audio packet size\n");
  2121. return AVERROR_INVALIDDATA;
  2122. }
  2123. for (x = 0; x < w / sps; x++)
  2124. memcpy(track->audio.buf +
  2125. sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
  2126. data + x * sps, sps);
  2127. }
  2128. if (++track->audio.sub_packet_cnt >= h) {
  2129. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  2130. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  2131. track->audio.sub_packet_cnt = 0;
  2132. track->audio.pkt_cnt = h * w / a;
  2133. }
  2134. }
  2135. while (track->audio.pkt_cnt) {
  2136. int ret;
  2137. AVPacket *pkt = av_mallocz(sizeof(AVPacket));
  2138. if (!pkt)
  2139. return AVERROR(ENOMEM);
  2140. ret = av_new_packet(pkt, a);
  2141. if (ret < 0) {
  2142. av_free(pkt);
  2143. return ret;
  2144. }
  2145. memcpy(pkt->data,
  2146. track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
  2147. a);
  2148. pkt->pts = track->audio.buf_timecode;
  2149. track->audio.buf_timecode = AV_NOPTS_VALUE;
  2150. pkt->pos = pos;
  2151. pkt->stream_index = st->index;
  2152. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2153. }
  2154. return 0;
  2155. }
  2156. /* reconstruct full wavpack blocks from mangled matroska ones */
  2157. static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
  2158. uint8_t **pdst, int *size)
  2159. {
  2160. uint8_t *dst = NULL;
  2161. int dstlen = 0;
  2162. int srclen = *size;
  2163. uint32_t samples;
  2164. uint16_t ver;
  2165. int ret, offset = 0;
  2166. if (srclen < 12 || track->stream->codec->extradata_size < 2)
  2167. return AVERROR_INVALIDDATA;
  2168. ver = AV_RL16(track->stream->codec->extradata);
  2169. samples = AV_RL32(src);
  2170. src += 4;
  2171. srclen -= 4;
  2172. while (srclen >= 8) {
  2173. int multiblock;
  2174. uint32_t blocksize;
  2175. uint8_t *tmp;
  2176. uint32_t flags = AV_RL32(src);
  2177. uint32_t crc = AV_RL32(src + 4);
  2178. src += 8;
  2179. srclen -= 8;
  2180. multiblock = (flags & 0x1800) != 0x1800;
  2181. if (multiblock) {
  2182. if (srclen < 4) {
  2183. ret = AVERROR_INVALIDDATA;
  2184. goto fail;
  2185. }
  2186. blocksize = AV_RL32(src);
  2187. src += 4;
  2188. srclen -= 4;
  2189. } else
  2190. blocksize = srclen;
  2191. if (blocksize > srclen) {
  2192. ret = AVERROR_INVALIDDATA;
  2193. goto fail;
  2194. }
  2195. tmp = av_realloc(dst, dstlen + blocksize + 32);
  2196. if (!tmp) {
  2197. ret = AVERROR(ENOMEM);
  2198. goto fail;
  2199. }
  2200. dst = tmp;
  2201. dstlen += blocksize + 32;
  2202. AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
  2203. AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
  2204. AV_WL16(dst + offset + 8, ver); // version
  2205. AV_WL16(dst + offset + 10, 0); // track/index_no
  2206. AV_WL32(dst + offset + 12, 0); // total samples
  2207. AV_WL32(dst + offset + 16, 0); // block index
  2208. AV_WL32(dst + offset + 20, samples); // number of samples
  2209. AV_WL32(dst + offset + 24, flags); // flags
  2210. AV_WL32(dst + offset + 28, crc); // crc
  2211. memcpy(dst + offset + 32, src, blocksize); // block data
  2212. src += blocksize;
  2213. srclen -= blocksize;
  2214. offset += blocksize + 32;
  2215. }
  2216. *pdst = dst;
  2217. *size = dstlen;
  2218. return 0;
  2219. fail:
  2220. av_freep(&dst);
  2221. return ret;
  2222. }
  2223. static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
  2224. MatroskaTrack *track,
  2225. AVStream *st,
  2226. uint8_t *data, int data_len,
  2227. uint64_t timecode,
  2228. uint64_t duration,
  2229. int64_t pos)
  2230. {
  2231. AVPacket *pkt;
  2232. uint8_t *id, *settings, *text, *buf;
  2233. int id_len, settings_len, text_len;
  2234. uint8_t *p, *q;
  2235. int err;
  2236. if (data_len <= 0)
  2237. return AVERROR_INVALIDDATA;
  2238. p = data;
  2239. q = data + data_len;
  2240. id = p;
  2241. id_len = -1;
  2242. while (p < q) {
  2243. if (*p == '\r' || *p == '\n') {
  2244. id_len = p - id;
  2245. if (*p == '\r')
  2246. p++;
  2247. break;
  2248. }
  2249. p++;
  2250. }
  2251. if (p >= q || *p != '\n')
  2252. return AVERROR_INVALIDDATA;
  2253. p++;
  2254. settings = p;
  2255. settings_len = -1;
  2256. while (p < q) {
  2257. if (*p == '\r' || *p == '\n') {
  2258. settings_len = p - settings;
  2259. if (*p == '\r')
  2260. p++;
  2261. break;
  2262. }
  2263. p++;
  2264. }
  2265. if (p >= q || *p != '\n')
  2266. return AVERROR_INVALIDDATA;
  2267. p++;
  2268. text = p;
  2269. text_len = q - p;
  2270. while (text_len > 0) {
  2271. const int len = text_len - 1;
  2272. const uint8_t c = p[len];
  2273. if (c != '\r' && c != '\n')
  2274. break;
  2275. text_len = len;
  2276. }
  2277. if (text_len <= 0)
  2278. return AVERROR_INVALIDDATA;
  2279. pkt = av_mallocz(sizeof(*pkt));
  2280. if (!pkt)
  2281. return AVERROR(ENOMEM);
  2282. err = av_new_packet(pkt, text_len);
  2283. if (err < 0) {
  2284. av_free(pkt);
  2285. return AVERROR(err);
  2286. }
  2287. memcpy(pkt->data, text, text_len);
  2288. if (id_len > 0) {
  2289. buf = av_packet_new_side_data(pkt,
  2290. AV_PKT_DATA_WEBVTT_IDENTIFIER,
  2291. id_len);
  2292. if (!buf) {
  2293. av_free(pkt);
  2294. return AVERROR(ENOMEM);
  2295. }
  2296. memcpy(buf, id, id_len);
  2297. }
  2298. if (settings_len > 0) {
  2299. buf = av_packet_new_side_data(pkt,
  2300. AV_PKT_DATA_WEBVTT_SETTINGS,
  2301. settings_len);
  2302. if (!buf) {
  2303. av_free(pkt);
  2304. return AVERROR(ENOMEM);
  2305. }
  2306. memcpy(buf, settings, settings_len);
  2307. }
  2308. // Do we need this for subtitles?
  2309. // pkt->flags = AV_PKT_FLAG_KEY;
  2310. pkt->stream_index = st->index;
  2311. pkt->pts = timecode;
  2312. // Do we need this for subtitles?
  2313. // pkt->dts = timecode;
  2314. pkt->duration = duration;
  2315. pkt->pos = pos;
  2316. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2317. matroska->prev_pkt = pkt;
  2318. return 0;
  2319. }
  2320. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  2321. MatroskaTrack *track, AVStream *st,
  2322. uint8_t *data, int pkt_size,
  2323. uint64_t timecode, uint64_t lace_duration,
  2324. int64_t pos, int is_keyframe,
  2325. uint8_t *additional, uint64_t additional_id, int additional_size,
  2326. int64_t discard_padding)
  2327. {
  2328. MatroskaTrackEncoding *encodings = track->encodings.elem;
  2329. uint8_t *pkt_data = data;
  2330. int offset = 0, res;
  2331. AVPacket *pkt;
  2332. if (encodings && !encodings->type && encodings->scope & 1) {
  2333. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  2334. if (res < 0)
  2335. return res;
  2336. }
  2337. if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
  2338. uint8_t *wv_data;
  2339. res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
  2340. if (res < 0) {
  2341. av_log(matroska->ctx, AV_LOG_ERROR,
  2342. "Error parsing a wavpack block.\n");
  2343. goto fail;
  2344. }
  2345. if (pkt_data != data)
  2346. av_freep(&pkt_data);
  2347. pkt_data = wv_data;
  2348. }
  2349. if (st->codec->codec_id == AV_CODEC_ID_PRORES &&
  2350. AV_RB32(&data[4]) != MKBETAG('i', 'c', 'p', 'f'))
  2351. offset = 8;
  2352. pkt = av_mallocz(sizeof(AVPacket));
  2353. if (!pkt)
  2354. return AVERROR(ENOMEM);
  2355. /* XXX: prevent data copy... */
  2356. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  2357. av_free(pkt);
  2358. res = AVERROR(ENOMEM);
  2359. goto fail;
  2360. }
  2361. if (st->codec->codec_id == AV_CODEC_ID_PRORES && offset == 8) {
  2362. uint8_t *buf = pkt->data;
  2363. bytestream_put_be32(&buf, pkt_size);
  2364. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  2365. }
  2366. memcpy(pkt->data + offset, pkt_data, pkt_size);
  2367. if (pkt_data != data)
  2368. av_freep(&pkt_data);
  2369. pkt->flags = is_keyframe;
  2370. pkt->stream_index = st->index;
  2371. if (additional_size > 0) {
  2372. uint8_t *side_data = av_packet_new_side_data(pkt,
  2373. AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
  2374. additional_size + 8);
  2375. if (!side_data) {
  2376. av_free_packet(pkt);
  2377. av_free(pkt);
  2378. return AVERROR(ENOMEM);
  2379. }
  2380. AV_WB64(side_data, additional_id);
  2381. memcpy(side_data + 8, additional, additional_size);
  2382. }
  2383. if (discard_padding) {
  2384. uint8_t *side_data = av_packet_new_side_data(pkt,
  2385. AV_PKT_DATA_SKIP_SAMPLES,
  2386. 10);
  2387. if (!side_data) {
  2388. av_free_packet(pkt);
  2389. av_free(pkt);
  2390. return AVERROR(ENOMEM);
  2391. }
  2392. AV_WL32(side_data, 0);
  2393. AV_WL32(side_data + 4, av_rescale_q(discard_padding,
  2394. (AVRational){1, 1000000000},
  2395. (AVRational){1, st->codec->sample_rate}));
  2396. }
  2397. if (track->ms_compat)
  2398. pkt->dts = timecode;
  2399. else
  2400. pkt->pts = timecode;
  2401. pkt->pos = pos;
  2402. if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
  2403. /*
  2404. * For backward compatibility.
  2405. * Historically, we have put subtitle duration
  2406. * in convergence_duration, on the off chance
  2407. * that the time_scale is less than 1us, which
  2408. * could result in a 32bit overflow on the
  2409. * normal duration field.
  2410. */
  2411. pkt->convergence_duration = lace_duration;
  2412. }
  2413. if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
  2414. lace_duration <= INT_MAX) {
  2415. /*
  2416. * For non subtitle tracks, just store the duration
  2417. * as normal.
  2418. *
  2419. * If it's a subtitle track and duration value does
  2420. * not overflow a uint32, then also store it normally.
  2421. */
  2422. pkt->duration = lace_duration;
  2423. }
  2424. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2425. matroska->prev_pkt = pkt;
  2426. return 0;
  2427. fail:
  2428. if (pkt_data != data)
  2429. av_freep(&pkt_data);
  2430. return res;
  2431. }
  2432. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  2433. int size, int64_t pos, uint64_t cluster_time,
  2434. uint64_t block_duration, int is_keyframe,
  2435. uint8_t *additional, uint64_t additional_id, int additional_size,
  2436. int64_t cluster_pos, int64_t discard_padding)
  2437. {
  2438. uint64_t timecode = AV_NOPTS_VALUE;
  2439. MatroskaTrack *track;
  2440. int res = 0;
  2441. AVStream *st;
  2442. int16_t block_time;
  2443. uint32_t *lace_size = NULL;
  2444. int n, flags, laces = 0;
  2445. uint64_t num;
  2446. int trust_default_duration = 1;
  2447. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  2448. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  2449. return n;
  2450. }
  2451. data += n;
  2452. size -= n;
  2453. track = matroska_find_track_by_num(matroska, num);
  2454. if (!track || !track->stream) {
  2455. av_log(matroska->ctx, AV_LOG_INFO,
  2456. "Invalid stream %"PRIu64" or size %u\n", num, size);
  2457. return AVERROR_INVALIDDATA;
  2458. } else if (size <= 3)
  2459. return 0;
  2460. st = track->stream;
  2461. if (st->discard >= AVDISCARD_ALL)
  2462. return res;
  2463. av_assert1(block_duration != AV_NOPTS_VALUE);
  2464. block_time = sign_extend(AV_RB16(data), 16);
  2465. data += 2;
  2466. flags = *data++;
  2467. size -= 3;
  2468. if (is_keyframe == -1)
  2469. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  2470. if (cluster_time != (uint64_t) -1 &&
  2471. (block_time >= 0 || cluster_time >= -block_time)) {
  2472. timecode = cluster_time + block_time - track->codec_delay;
  2473. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
  2474. timecode < track->end_timecode)
  2475. is_keyframe = 0; /* overlapping subtitles are not key frame */
  2476. if (is_keyframe)
  2477. av_add_index_entry(st, cluster_pos, timecode, 0, 0,
  2478. AVINDEX_KEYFRAME);
  2479. }
  2480. if (matroska->skip_to_keyframe &&
  2481. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  2482. if (timecode < matroska->skip_to_timecode)
  2483. return res;
  2484. if (is_keyframe)
  2485. matroska->skip_to_keyframe = 0;
  2486. else if (!st->skip_to_keyframe) {
  2487. av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
  2488. matroska->skip_to_keyframe = 0;
  2489. }
  2490. }
  2491. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  2492. &lace_size, &laces);
  2493. if (res)
  2494. goto end;
  2495. if (track->audio.samplerate == 8000) {
  2496. // If this is needed for more codecs, then add them here
  2497. if (st->codec->codec_id == AV_CODEC_ID_AC3) {
  2498. if (track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
  2499. trust_default_duration = 0;
  2500. }
  2501. }
  2502. if (!block_duration && trust_default_duration)
  2503. block_duration = track->default_duration * laces / matroska->time_scale;
  2504. if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
  2505. track->end_timecode =
  2506. FFMAX(track->end_timecode, timecode + block_duration);
  2507. for (n = 0; n < laces; n++) {
  2508. int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
  2509. if (lace_size[n] > size) {
  2510. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  2511. break;
  2512. }
  2513. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  2514. st->codec->codec_id == AV_CODEC_ID_COOK ||
  2515. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  2516. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  2517. st->codec->block_align && track->audio.sub_packet_size) {
  2518. res = matroska_parse_rm_audio(matroska, track, st, data,
  2519. lace_size[n],
  2520. timecode, pos);
  2521. if (res)
  2522. goto end;
  2523. } else if (st->codec->codec_id == AV_CODEC_ID_WEBVTT) {
  2524. res = matroska_parse_webvtt(matroska, track, st,
  2525. data, lace_size[n],
  2526. timecode, lace_duration,
  2527. pos);
  2528. if (res)
  2529. goto end;
  2530. } else {
  2531. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  2532. timecode, lace_duration, pos,
  2533. !n ? is_keyframe : 0,
  2534. additional, additional_id, additional_size,
  2535. discard_padding);
  2536. if (res)
  2537. goto end;
  2538. }
  2539. if (timecode != AV_NOPTS_VALUE)
  2540. timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
  2541. data += lace_size[n];
  2542. size -= lace_size[n];
  2543. }
  2544. end:
  2545. av_free(lace_size);
  2546. return res;
  2547. }
  2548. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2549. {
  2550. EbmlList *blocks_list;
  2551. MatroskaBlock *blocks;
  2552. int i, res;
  2553. res = ebml_parse(matroska,
  2554. matroska_cluster_incremental_parsing,
  2555. &matroska->current_cluster);
  2556. if (res == 1) {
  2557. /* New Cluster */
  2558. if (matroska->current_cluster_pos)
  2559. ebml_level_end(matroska);
  2560. ebml_free(matroska_cluster, &matroska->current_cluster);
  2561. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2562. matroska->current_cluster_num_blocks = 0;
  2563. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2564. matroska->prev_pkt = NULL;
  2565. /* sizeof the ID which was already read */
  2566. if (matroska->current_id)
  2567. matroska->current_cluster_pos -= 4;
  2568. res = ebml_parse(matroska,
  2569. matroska_clusters_incremental,
  2570. &matroska->current_cluster);
  2571. /* Try parsing the block again. */
  2572. if (res == 1)
  2573. res = ebml_parse(matroska,
  2574. matroska_cluster_incremental_parsing,
  2575. &matroska->current_cluster);
  2576. }
  2577. if (!res &&
  2578. matroska->current_cluster_num_blocks <
  2579. matroska->current_cluster.blocks.nb_elem) {
  2580. blocks_list = &matroska->current_cluster.blocks;
  2581. blocks = blocks_list->elem;
  2582. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2583. i = blocks_list->nb_elem - 1;
  2584. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2585. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2586. uint8_t* additional = blocks[i].additional.size > 0 ?
  2587. blocks[i].additional.data : NULL;
  2588. if (!blocks[i].non_simple)
  2589. blocks[i].duration = 0;
  2590. res = matroska_parse_block(matroska, blocks[i].bin.data,
  2591. blocks[i].bin.size, blocks[i].bin.pos,
  2592. matroska->current_cluster.timecode,
  2593. blocks[i].duration, is_keyframe,
  2594. additional, blocks[i].additional_id,
  2595. blocks[i].additional.size,
  2596. matroska->current_cluster_pos,
  2597. blocks[i].discard_padding);
  2598. }
  2599. }
  2600. return res;
  2601. }
  2602. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2603. {
  2604. MatroskaCluster cluster = { 0 };
  2605. EbmlList *blocks_list;
  2606. MatroskaBlock *blocks;
  2607. int i, res;
  2608. int64_t pos;
  2609. if (!matroska->contains_ssa)
  2610. return matroska_parse_cluster_incremental(matroska);
  2611. pos = avio_tell(matroska->ctx->pb);
  2612. matroska->prev_pkt = NULL;
  2613. if (matroska->current_id)
  2614. pos -= 4; /* sizeof the ID which was already read */
  2615. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2616. blocks_list = &cluster.blocks;
  2617. blocks = blocks_list->elem;
  2618. for (i = 0; i < blocks_list->nb_elem; i++)
  2619. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2620. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2621. res = matroska_parse_block(matroska, blocks[i].bin.data,
  2622. blocks[i].bin.size, blocks[i].bin.pos,
  2623. cluster.timecode, blocks[i].duration,
  2624. is_keyframe, NULL, 0, 0, pos,
  2625. blocks[i].discard_padding);
  2626. }
  2627. ebml_free(matroska_cluster, &cluster);
  2628. return res;
  2629. }
  2630. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2631. {
  2632. MatroskaDemuxContext *matroska = s->priv_data;
  2633. while (matroska_deliver_packet(matroska, pkt)) {
  2634. int64_t pos = avio_tell(matroska->ctx->pb);
  2635. if (matroska->done)
  2636. return AVERROR_EOF;
  2637. if (matroska_parse_cluster(matroska) < 0)
  2638. matroska_resync(matroska, pos);
  2639. }
  2640. return 0;
  2641. }
  2642. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2643. int64_t timestamp, int flags)
  2644. {
  2645. MatroskaDemuxContext *matroska = s->priv_data;
  2646. MatroskaTrack *tracks = NULL;
  2647. AVStream *st = s->streams[stream_index];
  2648. int i, index, index_sub, index_min;
  2649. /* Parse the CUES now since we need the index data to seek. */
  2650. if (matroska->cues_parsing_deferred > 0) {
  2651. matroska->cues_parsing_deferred = 0;
  2652. matroska_parse_cues(matroska);
  2653. }
  2654. if (!st->nb_index_entries)
  2655. goto err;
  2656. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2657. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
  2658. avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
  2659. SEEK_SET);
  2660. matroska->current_id = 0;
  2661. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
  2662. matroska_clear_queue(matroska);
  2663. if (matroska_parse_cluster(matroska) < 0)
  2664. break;
  2665. }
  2666. }
  2667. matroska_clear_queue(matroska);
  2668. if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
  2669. goto err;
  2670. index_min = index;
  2671. tracks = matroska->tracks.elem;
  2672. for (i = 0; i < matroska->tracks.nb_elem; i++) {
  2673. tracks[i].audio.pkt_cnt = 0;
  2674. tracks[i].audio.sub_packet_cnt = 0;
  2675. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2676. tracks[i].end_timecode = 0;
  2677. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
  2678. tracks[i].stream->discard != AVDISCARD_ALL) {
  2679. index_sub = av_index_search_timestamp(
  2680. tracks[i].stream, st->index_entries[index].timestamp,
  2681. AVSEEK_FLAG_BACKWARD);
  2682. while (index_sub >= 0 &&
  2683. index_min > 0 &&
  2684. tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos &&
  2685. st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000 / matroska->time_scale)
  2686. index_min--;
  2687. }
  2688. }
  2689. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2690. matroska->current_id = 0;
  2691. if (flags & AVSEEK_FLAG_ANY) {
  2692. st->skip_to_keyframe = 0;
  2693. matroska->skip_to_timecode = timestamp;
  2694. } else {
  2695. st->skip_to_keyframe = 1;
  2696. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2697. }
  2698. matroska->skip_to_keyframe = 1;
  2699. matroska->done = 0;
  2700. matroska->num_levels = 0;
  2701. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2702. return 0;
  2703. err:
  2704. // slightly hackish but allows proper fallback to
  2705. // the generic seeking code.
  2706. matroska_clear_queue(matroska);
  2707. matroska->current_id = 0;
  2708. st->skip_to_keyframe =
  2709. matroska->skip_to_keyframe = 0;
  2710. matroska->done = 0;
  2711. matroska->num_levels = 0;
  2712. return -1;
  2713. }
  2714. static int matroska_read_close(AVFormatContext *s)
  2715. {
  2716. MatroskaDemuxContext *matroska = s->priv_data;
  2717. MatroskaTrack *tracks = matroska->tracks.elem;
  2718. int n;
  2719. matroska_clear_queue(matroska);
  2720. for (n = 0; n < matroska->tracks.nb_elem; n++)
  2721. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2722. av_freep(&tracks[n].audio.buf);
  2723. ebml_free(matroska_cluster, &matroska->current_cluster);
  2724. ebml_free(matroska_segment, matroska);
  2725. return 0;
  2726. }
  2727. typedef struct {
  2728. int64_t start_time_ns;
  2729. int64_t end_time_ns;
  2730. int64_t start_offset;
  2731. int64_t end_offset;
  2732. } CueDesc;
  2733. /* This function searches all the Cues and returns the CueDesc corresponding the
  2734. * the timestamp ts. Returned CueDesc will be such that start_time_ns <= ts <
  2735. * end_time_ns. All 4 fields will be set to -1 if ts >= file's duration.
  2736. */
  2737. static CueDesc get_cue_desc(AVFormatContext *s, int64_t ts, int64_t cues_start) {
  2738. MatroskaDemuxContext *matroska = s->priv_data;
  2739. CueDesc cue_desc;
  2740. int i;
  2741. int nb_index_entries = s->streams[0]->nb_index_entries;
  2742. AVIndexEntry *index_entries = s->streams[0]->index_entries;
  2743. if (ts >= matroska->duration * matroska->time_scale) return (CueDesc) {-1, -1, -1, -1};
  2744. for (i = 1; i < nb_index_entries; i++) {
  2745. if (index_entries[i - 1].timestamp * matroska->time_scale <= ts &&
  2746. index_entries[i].timestamp * matroska->time_scale > ts) {
  2747. break;
  2748. }
  2749. }
  2750. --i;
  2751. cue_desc.start_time_ns = index_entries[i].timestamp * matroska->time_scale;
  2752. cue_desc.start_offset = index_entries[i].pos - matroska->segment_start;
  2753. if (i != nb_index_entries - 1) {
  2754. cue_desc.end_time_ns = index_entries[i + 1].timestamp * matroska->time_scale;
  2755. cue_desc.end_offset = index_entries[i + 1].pos - matroska->segment_start;
  2756. } else {
  2757. cue_desc.end_time_ns = matroska->duration * matroska->time_scale;
  2758. // FIXME: this needs special handling for files where Cues appear
  2759. // before Clusters. the current logic assumes Cues appear after
  2760. // Clusters.
  2761. cue_desc.end_offset = cues_start - matroska->segment_start;
  2762. }
  2763. return cue_desc;
  2764. }
  2765. static int webm_clusters_start_with_keyframe(AVFormatContext *s)
  2766. {
  2767. MatroskaDemuxContext *matroska = s->priv_data;
  2768. int64_t cluster_pos, before_pos;
  2769. int index, rv = 1;
  2770. if (s->streams[0]->nb_index_entries <= 0) return 0;
  2771. // seek to the first cluster using cues.
  2772. index = av_index_search_timestamp(s->streams[0], 0, 0);
  2773. if (index < 0) return 0;
  2774. cluster_pos = s->streams[0]->index_entries[index].pos;
  2775. before_pos = avio_tell(s->pb);
  2776. while (1) {
  2777. int64_t cluster_id = 0, cluster_length = 0;
  2778. AVPacket *pkt;
  2779. avio_seek(s->pb, cluster_pos, SEEK_SET);
  2780. // read cluster id and length
  2781. ebml_read_num(matroska, matroska->ctx->pb, 4, &cluster_id);
  2782. ebml_read_length(matroska, matroska->ctx->pb, &cluster_length);
  2783. if (cluster_id != 0xF43B675) { // done with all clusters
  2784. break;
  2785. }
  2786. avio_seek(s->pb, cluster_pos, SEEK_SET);
  2787. matroska->current_id = 0;
  2788. matroska_clear_queue(matroska);
  2789. if (matroska_parse_cluster(matroska) < 0 ||
  2790. matroska->num_packets <= 0) {
  2791. break;
  2792. }
  2793. pkt = matroska->packets[0];
  2794. cluster_pos += cluster_length + 12; // 12 is the offset of the cluster id and length.
  2795. if (!(pkt->flags & AV_PKT_FLAG_KEY)) {
  2796. rv = 0;
  2797. break;
  2798. }
  2799. }
  2800. avio_seek(s->pb, before_pos, SEEK_SET);
  2801. return rv;
  2802. }
  2803. static int buffer_size_after_time_downloaded(int64_t time_ns, double search_sec, int64_t bps,
  2804. double min_buffer, double* buffer,
  2805. double* sec_to_download, AVFormatContext *s,
  2806. int64_t cues_start)
  2807. {
  2808. double nano_seconds_per_second = 1000000000.0;
  2809. double time_sec = time_ns / nano_seconds_per_second;
  2810. int rv = 0;
  2811. int64_t time_to_search_ns = (int64_t)(search_sec * nano_seconds_per_second);
  2812. int64_t end_time_ns = time_ns + time_to_search_ns;
  2813. double sec_downloaded = 0.0;
  2814. CueDesc desc_curr = get_cue_desc(s, time_ns, cues_start);
  2815. if (desc_curr.start_time_ns == -1)
  2816. return -1;
  2817. *sec_to_download = 0.0;
  2818. // Check for non cue start time.
  2819. if (time_ns > desc_curr.start_time_ns) {
  2820. int64_t cue_nano = desc_curr.end_time_ns - time_ns;
  2821. double percent = (double)(cue_nano) / (desc_curr.end_time_ns - desc_curr.start_time_ns);
  2822. double cueBytes = (desc_curr.end_offset - desc_curr.start_offset) * percent;
  2823. double timeToDownload = (cueBytes * 8.0) / bps;
  2824. sec_downloaded += (cue_nano / nano_seconds_per_second) - timeToDownload;
  2825. *sec_to_download += timeToDownload;
  2826. // Check if the search ends within the first cue.
  2827. if (desc_curr.end_time_ns >= end_time_ns) {
  2828. double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
  2829. double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
  2830. sec_downloaded = percent_to_sub * sec_downloaded;
  2831. *sec_to_download = percent_to_sub * *sec_to_download;
  2832. }
  2833. if ((sec_downloaded + *buffer) <= min_buffer) {
  2834. return 1;
  2835. }
  2836. // Get the next Cue.
  2837. desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
  2838. }
  2839. while (desc_curr.start_time_ns != -1) {
  2840. int64_t desc_bytes = desc_curr.end_offset - desc_curr.start_offset;
  2841. int64_t desc_ns = desc_curr.end_time_ns - desc_curr.start_time_ns;
  2842. double desc_sec = desc_ns / nano_seconds_per_second;
  2843. double bits = (desc_bytes * 8.0);
  2844. double time_to_download = bits / bps;
  2845. sec_downloaded += desc_sec - time_to_download;
  2846. *sec_to_download += time_to_download;
  2847. if (desc_curr.end_time_ns >= end_time_ns) {
  2848. double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
  2849. double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
  2850. sec_downloaded = percent_to_sub * sec_downloaded;
  2851. *sec_to_download = percent_to_sub * *sec_to_download;
  2852. if ((sec_downloaded + *buffer) <= min_buffer)
  2853. rv = 1;
  2854. break;
  2855. }
  2856. if ((sec_downloaded + *buffer) <= min_buffer) {
  2857. rv = 1;
  2858. break;
  2859. }
  2860. desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
  2861. }
  2862. *buffer = *buffer + sec_downloaded;
  2863. return rv;
  2864. }
  2865. /* This function computes the bandwidth of the WebM file with the help of
  2866. * buffer_size_after_time_downloaded() function. Both of these functions are
  2867. * adapted from WebM Tools project and are adapted to work with FFmpeg's
  2868. * Matroska parsing mechanism.
  2869. *
  2870. * Returns the bandwidth of the file on success; -1 on error.
  2871. * */
  2872. static int64_t webm_dash_manifest_compute_bandwidth(AVFormatContext *s, int64_t cues_start)
  2873. {
  2874. MatroskaDemuxContext *matroska = s->priv_data;
  2875. AVStream *st = s->streams[0];
  2876. double bandwidth = 0.0;
  2877. int i;
  2878. for (i = 0; i < st->nb_index_entries; i++) {
  2879. int64_t prebuffer_ns = 1000000000;
  2880. int64_t time_ns = st->index_entries[i].timestamp * matroska->time_scale;
  2881. double nano_seconds_per_second = 1000000000.0;
  2882. int64_t prebuffered_ns = time_ns + prebuffer_ns;
  2883. double prebuffer_bytes = 0.0;
  2884. int64_t temp_prebuffer_ns = prebuffer_ns;
  2885. int64_t pre_bytes, pre_ns;
  2886. double pre_sec, prebuffer, bits_per_second;
  2887. CueDesc desc_beg = get_cue_desc(s, time_ns, cues_start);
  2888. // Start with the first Cue.
  2889. CueDesc desc_end = desc_beg;
  2890. // Figure out how much data we have downloaded for the prebuffer. This will
  2891. // be used later to adjust the bits per sample to try.
  2892. while (desc_end.start_time_ns != -1 && desc_end.end_time_ns < prebuffered_ns) {
  2893. // Prebuffered the entire Cue.
  2894. prebuffer_bytes += desc_end.end_offset - desc_end.start_offset;
  2895. temp_prebuffer_ns -= desc_end.end_time_ns - desc_end.start_time_ns;
  2896. desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
  2897. }
  2898. if (desc_end.start_time_ns == -1) {
  2899. // The prebuffer is larger than the duration.
  2900. if (matroska->duration * matroska->time_scale >= prebuffered_ns)
  2901. return -1;
  2902. bits_per_second = 0.0;
  2903. } else {
  2904. // The prebuffer ends in the last Cue. Estimate how much data was
  2905. // prebuffered.
  2906. pre_bytes = desc_end.end_offset - desc_end.start_offset;
  2907. pre_ns = desc_end.end_time_ns - desc_end.start_time_ns;
  2908. pre_sec = pre_ns / nano_seconds_per_second;
  2909. prebuffer_bytes +=
  2910. pre_bytes * ((temp_prebuffer_ns / nano_seconds_per_second) / pre_sec);
  2911. prebuffer = prebuffer_ns / nano_seconds_per_second;
  2912. // Set this to 0.0 in case our prebuffer buffers the entire video.
  2913. bits_per_second = 0.0;
  2914. do {
  2915. int64_t desc_bytes = desc_end.end_offset - desc_beg.start_offset;
  2916. int64_t desc_ns = desc_end.end_time_ns - desc_beg.start_time_ns;
  2917. double desc_sec = desc_ns / nano_seconds_per_second;
  2918. double calc_bits_per_second = (desc_bytes * 8) / desc_sec;
  2919. // Drop the bps by the percentage of bytes buffered.
  2920. double percent = (desc_bytes - prebuffer_bytes) / desc_bytes;
  2921. double mod_bits_per_second = calc_bits_per_second * percent;
  2922. if (prebuffer < desc_sec) {
  2923. double search_sec =
  2924. (double)(matroska->duration * matroska->time_scale) / nano_seconds_per_second;
  2925. // Add 1 so the bits per second should be a little bit greater than file
  2926. // datarate.
  2927. int64_t bps = (int64_t)(mod_bits_per_second) + 1;
  2928. const double min_buffer = 0.0;
  2929. double buffer = prebuffer;
  2930. double sec_to_download = 0.0;
  2931. int rv = buffer_size_after_time_downloaded(prebuffered_ns, search_sec, bps,
  2932. min_buffer, &buffer, &sec_to_download,
  2933. s, cues_start);
  2934. if (rv < 0) {
  2935. return -1;
  2936. } else if (rv == 0) {
  2937. bits_per_second = (double)(bps);
  2938. break;
  2939. }
  2940. }
  2941. desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
  2942. } while (desc_end.start_time_ns != -1);
  2943. }
  2944. if (bandwidth < bits_per_second) bandwidth = bits_per_second;
  2945. }
  2946. return (int64_t)bandwidth;
  2947. }
  2948. static int webm_dash_manifest_cues(AVFormatContext *s)
  2949. {
  2950. MatroskaDemuxContext *matroska = s->priv_data;
  2951. EbmlList *seekhead_list = &matroska->seekhead;
  2952. MatroskaSeekhead *seekhead = seekhead_list->elem;
  2953. char *buf;
  2954. int64_t cues_start = -1, cues_end = -1, before_pos, bandwidth;
  2955. int i;
  2956. // determine cues start and end positions
  2957. for (i = 0; i < seekhead_list->nb_elem; i++)
  2958. if (seekhead[i].id == MATROSKA_ID_CUES)
  2959. break;
  2960. if (i >= seekhead_list->nb_elem) return -1;
  2961. before_pos = avio_tell(matroska->ctx->pb);
  2962. cues_start = seekhead[i].pos + matroska->segment_start;
  2963. if (avio_seek(matroska->ctx->pb, cues_start, SEEK_SET) == cues_start) {
  2964. // cues_end is computed as cues_start + cues_length + length of the
  2965. // Cues element ID + EBML length of the Cues element. cues_end is
  2966. // inclusive and the above sum is reduced by 1.
  2967. uint64_t cues_length = 0, cues_id = 0, bytes_read = 0;
  2968. bytes_read += ebml_read_num(matroska, matroska->ctx->pb, 4, &cues_id);
  2969. bytes_read += ebml_read_length(matroska, matroska->ctx->pb, &cues_length);
  2970. cues_end = cues_start + cues_length + bytes_read - 1;
  2971. }
  2972. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  2973. if (cues_start == -1 || cues_end == -1) return -1;
  2974. // parse the cues
  2975. matroska_parse_cues(matroska);
  2976. // cues start
  2977. av_dict_set_int(&s->streams[0]->metadata, CUES_START, cues_start, 0);
  2978. // cues end
  2979. av_dict_set_int(&s->streams[0]->metadata, CUES_END, cues_end, 0);
  2980. // bandwidth
  2981. bandwidth = webm_dash_manifest_compute_bandwidth(s, cues_start);
  2982. if (bandwidth < 0) return -1;
  2983. av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH, bandwidth, 0);
  2984. // check if all clusters start with key frames
  2985. av_dict_set_int(&s->streams[0]->metadata, CLUSTER_KEYFRAME, webm_clusters_start_with_keyframe(s), 0);
  2986. // store cue point timestamps as a comma separated list for checking subsegment alignment in
  2987. // the muxer. assumes that each timestamp cannot be more than 20 characters long.
  2988. buf = av_malloc_array(s->streams[0]->nb_index_entries, 20 * sizeof(char));
  2989. if (!buf) return -1;
  2990. strcpy(buf, "");
  2991. for (i = 0; i < s->streams[0]->nb_index_entries; i++) {
  2992. snprintf(buf, (i + 1) * 20 * sizeof(char),
  2993. "%s%" PRId64, buf, s->streams[0]->index_entries[i].timestamp);
  2994. if (i != s->streams[0]->nb_index_entries - 1)
  2995. strncat(buf, ",", sizeof(char));
  2996. }
  2997. av_dict_set(&s->streams[0]->metadata, CUE_TIMESTAMPS, buf, 0);
  2998. av_free(buf);
  2999. return 0;
  3000. }
  3001. static int webm_dash_manifest_read_header(AVFormatContext *s)
  3002. {
  3003. char *buf;
  3004. int ret = matroska_read_header(s);
  3005. MatroskaTrack *tracks;
  3006. MatroskaDemuxContext *matroska = s->priv_data;
  3007. if (ret) {
  3008. av_log(s, AV_LOG_ERROR, "Failed to read file headers\n");
  3009. return -1;
  3010. }
  3011. // initialization range
  3012. // 5 is the offset of Cluster ID.
  3013. av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, avio_tell(s->pb) - 5, 0);
  3014. // basename of the file
  3015. buf = strrchr(s->filename, '/');
  3016. av_dict_set(&s->streams[0]->metadata, FILENAME, buf ? ++buf : s->filename, 0);
  3017. // duration
  3018. buf = av_asprintf("%g", matroska->duration);
  3019. if (!buf) return AVERROR(ENOMEM);
  3020. av_dict_set(&s->streams[0]->metadata, DURATION, buf, 0);
  3021. av_free(buf);
  3022. // track number
  3023. tracks = matroska->tracks.elem;
  3024. av_dict_set_int(&s->streams[0]->metadata, TRACK_NUMBER, tracks[0].num, 0);
  3025. // parse the cues and populate Cue related fields
  3026. return webm_dash_manifest_cues(s);
  3027. }
  3028. static int webm_dash_manifest_read_packet(AVFormatContext *s, AVPacket *pkt)
  3029. {
  3030. return AVERROR_EOF;
  3031. }
  3032. AVInputFormat ff_matroska_demuxer = {
  3033. .name = "matroska,webm",
  3034. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  3035. .extensions = "mkv,mk3d,mka,mks",
  3036. .priv_data_size = sizeof(MatroskaDemuxContext),
  3037. .read_probe = matroska_probe,
  3038. .read_header = matroska_read_header,
  3039. .read_packet = matroska_read_packet,
  3040. .read_close = matroska_read_close,
  3041. .read_seek = matroska_read_seek,
  3042. .mime_type = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
  3043. };
  3044. AVInputFormat ff_webm_dash_manifest_demuxer = {
  3045. .name = "webm_dash_manifest",
  3046. .long_name = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
  3047. .priv_data_size = sizeof(MatroskaDemuxContext),
  3048. .read_header = webm_dash_manifest_read_header,
  3049. .read_packet = webm_dash_manifest_read_packet,
  3050. .read_close = matroska_read_close,
  3051. };