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.

3386 lines
120KB

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