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.

3366 lines
119KB

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