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.

2533 lines
87KB

  1. /*
  2. * Matroska file demuxer
  3. * Copyright (c) 2003-2008 The Libav Project
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Matroska file demuxer
  24. * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * @see specs available on the Matroska project page: http://www.matroska.org/
  28. */
  29. #include "config.h"
  30. #include <inttypes.h>
  31. #include <stdio.h>
  32. #if CONFIG_BZLIB
  33. #include <bzlib.h>
  34. #endif
  35. #if CONFIG_ZLIB
  36. #include <zlib.h>
  37. #endif
  38. #include "libavutil/avstring.h"
  39. #include "libavutil/dict.h"
  40. #include "libavutil/intfloat.h"
  41. #include "libavutil/intreadwrite.h"
  42. #include "libavutil/lzo.h"
  43. #include "libavcodec/bytestream.h"
  44. #include "libavcodec/mpeg4audio.h"
  45. #include "avformat.h"
  46. #include "avio_internal.h"
  47. #include "internal.h"
  48. #include "isom.h"
  49. #include "matroska.h"
  50. /* For ff_codec_get_id(). */
  51. #include "riff.h"
  52. #include "rmsipr.h"
  53. typedef enum {
  54. EBML_NONE,
  55. EBML_UINT,
  56. EBML_FLOAT,
  57. EBML_STR,
  58. EBML_UTF8,
  59. EBML_BIN,
  60. EBML_NEST,
  61. EBML_PASS,
  62. EBML_STOP,
  63. EBML_TYPE_COUNT
  64. } EbmlType;
  65. typedef const struct EbmlSyntax {
  66. uint32_t id;
  67. EbmlType type;
  68. int list_elem_size;
  69. int data_offset;
  70. union {
  71. uint64_t u;
  72. double f;
  73. const char *s;
  74. const struct EbmlSyntax *n;
  75. } def;
  76. } EbmlSyntax;
  77. typedef struct {
  78. int nb_elem;
  79. void *elem;
  80. } EbmlList;
  81. typedef struct {
  82. int size;
  83. uint8_t *data;
  84. int64_t pos;
  85. } EbmlBin;
  86. typedef struct {
  87. uint64_t version;
  88. uint64_t max_size;
  89. uint64_t id_length;
  90. char *doctype;
  91. uint64_t doctype_version;
  92. } Ebml;
  93. typedef struct {
  94. uint64_t algo;
  95. EbmlBin settings;
  96. } MatroskaTrackCompression;
  97. typedef struct {
  98. uint64_t scope;
  99. uint64_t type;
  100. MatroskaTrackCompression compression;
  101. } MatroskaTrackEncoding;
  102. typedef struct {
  103. double frame_rate;
  104. uint64_t display_width;
  105. uint64_t display_height;
  106. uint64_t pixel_width;
  107. uint64_t pixel_height;
  108. uint64_t fourcc;
  109. } MatroskaTrackVideo;
  110. typedef struct {
  111. double samplerate;
  112. double out_samplerate;
  113. uint64_t bitdepth;
  114. uint64_t channels;
  115. /* real audio header (extracted from extradata) */
  116. int coded_framesize;
  117. int sub_packet_h;
  118. int frame_size;
  119. int sub_packet_size;
  120. int sub_packet_cnt;
  121. int pkt_cnt;
  122. uint64_t buf_timecode;
  123. uint8_t *buf;
  124. } MatroskaTrackAudio;
  125. typedef struct {
  126. uint64_t num;
  127. uint64_t uid;
  128. uint64_t type;
  129. char *name;
  130. char *codec_id;
  131. EbmlBin codec_priv;
  132. char *language;
  133. double time_scale;
  134. uint64_t default_duration;
  135. uint64_t flag_default;
  136. uint64_t flag_forced;
  137. MatroskaTrackVideo video;
  138. MatroskaTrackAudio audio;
  139. EbmlList encodings;
  140. AVStream *stream;
  141. int64_t end_timecode;
  142. int ms_compat;
  143. } MatroskaTrack;
  144. typedef struct {
  145. uint64_t uid;
  146. char *filename;
  147. char *mime;
  148. EbmlBin bin;
  149. AVStream *stream;
  150. } MatroskaAttachment;
  151. typedef struct {
  152. uint64_t start;
  153. uint64_t end;
  154. uint64_t uid;
  155. char *title;
  156. AVChapter *chapter;
  157. } MatroskaChapter;
  158. typedef struct {
  159. uint64_t track;
  160. uint64_t pos;
  161. } MatroskaIndexPos;
  162. typedef struct {
  163. uint64_t time;
  164. EbmlList pos;
  165. } MatroskaIndex;
  166. typedef struct {
  167. char *name;
  168. char *string;
  169. char *lang;
  170. uint64_t def;
  171. EbmlList sub;
  172. } MatroskaTag;
  173. typedef struct {
  174. char *type;
  175. uint64_t typevalue;
  176. uint64_t trackuid;
  177. uint64_t chapteruid;
  178. uint64_t attachuid;
  179. } MatroskaTagTarget;
  180. typedef struct {
  181. MatroskaTagTarget target;
  182. EbmlList tag;
  183. } MatroskaTags;
  184. typedef struct {
  185. uint64_t id;
  186. uint64_t pos;
  187. } MatroskaSeekhead;
  188. typedef struct {
  189. uint64_t start;
  190. uint64_t length;
  191. } MatroskaLevel;
  192. typedef struct {
  193. uint64_t timecode;
  194. EbmlList blocks;
  195. } MatroskaCluster;
  196. typedef struct {
  197. AVFormatContext *ctx;
  198. /* EBML stuff */
  199. int num_levels;
  200. MatroskaLevel levels[EBML_MAX_DEPTH];
  201. int level_up;
  202. uint32_t current_id;
  203. uint64_t time_scale;
  204. double duration;
  205. char *title;
  206. EbmlList tracks;
  207. EbmlList attachments;
  208. EbmlList chapters;
  209. EbmlList index;
  210. EbmlList tags;
  211. EbmlList seekhead;
  212. /* byte position of the segment inside the stream */
  213. int64_t segment_start;
  214. /* the packet queue */
  215. AVPacket **packets;
  216. int num_packets;
  217. AVPacket *prev_pkt;
  218. int done;
  219. /* What to skip before effectively reading a packet. */
  220. int skip_to_keyframe;
  221. uint64_t skip_to_timecode;
  222. /* File has a CUES element, but we defer parsing until it is needed. */
  223. int cues_parsing_deferred;
  224. int current_cluster_num_blocks;
  225. int64_t current_cluster_pos;
  226. MatroskaCluster current_cluster;
  227. /* File has SSA subtitles which prevent incremental cluster parsing. */
  228. int contains_ssa;
  229. } MatroskaDemuxContext;
  230. typedef struct {
  231. uint64_t duration;
  232. int64_t reference;
  233. uint64_t non_simple;
  234. EbmlBin bin;
  235. } MatroskaBlock;
  236. static EbmlSyntax ebml_header[] = {
  237. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml, version), { .u = EBML_VERSION } },
  238. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml, max_size), { .u = 8 } },
  239. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml, id_length), { .u = 4 } },
  240. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml, doctype), { .s = "(none)" } },
  241. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml, doctype_version), { .u = 1 } },
  242. { EBML_ID_EBMLVERSION, EBML_NONE },
  243. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  244. { 0 }
  245. };
  246. static EbmlSyntax ebml_syntax[] = {
  247. { EBML_ID_HEADER, EBML_NEST, 0, 0, { .n = ebml_header } },
  248. { 0 }
  249. };
  250. static EbmlSyntax matroska_info[] = {
  251. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext, time_scale), { .u = 1000000 } },
  252. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext, duration) },
  253. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext, title) },
  254. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  255. { MATROSKA_ID_MUXINGAPP, EBML_NONE },
  256. { MATROSKA_ID_DATEUTC, EBML_NONE },
  257. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  258. { 0 }
  259. };
  260. static EbmlSyntax matroska_track_video[] = {
  261. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT, 0, offsetof(MatroskaTrackVideo, frame_rate) },
  262. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_width) },
  263. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_height) },
  264. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo, pixel_width) },
  265. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, pixel_height) },
  266. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo, fourcc) },
  267. { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
  268. { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
  269. { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
  270. { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
  271. { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
  272. { MATROSKA_ID_VIDEOFLAGINTERLACED, EBML_NONE },
  273. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
  274. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  275. { 0 }
  276. };
  277. static EbmlSyntax matroska_track_audio[] = {
  278. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, samplerate), { .f = 8000.0 } },
  279. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, out_samplerate) },
  280. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio, bitdepth) },
  281. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio, channels), { .u = 1 } },
  282. { 0 }
  283. };
  284. static EbmlSyntax matroska_track_encoding_compression[] = {
  285. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression, algo), { .u = 0 } },
  286. { MATROSKA_ID_ENCODINGCOMPSETTINGS, EBML_BIN, 0, offsetof(MatroskaTrackCompression, settings) },
  287. { 0 }
  288. };
  289. static EbmlSyntax matroska_track_encoding[] = {
  290. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding, scope), { .u = 1 } },
  291. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding, type), { .u = 0 } },
  292. { MATROSKA_ID_ENCODINGCOMPRESSION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, compression), { .n = matroska_track_encoding_compression } },
  293. { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
  294. { 0 }
  295. };
  296. static EbmlSyntax matroska_track_encodings[] = {
  297. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack, encodings), { .n = matroska_track_encoding } },
  298. { 0 }
  299. };
  300. static EbmlSyntax matroska_track[] = {
  301. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack, num) },
  302. { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack, name) },
  303. { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack, uid) },
  304. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack, type) },
  305. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack, codec_id) },
  306. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack, codec_priv) },
  307. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack, language), { .s = "eng" } },
  308. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack, default_duration) },
  309. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT, 0, offsetof(MatroskaTrack, time_scale), { .f = 1.0 } },
  310. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack, flag_default), { .u = 1 } },
  311. { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack, flag_forced), { .u = 0 } },
  312. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack, video), { .n = matroska_track_video } },
  313. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack, audio), { .n = matroska_track_audio } },
  314. { MATROSKA_ID_TRACKCONTENTENCODINGS, EBML_NEST, 0, 0, { .n = matroska_track_encodings } },
  315. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  316. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  317. { MATROSKA_ID_CODECNAME, EBML_NONE },
  318. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  319. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  320. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  321. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  322. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  323. { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
  324. { 0 }
  325. };
  326. static EbmlSyntax matroska_tracks[] = {
  327. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
  328. { 0 }
  329. };
  330. static EbmlSyntax matroska_attachment[] = {
  331. { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachment, uid) },
  332. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachment, filename) },
  333. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachment, mime) },
  334. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachment, bin) },
  335. { MATROSKA_ID_FILEDESC, EBML_NONE },
  336. { 0 }
  337. };
  338. static EbmlSyntax matroska_attachments[] = {
  339. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
  340. { 0 }
  341. };
  342. static EbmlSyntax matroska_chapter_display[] = {
  343. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter, title) },
  344. { MATROSKA_ID_CHAPLANG, EBML_NONE },
  345. { 0 }
  346. };
  347. static EbmlSyntax matroska_chapter_entry[] = {
  348. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter, start), { .u = AV_NOPTS_VALUE } },
  349. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter, end), { .u = AV_NOPTS_VALUE } },
  350. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter, uid) },
  351. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, { .n = matroska_chapter_display } },
  352. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  353. { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  354. { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
  355. { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
  356. { 0 }
  357. };
  358. static EbmlSyntax matroska_chapter[] = {
  359. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
  360. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  361. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  362. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  363. { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  364. { 0 }
  365. };
  366. static EbmlSyntax matroska_chapters[] = {
  367. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, { .n = matroska_chapter } },
  368. { 0 }
  369. };
  370. static EbmlSyntax matroska_index_pos[] = {
  371. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos, track) },
  372. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos, pos) },
  373. { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
  374. { 0 }
  375. };
  376. static EbmlSyntax matroska_index_entry[] = {
  377. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex, time) },
  378. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex, pos), { .n = matroska_index_pos } },
  379. { 0 }
  380. };
  381. static EbmlSyntax matroska_index[] = {
  382. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext, index), { .n = matroska_index_entry } },
  383. { 0 }
  384. };
  385. static EbmlSyntax matroska_simpletag[] = {
  386. { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag, name) },
  387. { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag, string) },
  388. { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag, lang), { .s = "und" } },
  389. { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag, def) },
  390. { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag, def) },
  391. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag, sub), { .n = matroska_simpletag } },
  392. { 0 }
  393. };
  394. static EbmlSyntax matroska_tagtargets[] = {
  395. { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget, type) },
  396. { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget, typevalue), { .u = 50 } },
  397. { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, trackuid) },
  398. { MATROSKA_ID_TAGTARGETS_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, chapteruid) },
  399. { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, attachuid) },
  400. { 0 }
  401. };
  402. static EbmlSyntax matroska_tag[] = {
  403. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags, tag), { .n = matroska_simpletag } },
  404. { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags, target), { .n = matroska_tagtargets } },
  405. { 0 }
  406. };
  407. static EbmlSyntax matroska_tags[] = {
  408. { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
  409. { 0 }
  410. };
  411. static EbmlSyntax matroska_seekhead_entry[] = {
  412. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead, id) },
  413. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
  414. { 0 }
  415. };
  416. static EbmlSyntax matroska_seekhead[] = {
  417. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
  418. { 0 }
  419. };
  420. static EbmlSyntax matroska_segment[] = {
  421. { MATROSKA_ID_INFO, EBML_NEST, 0, 0, { .n = matroska_info } },
  422. { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, { .n = matroska_tracks } },
  423. { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, { .n = matroska_attachments } },
  424. { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, { .n = matroska_chapters } },
  425. { MATROSKA_ID_CUES, EBML_NEST, 0, 0, { .n = matroska_index } },
  426. { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, { .n = matroska_tags } },
  427. { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, { .n = matroska_seekhead } },
  428. { MATROSKA_ID_CLUSTER, EBML_STOP },
  429. { 0 }
  430. };
  431. static EbmlSyntax matroska_segments[] = {
  432. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, { .n = matroska_segment } },
  433. { 0 }
  434. };
  435. static EbmlSyntax matroska_blockgroup[] = {
  436. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) },
  437. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) },
  438. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock, duration), { .u = AV_NOPTS_VALUE } },
  439. { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock, reference) },
  440. { MATROSKA_ID_CODECSTATE, EBML_NONE },
  441. { 1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
  442. { 0 }
  443. };
  444. static EbmlSyntax matroska_cluster[] = {
  445. { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
  446. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  447. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  448. { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  449. { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  450. { 0 }
  451. };
  452. static EbmlSyntax matroska_clusters[] = {
  453. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, { .n = matroska_cluster } },
  454. { MATROSKA_ID_INFO, EBML_NONE },
  455. { MATROSKA_ID_CUES, EBML_NONE },
  456. { MATROSKA_ID_TAGS, EBML_NONE },
  457. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  458. { 0 }
  459. };
  460. static EbmlSyntax matroska_cluster_incremental_parsing[] = {
  461. { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
  462. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  463. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  464. { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  465. { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  466. { MATROSKA_ID_INFO, EBML_NONE },
  467. { MATROSKA_ID_CUES, EBML_NONE },
  468. { MATROSKA_ID_TAGS, EBML_NONE },
  469. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  470. { MATROSKA_ID_CLUSTER, EBML_STOP },
  471. { 0 }
  472. };
  473. static EbmlSyntax matroska_cluster_incremental[] = {
  474. { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
  475. { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
  476. { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
  477. { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  478. { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  479. { 0 }
  480. };
  481. static EbmlSyntax matroska_clusters_incremental[] = {
  482. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, { .n = matroska_cluster_incremental } },
  483. { MATROSKA_ID_INFO, EBML_NONE },
  484. { MATROSKA_ID_CUES, EBML_NONE },
  485. { MATROSKA_ID_TAGS, EBML_NONE },
  486. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  487. { 0 }
  488. };
  489. static const char *const matroska_doctypes[] = { "matroska", "webm" };
  490. static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
  491. {
  492. AVIOContext *pb = matroska->ctx->pb;
  493. uint32_t id;
  494. matroska->current_id = 0;
  495. matroska->num_levels = 0;
  496. /* seek to next position to resync from */
  497. if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
  498. goto eof;
  499. id = avio_rb32(pb);
  500. // try to find a toplevel element
  501. while (!pb->eof_reached) {
  502. if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
  503. id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
  504. id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
  505. id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
  506. matroska->current_id = id;
  507. return 0;
  508. }
  509. id = (id << 8) | avio_r8(pb);
  510. }
  511. eof:
  512. matroska->done = 1;
  513. return AVERROR_EOF;
  514. }
  515. /*
  516. * Return: Whether we reached the end of a level in the hierarchy or not.
  517. */
  518. static int ebml_level_end(MatroskaDemuxContext *matroska)
  519. {
  520. AVIOContext *pb = matroska->ctx->pb;
  521. int64_t pos = avio_tell(pb);
  522. if (matroska->num_levels > 0) {
  523. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  524. if (pos - level->start >= level->length || matroska->current_id) {
  525. matroska->num_levels--;
  526. return 1;
  527. }
  528. }
  529. return 0;
  530. }
  531. /*
  532. * Read: an "EBML number", which is defined as a variable-length
  533. * array of bytes. The first byte indicates the length by giving a
  534. * number of 0-bits followed by a one. The position of the first
  535. * "one" bit inside the first byte indicates the length of this
  536. * number.
  537. * Returns: number of bytes read, < 0 on error
  538. */
  539. static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  540. int max_size, uint64_t *number)
  541. {
  542. int read = 1, n = 1;
  543. uint64_t total = 0;
  544. /* The first byte tells us the length in bytes - avio_r8() can normally
  545. * return 0, but since that's not a valid first ebmlID byte, we can
  546. * use it safely here to catch EOS. */
  547. if (!(total = avio_r8(pb))) {
  548. /* we might encounter EOS here */
  549. if (!pb->eof_reached) {
  550. int64_t pos = avio_tell(pb);
  551. av_log(matroska->ctx, AV_LOG_ERROR,
  552. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  553. pos, pos);
  554. return pb->error ? pb->error : AVERROR(EIO);
  555. }
  556. return AVERROR_EOF;
  557. }
  558. /* get the length of the EBML number */
  559. read = 8 - ff_log2_tab[total];
  560. if (read > max_size) {
  561. int64_t pos = avio_tell(pb) - 1;
  562. av_log(matroska->ctx, AV_LOG_ERROR,
  563. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  564. (uint8_t) total, pos, pos);
  565. return AVERROR_INVALIDDATA;
  566. }
  567. /* read out length */
  568. total ^= 1 << ff_log2_tab[total];
  569. while (n++ < read)
  570. total = (total << 8) | avio_r8(pb);
  571. *number = total;
  572. return read;
  573. }
  574. /**
  575. * Read a EBML length value.
  576. * This needs special handling for the "unknown length" case which has multiple
  577. * encodings.
  578. */
  579. static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  580. uint64_t *number)
  581. {
  582. int res = ebml_read_num(matroska, pb, 8, number);
  583. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  584. *number = 0xffffffffffffffULL;
  585. return res;
  586. }
  587. /*
  588. * Read the next element as an unsigned int.
  589. * 0 is success, < 0 is failure.
  590. */
  591. static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  592. {
  593. int n = 0;
  594. if (size > 8)
  595. return AVERROR_INVALIDDATA;
  596. /* big-endian ordering; build up number */
  597. *num = 0;
  598. while (n++ < size)
  599. *num = (*num << 8) | avio_r8(pb);
  600. return 0;
  601. }
  602. /*
  603. * Read the next element as a float.
  604. * 0 is success, < 0 is failure.
  605. */
  606. static int ebml_read_float(AVIOContext *pb, int size, double *num)
  607. {
  608. if (size == 0)
  609. *num = 0;
  610. else if (size == 4)
  611. *num = av_int2float(avio_rb32(pb));
  612. else if (size == 8)
  613. *num = av_int2double(avio_rb64(pb));
  614. else
  615. return AVERROR_INVALIDDATA;
  616. return 0;
  617. }
  618. /*
  619. * Read the next element as an ASCII string.
  620. * 0 is success, < 0 is failure.
  621. */
  622. static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  623. {
  624. char *res;
  625. /* EBML strings are usually not 0-terminated, so we allocate one
  626. * byte more, read the string and NULL-terminate it ourselves. */
  627. if (!(res = av_malloc(size + 1)))
  628. return AVERROR(ENOMEM);
  629. if (avio_read(pb, (uint8_t *) res, size) != size) {
  630. av_free(res);
  631. return AVERROR(EIO);
  632. }
  633. (res)[size] = '\0';
  634. av_free(*str);
  635. *str = res;
  636. return 0;
  637. }
  638. /*
  639. * Read the next element as binary data.
  640. * 0 is success, < 0 is failure.
  641. */
  642. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  643. {
  644. av_free(bin->data);
  645. if (!(bin->data = av_malloc(length + FF_INPUT_BUFFER_PADDING_SIZE)))
  646. return AVERROR(ENOMEM);
  647. memset(bin->data + length, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  648. bin->size = length;
  649. bin->pos = avio_tell(pb);
  650. if (avio_read(pb, bin->data, length) != length) {
  651. av_freep(&bin->data);
  652. return AVERROR(EIO);
  653. }
  654. return 0;
  655. }
  656. /*
  657. * Read the next element, but only the header. The contents
  658. * are supposed to be sub-elements which can be read separately.
  659. * 0 is success, < 0 is failure.
  660. */
  661. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  662. {
  663. AVIOContext *pb = matroska->ctx->pb;
  664. MatroskaLevel *level;
  665. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  666. av_log(matroska->ctx, AV_LOG_ERROR,
  667. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  668. return AVERROR(ENOSYS);
  669. }
  670. level = &matroska->levels[matroska->num_levels++];
  671. level->start = avio_tell(pb);
  672. level->length = length;
  673. return 0;
  674. }
  675. /*
  676. * Read signed/unsigned "EBML" numbers.
  677. * Return: number of bytes processed, < 0 on error
  678. */
  679. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  680. uint8_t *data, uint32_t size, uint64_t *num)
  681. {
  682. AVIOContext pb;
  683. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  684. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  685. }
  686. /*
  687. * Same as above, but signed.
  688. */
  689. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  690. uint8_t *data, uint32_t size, int64_t *num)
  691. {
  692. uint64_t unum;
  693. int res;
  694. /* read as unsigned number first */
  695. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  696. return res;
  697. /* make signed (weird way) */
  698. *num = unum - ((1LL << (7 * res - 1)) - 1);
  699. return res;
  700. }
  701. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  702. EbmlSyntax *syntax, void *data);
  703. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  704. uint32_t id, void *data)
  705. {
  706. int i;
  707. for (i = 0; syntax[i].id; i++)
  708. if (id == syntax[i].id)
  709. break;
  710. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  711. matroska->num_levels > 0 &&
  712. matroska->levels[matroska->num_levels - 1].length == 0xffffffffffffff)
  713. return 0; // we reached the end of an unknown size cluster
  714. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
  715. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%"PRIX32"\n", id);
  716. if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
  717. return AVERROR_INVALIDDATA;
  718. }
  719. return ebml_parse_elem(matroska, &syntax[i], data);
  720. }
  721. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  722. void *data)
  723. {
  724. if (!matroska->current_id) {
  725. uint64_t id;
  726. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  727. if (res < 0)
  728. return res;
  729. matroska->current_id = id | 1 << 7 * res;
  730. }
  731. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  732. }
  733. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  734. void *data)
  735. {
  736. int i, res = 0;
  737. for (i = 0; syntax[i].id; i++)
  738. switch (syntax[i].type) {
  739. case EBML_UINT:
  740. *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u;
  741. break;
  742. case EBML_FLOAT:
  743. *(double *) ((char *) data + syntax[i].data_offset) = syntax[i].def.f;
  744. break;
  745. case EBML_STR:
  746. case EBML_UTF8:
  747. // the default may be NULL
  748. if (syntax[i].def.s) {
  749. uint8_t **dst = (uint8_t **) ((uint8_t *) data + syntax[i].data_offset);
  750. *dst = av_strdup(syntax[i].def.s);
  751. if (!*dst)
  752. return AVERROR(ENOMEM);
  753. }
  754. break;
  755. }
  756. while (!res && !ebml_level_end(matroska))
  757. res = ebml_parse(matroska, syntax, data);
  758. return res;
  759. }
  760. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  761. EbmlSyntax *syntax, void *data)
  762. {
  763. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  764. [EBML_UINT] = 8,
  765. [EBML_FLOAT] = 8,
  766. // max. 16 MB for strings
  767. [EBML_STR] = 0x1000000,
  768. [EBML_UTF8] = 0x1000000,
  769. // max. 256 MB for binary data
  770. [EBML_BIN] = 0x10000000,
  771. // no limits for anything else
  772. };
  773. AVIOContext *pb = matroska->ctx->pb;
  774. uint32_t id = syntax->id;
  775. uint64_t length;
  776. int res;
  777. data = (char *) data + syntax->data_offset;
  778. if (syntax->list_elem_size) {
  779. EbmlList *list = data;
  780. if ((res = av_reallocp_array(&list->elem,
  781. list->nb_elem + 1,
  782. syntax->list_elem_size)) < 0) {
  783. list->nb_elem = 0;
  784. return res;
  785. }
  786. data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
  787. memset(data, 0, syntax->list_elem_size);
  788. list->nb_elem++;
  789. }
  790. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  791. matroska->current_id = 0;
  792. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  793. return res;
  794. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  795. av_log(matroska->ctx, AV_LOG_ERROR,
  796. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  797. length, max_lengths[syntax->type], syntax->type);
  798. return AVERROR_INVALIDDATA;
  799. }
  800. }
  801. switch (syntax->type) {
  802. case EBML_UINT:
  803. res = ebml_read_uint(pb, length, data);
  804. break;
  805. case EBML_FLOAT:
  806. res = ebml_read_float(pb, length, data);
  807. break;
  808. case EBML_STR:
  809. case EBML_UTF8:
  810. res = ebml_read_ascii(pb, length, data);
  811. break;
  812. case EBML_BIN:
  813. res = ebml_read_binary(pb, length, data);
  814. break;
  815. case EBML_NEST:
  816. if ((res = ebml_read_master(matroska, length)) < 0)
  817. return res;
  818. if (id == MATROSKA_ID_SEGMENT)
  819. matroska->segment_start = avio_tell(matroska->ctx->pb);
  820. return ebml_parse_nest(matroska, syntax->def.n, data);
  821. case EBML_PASS:
  822. return ebml_parse_id(matroska, syntax->def.n, id, data);
  823. case EBML_STOP:
  824. return 1;
  825. default:
  826. return avio_skip(pb, length) < 0 ? AVERROR(EIO) : 0;
  827. }
  828. if (res == AVERROR_INVALIDDATA)
  829. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  830. else if (res == AVERROR(EIO))
  831. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  832. return res;
  833. }
  834. static void ebml_free(EbmlSyntax *syntax, void *data)
  835. {
  836. int i, j;
  837. for (i = 0; syntax[i].id; i++) {
  838. void *data_off = (char *) data + syntax[i].data_offset;
  839. switch (syntax[i].type) {
  840. case EBML_STR:
  841. case EBML_UTF8:
  842. av_freep(data_off);
  843. break;
  844. case EBML_BIN:
  845. av_freep(&((EbmlBin *) data_off)->data);
  846. break;
  847. case EBML_NEST:
  848. if (syntax[i].list_elem_size) {
  849. EbmlList *list = data_off;
  850. char *ptr = list->elem;
  851. for (j = 0; j < list->nb_elem;
  852. j++, ptr += syntax[i].list_elem_size)
  853. ebml_free(syntax[i].def.n, ptr);
  854. av_free(list->elem);
  855. } else
  856. ebml_free(syntax[i].def.n, data_off);
  857. default:
  858. break;
  859. }
  860. }
  861. }
  862. /*
  863. * Autodetecting...
  864. */
  865. static int matroska_probe(AVProbeData *p)
  866. {
  867. uint64_t total = 0;
  868. int len_mask = 0x80, size = 1, n = 1, i;
  869. /* EBML header? */
  870. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  871. return 0;
  872. /* length of header */
  873. total = p->buf[4];
  874. while (size <= 8 && !(total & len_mask)) {
  875. size++;
  876. len_mask >>= 1;
  877. }
  878. if (size > 8)
  879. return 0;
  880. total &= (len_mask - 1);
  881. while (n < size)
  882. total = (total << 8) | p->buf[4 + n++];
  883. /* Does the probe data contain the whole header? */
  884. if (p->buf_size < 4 + size + total)
  885. return 0;
  886. /* The header should contain a known document type. For now,
  887. * we don't parse the whole header but simply check for the
  888. * availability of that array of characters inside the header.
  889. * Not fully fool-proof, but good enough. */
  890. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  891. int probelen = strlen(matroska_doctypes[i]);
  892. if (total < probelen)
  893. continue;
  894. for (n = 4 + size; n <= 4 + size + total - probelen; n++)
  895. if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
  896. return AVPROBE_SCORE_MAX;
  897. }
  898. // probably valid EBML header but no recognized doctype
  899. return AVPROBE_SCORE_EXTENSION;
  900. }
  901. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  902. int num)
  903. {
  904. MatroskaTrack *tracks = matroska->tracks.elem;
  905. int i;
  906. for (i = 0; i < matroska->tracks.nb_elem; i++)
  907. if (tracks[i].num == num)
  908. return &tracks[i];
  909. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  910. return NULL;
  911. }
  912. static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
  913. MatroskaTrack *track)
  914. {
  915. MatroskaTrackEncoding *encodings = track->encodings.elem;
  916. uint8_t *data = *buf;
  917. int isize = *buf_size;
  918. uint8_t *pkt_data = NULL;
  919. uint8_t av_unused *newpktdata;
  920. int pkt_size = isize;
  921. int result = 0;
  922. int olen;
  923. if (pkt_size >= 10000000)
  924. return AVERROR_INVALIDDATA;
  925. switch (encodings[0].compression.algo) {
  926. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  927. {
  928. int header_size = encodings[0].compression.settings.size;
  929. uint8_t *header = encodings[0].compression.settings.data;
  930. if (!header_size)
  931. return 0;
  932. pkt_size = isize + header_size;
  933. pkt_data = av_malloc(pkt_size);
  934. if (!pkt_data)
  935. return AVERROR(ENOMEM);
  936. memcpy(pkt_data, header, header_size);
  937. memcpy(pkt_data + header_size, data, isize);
  938. break;
  939. }
  940. #if CONFIG_LZO
  941. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  942. do {
  943. olen = pkt_size *= 3;
  944. newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
  945. if (!newpktdata) {
  946. result = AVERROR(ENOMEM);
  947. goto failed;
  948. }
  949. pkt_data = newpktdata;
  950. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  951. } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
  952. if (result) {
  953. result = AVERROR_INVALIDDATA;
  954. goto failed;
  955. }
  956. pkt_size -= olen;
  957. break;
  958. #endif
  959. #if CONFIG_ZLIB
  960. case MATROSKA_TRACK_ENCODING_COMP_ZLIB:
  961. {
  962. z_stream zstream = { 0 };
  963. if (inflateInit(&zstream) != Z_OK)
  964. return -1;
  965. zstream.next_in = data;
  966. zstream.avail_in = isize;
  967. do {
  968. pkt_size *= 3;
  969. newpktdata = av_realloc(pkt_data, pkt_size);
  970. if (!newpktdata) {
  971. inflateEnd(&zstream);
  972. goto failed;
  973. }
  974. pkt_data = newpktdata;
  975. zstream.avail_out = pkt_size - zstream.total_out;
  976. zstream.next_out = pkt_data + zstream.total_out;
  977. result = inflate(&zstream, Z_NO_FLUSH);
  978. } while (result == Z_OK && pkt_size < 10000000);
  979. pkt_size = zstream.total_out;
  980. inflateEnd(&zstream);
  981. if (result != Z_STREAM_END) {
  982. if (result == Z_MEM_ERROR)
  983. result = AVERROR(ENOMEM);
  984. else
  985. result = AVERROR_INVALIDDATA;
  986. goto failed;
  987. }
  988. break;
  989. }
  990. #endif
  991. #if CONFIG_BZLIB
  992. case MATROSKA_TRACK_ENCODING_COMP_BZLIB:
  993. {
  994. bz_stream bzstream = { 0 };
  995. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  996. return -1;
  997. bzstream.next_in = data;
  998. bzstream.avail_in = isize;
  999. do {
  1000. pkt_size *= 3;
  1001. newpktdata = av_realloc(pkt_data, pkt_size);
  1002. if (!newpktdata) {
  1003. BZ2_bzDecompressEnd(&bzstream);
  1004. goto failed;
  1005. }
  1006. pkt_data = newpktdata;
  1007. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  1008. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  1009. result = BZ2_bzDecompress(&bzstream);
  1010. } while (result == BZ_OK && pkt_size < 10000000);
  1011. pkt_size = bzstream.total_out_lo32;
  1012. BZ2_bzDecompressEnd(&bzstream);
  1013. if (result != BZ_STREAM_END) {
  1014. if (result == BZ_MEM_ERROR)
  1015. result = AVERROR(ENOMEM);
  1016. else
  1017. result = AVERROR_INVALIDDATA;
  1018. goto failed;
  1019. }
  1020. break;
  1021. }
  1022. #endif
  1023. default:
  1024. return AVERROR_INVALIDDATA;
  1025. }
  1026. *buf = pkt_data;
  1027. *buf_size = pkt_size;
  1028. return 0;
  1029. failed:
  1030. av_free(pkt_data);
  1031. return result;
  1032. }
  1033. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  1034. AVPacket *pkt, uint64_t display_duration)
  1035. {
  1036. AVBufferRef *line;
  1037. char *layer, *ptr = pkt->data, *end = ptr + pkt->size;
  1038. for (; *ptr != ',' && ptr < end - 1; ptr++)
  1039. ;
  1040. if (*ptr == ',')
  1041. layer = ++ptr;
  1042. for (; *ptr != ',' && ptr < end - 1; ptr++)
  1043. ;
  1044. if (*ptr == ',') {
  1045. int64_t end_pts = pkt->pts + display_duration;
  1046. int sc = matroska->time_scale * pkt->pts / 10000000;
  1047. int ec = matroska->time_scale * end_pts / 10000000;
  1048. int sh, sm, ss, eh, em, es, len;
  1049. sh = sc / 360000;
  1050. sc -= 360000 * sh;
  1051. sm = sc / 6000;
  1052. sc -= 6000 * sm;
  1053. ss = sc / 100;
  1054. sc -= 100 * ss;
  1055. eh = ec / 360000;
  1056. ec -= 360000 * eh;
  1057. em = ec / 6000;
  1058. ec -= 6000 * em;
  1059. es = ec / 100;
  1060. ec -= 100 * es;
  1061. *ptr++ = '\0';
  1062. len = 50 + end - ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  1063. if (!(line = av_buffer_alloc(len)))
  1064. return;
  1065. snprintf(line->data, len,
  1066. "Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  1067. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  1068. av_buffer_unref(&pkt->buf);
  1069. pkt->buf = line;
  1070. pkt->data = line->data;
  1071. pkt->size = strlen(line->data);
  1072. }
  1073. }
  1074. static int matroska_merge_packets(AVPacket *out, AVPacket *in)
  1075. {
  1076. int old_size = out->size;
  1077. int ret = av_grow_packet(out, in->size);
  1078. if (ret < 0)
  1079. return ret;
  1080. memcpy(out->data + old_size, in->data, in->size);
  1081. av_free_packet(in);
  1082. av_free(in);
  1083. return 0;
  1084. }
  1085. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  1086. AVDictionary **metadata, char *prefix)
  1087. {
  1088. MatroskaTag *tags = list->elem;
  1089. char key[1024];
  1090. int i;
  1091. for (i = 0; i < list->nb_elem; i++) {
  1092. const char *lang = tags[i].lang &&
  1093. strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  1094. if (!tags[i].name) {
  1095. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1096. continue;
  1097. }
  1098. if (prefix)
  1099. snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1100. else
  1101. av_strlcpy(key, tags[i].name, sizeof(key));
  1102. if (tags[i].def || !lang) {
  1103. av_dict_set(metadata, key, tags[i].string, 0);
  1104. if (tags[i].sub.nb_elem)
  1105. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1106. }
  1107. if (lang) {
  1108. av_strlcat(key, "-", sizeof(key));
  1109. av_strlcat(key, lang, sizeof(key));
  1110. av_dict_set(metadata, key, tags[i].string, 0);
  1111. if (tags[i].sub.nb_elem)
  1112. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1113. }
  1114. }
  1115. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1116. }
  1117. static void matroska_convert_tags(AVFormatContext *s)
  1118. {
  1119. MatroskaDemuxContext *matroska = s->priv_data;
  1120. MatroskaTags *tags = matroska->tags.elem;
  1121. int i, j;
  1122. for (i = 0; i < matroska->tags.nb_elem; i++) {
  1123. if (tags[i].target.attachuid) {
  1124. MatroskaAttachment *attachment = matroska->attachments.elem;
  1125. for (j = 0; j < matroska->attachments.nb_elem; j++)
  1126. if (attachment[j].uid == tags[i].target.attachuid &&
  1127. attachment[j].stream)
  1128. matroska_convert_tag(s, &tags[i].tag,
  1129. &attachment[j].stream->metadata, NULL);
  1130. } else if (tags[i].target.chapteruid) {
  1131. MatroskaChapter *chapter = matroska->chapters.elem;
  1132. for (j = 0; j < matroska->chapters.nb_elem; j++)
  1133. if (chapter[j].uid == tags[i].target.chapteruid &&
  1134. chapter[j].chapter)
  1135. matroska_convert_tag(s, &tags[i].tag,
  1136. &chapter[j].chapter->metadata, NULL);
  1137. } else if (tags[i].target.trackuid) {
  1138. MatroskaTrack *track = matroska->tracks.elem;
  1139. for (j = 0; j < matroska->tracks.nb_elem; j++)
  1140. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1141. matroska_convert_tag(s, &tags[i].tag,
  1142. &track[j].stream->metadata, NULL);
  1143. } else {
  1144. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1145. tags[i].target.type);
  1146. }
  1147. }
  1148. }
  1149. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
  1150. int idx)
  1151. {
  1152. EbmlList *seekhead_list = &matroska->seekhead;
  1153. uint32_t level_up = matroska->level_up;
  1154. uint32_t saved_id = matroska->current_id;
  1155. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1156. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1157. MatroskaLevel level;
  1158. int64_t offset;
  1159. int ret = 0;
  1160. if (idx >= seekhead_list->nb_elem ||
  1161. seekhead[idx].id == MATROSKA_ID_SEEKHEAD ||
  1162. seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1163. return 0;
  1164. /* seek */
  1165. offset = seekhead[idx].pos + matroska->segment_start;
  1166. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1167. /* We don't want to lose our seekhead level, so we add
  1168. * a dummy. This is a crude hack. */
  1169. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1170. av_log(matroska->ctx, AV_LOG_INFO,
  1171. "Max EBML element depth (%d) reached, "
  1172. "cannot parse further.\n", EBML_MAX_DEPTH);
  1173. ret = AVERROR_INVALIDDATA;
  1174. } else {
  1175. level.start = 0;
  1176. level.length = (uint64_t) -1;
  1177. matroska->levels[matroska->num_levels] = level;
  1178. matroska->num_levels++;
  1179. matroska->current_id = 0;
  1180. ret = ebml_parse(matroska, matroska_segment, matroska);
  1181. /* remove dummy level */
  1182. while (matroska->num_levels) {
  1183. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1184. if (length == (uint64_t) -1)
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. /* seek back */
  1190. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1191. matroska->level_up = level_up;
  1192. matroska->current_id = saved_id;
  1193. return ret;
  1194. }
  1195. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1196. {
  1197. EbmlList *seekhead_list = &matroska->seekhead;
  1198. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1199. int i;
  1200. // we should not do any seeking in the streaming case
  1201. if (!matroska->ctx->pb->seekable ||
  1202. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1203. return;
  1204. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1205. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1206. if (seekhead[i].pos <= before_pos)
  1207. continue;
  1208. // defer cues parsing until we actually need cue data.
  1209. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1210. matroska->cues_parsing_deferred = 1;
  1211. continue;
  1212. }
  1213. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1214. break;
  1215. }
  1216. }
  1217. static void matroska_parse_cues(MatroskaDemuxContext *matroska)
  1218. {
  1219. EbmlList *seekhead_list = &matroska->seekhead;
  1220. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1221. EbmlList *index_list;
  1222. MatroskaIndex *index;
  1223. int index_scale = 1;
  1224. int i, j;
  1225. for (i = 0; i < seekhead_list->nb_elem; i++)
  1226. if (seekhead[i].id == MATROSKA_ID_CUES)
  1227. break;
  1228. assert(i <= seekhead_list->nb_elem);
  1229. matroska_parse_seekhead_entry(matroska, i);
  1230. index_list = &matroska->index;
  1231. index = index_list->elem;
  1232. if (index_list->nb_elem &&
  1233. index[0].time > 1E14 / matroska->time_scale) {
  1234. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1235. index_scale = matroska->time_scale;
  1236. }
  1237. for (i = 0; i < index_list->nb_elem; i++) {
  1238. EbmlList *pos_list = &index[i].pos;
  1239. MatroskaIndexPos *pos = pos_list->elem;
  1240. for (j = 0; j < pos_list->nb_elem; j++) {
  1241. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1242. pos[j].track);
  1243. if (track && track->stream)
  1244. av_add_index_entry(track->stream,
  1245. pos[j].pos + matroska->segment_start,
  1246. index[i].time / index_scale, 0, 0,
  1247. AVINDEX_KEYFRAME);
  1248. }
  1249. }
  1250. }
  1251. static int matroska_aac_profile(char *codec_id)
  1252. {
  1253. static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1254. int profile;
  1255. for (profile = 0; profile < FF_ARRAY_ELEMS(aac_profiles); profile++)
  1256. if (strstr(codec_id, aac_profiles[profile]))
  1257. break;
  1258. return profile + 1;
  1259. }
  1260. static int matroska_aac_sri(int samplerate)
  1261. {
  1262. int sri;
  1263. for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1264. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1265. break;
  1266. return sri;
  1267. }
  1268. static int matroska_read_header(AVFormatContext *s)
  1269. {
  1270. MatroskaDemuxContext *matroska = s->priv_data;
  1271. EbmlList *attachments_list = &matroska->attachments;
  1272. EbmlList *chapters_list = &matroska->chapters;
  1273. MatroskaAttachment *attachments;
  1274. MatroskaChapter *chapters;
  1275. MatroskaTrack *tracks;
  1276. uint64_t max_start = 0;
  1277. int64_t pos;
  1278. Ebml ebml = { 0 };
  1279. AVStream *st;
  1280. int i, j, res;
  1281. matroska->ctx = s;
  1282. /* First read the EBML header. */
  1283. if (ebml_parse(matroska, ebml_syntax, &ebml) ||
  1284. ebml.version > EBML_VERSION ||
  1285. ebml.max_size > sizeof(uint64_t) ||
  1286. ebml.id_length > sizeof(uint32_t) ||
  1287. ebml.doctype_version > 2) {
  1288. av_log(matroska->ctx, AV_LOG_ERROR,
  1289. "EBML header using unsupported features\n"
  1290. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1291. ebml.version, ebml.doctype, ebml.doctype_version);
  1292. ebml_free(ebml_syntax, &ebml);
  1293. return AVERROR_PATCHWELCOME;
  1294. }
  1295. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1296. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1297. break;
  1298. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1299. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1300. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1301. ebml_free(ebml_syntax, &ebml);
  1302. return AVERROR_INVALIDDATA;
  1303. }
  1304. }
  1305. ebml_free(ebml_syntax, &ebml);
  1306. /* The next thing is a segment. */
  1307. pos = avio_tell(matroska->ctx->pb);
  1308. res = ebml_parse(matroska, matroska_segments, matroska);
  1309. // try resyncing until we find a EBML_STOP type element.
  1310. while (res != 1) {
  1311. res = matroska_resync(matroska, pos);
  1312. if (res < 0)
  1313. return res;
  1314. pos = avio_tell(matroska->ctx->pb);
  1315. res = ebml_parse(matroska, matroska_segment, matroska);
  1316. }
  1317. matroska_execute_seekhead(matroska);
  1318. if (!matroska->time_scale)
  1319. matroska->time_scale = 1000000;
  1320. if (matroska->duration)
  1321. matroska->ctx->duration = matroska->duration * matroska->time_scale *
  1322. 1000 / AV_TIME_BASE;
  1323. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1324. tracks = matroska->tracks.elem;
  1325. for (i = 0; i < matroska->tracks.nb_elem; i++) {
  1326. MatroskaTrack *track = &tracks[i];
  1327. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1328. EbmlList *encodings_list = &track->encodings;
  1329. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1330. uint8_t *extradata = NULL;
  1331. int extradata_size = 0;
  1332. int extradata_offset = 0;
  1333. AVIOContext b;
  1334. /* Apply some sanity checks. */
  1335. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1336. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1337. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1338. av_log(matroska->ctx, AV_LOG_INFO,
  1339. "Unknown or unsupported track type %"PRIu64"\n",
  1340. track->type);
  1341. continue;
  1342. }
  1343. if (track->codec_id == NULL)
  1344. continue;
  1345. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1346. if (!track->default_duration && track->video.frame_rate > 0)
  1347. track->default_duration = 1000000000 / track->video.frame_rate;
  1348. if (!track->video.display_width)
  1349. track->video.display_width = track->video.pixel_width;
  1350. if (!track->video.display_height)
  1351. track->video.display_height = track->video.pixel_height;
  1352. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1353. if (!track->audio.out_samplerate)
  1354. track->audio.out_samplerate = track->audio.samplerate;
  1355. }
  1356. if (encodings_list->nb_elem > 1) {
  1357. av_log(matroska->ctx, AV_LOG_ERROR,
  1358. "Multiple combined encodings not supported");
  1359. } else if (encodings_list->nb_elem == 1) {
  1360. if (encodings[0].type ||
  1361. (
  1362. #if CONFIG_ZLIB
  1363. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1364. #endif
  1365. #if CONFIG_BZLIB
  1366. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1367. #endif
  1368. #if CONFIG_LZO
  1369. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1370. #endif
  1371. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
  1372. encodings[0].scope = 0;
  1373. av_log(matroska->ctx, AV_LOG_ERROR,
  1374. "Unsupported encoding type");
  1375. } else if (track->codec_priv.size && encodings[0].scope & 2) {
  1376. uint8_t *codec_priv = track->codec_priv.data;
  1377. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1378. &track->codec_priv.size,
  1379. track);
  1380. if (ret < 0) {
  1381. track->codec_priv.data = NULL;
  1382. track->codec_priv.size = 0;
  1383. av_log(matroska->ctx, AV_LOG_ERROR,
  1384. "Failed to decode codec private data\n");
  1385. }
  1386. if (codec_priv != track->codec_priv.data)
  1387. av_free(codec_priv);
  1388. }
  1389. }
  1390. for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
  1391. if (!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1392. strlen(ff_mkv_codec_tags[j].str))) {
  1393. codec_id = ff_mkv_codec_tags[j].id;
  1394. break;
  1395. }
  1396. }
  1397. st = track->stream = avformat_new_stream(s, NULL);
  1398. if (st == NULL)
  1399. return AVERROR(ENOMEM);
  1400. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
  1401. track->codec_priv.size >= 40 &&
  1402. track->codec_priv.data != NULL) {
  1403. track->ms_compat = 1;
  1404. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1405. codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  1406. track->video.fourcc);
  1407. extradata_offset = 40;
  1408. } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
  1409. track->codec_priv.size >= 14 &&
  1410. track->codec_priv.data != NULL) {
  1411. int ret;
  1412. ffio_init_context(&b, track->codec_priv.data,
  1413. track->codec_priv.size,
  1414. 0, NULL, NULL, NULL, NULL);
  1415. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1416. if (ret < 0)
  1417. return ret;
  1418. codec_id = st->codec->codec_id;
  1419. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1420. } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
  1421. (track->codec_priv.size >= 86) &&
  1422. (track->codec_priv.data != NULL)) {
  1423. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1424. codec_id = ff_codec_get_id(ff_codec_movvideo_tags,
  1425. track->video.fourcc);
  1426. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1427. switch (track->audio.bitdepth) {
  1428. case 8:
  1429. codec_id = AV_CODEC_ID_PCM_U8;
  1430. break;
  1431. case 24:
  1432. codec_id = AV_CODEC_ID_PCM_S24BE;
  1433. break;
  1434. case 32:
  1435. codec_id = AV_CODEC_ID_PCM_S32BE;
  1436. break;
  1437. }
  1438. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1439. switch (track->audio.bitdepth) {
  1440. case 8:
  1441. codec_id = AV_CODEC_ID_PCM_U8;
  1442. break;
  1443. case 24:
  1444. codec_id = AV_CODEC_ID_PCM_S24LE;
  1445. break;
  1446. case 32:
  1447. codec_id = AV_CODEC_ID_PCM_S32LE;
  1448. break;
  1449. }
  1450. } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
  1451. track->audio.bitdepth == 64) {
  1452. codec_id = AV_CODEC_ID_PCM_F64LE;
  1453. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1454. int profile = matroska_aac_profile(track->codec_id);
  1455. int sri = matroska_aac_sri(track->audio.samplerate);
  1456. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1457. if (extradata == NULL)
  1458. return AVERROR(ENOMEM);
  1459. extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
  1460. extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
  1461. if (strstr(track->codec_id, "SBR")) {
  1462. sri = matroska_aac_sri(track->audio.out_samplerate);
  1463. extradata[2] = 0x56;
  1464. extradata[3] = 0xE5;
  1465. extradata[4] = 0x80 | (sri << 3);
  1466. extradata_size = 5;
  1467. } else
  1468. extradata_size = 2;
  1469. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
  1470. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1471. * Create the "atom size", "tag", and "tag version" fields the
  1472. * decoder expects manually. */
  1473. extradata_size = 12 + track->codec_priv.size;
  1474. extradata = av_mallocz(extradata_size +
  1475. FF_INPUT_BUFFER_PADDING_SIZE);
  1476. if (extradata == NULL)
  1477. return AVERROR(ENOMEM);
  1478. AV_WB32(extradata, extradata_size);
  1479. memcpy(&extradata[4], "alac", 4);
  1480. AV_WB32(&extradata[8], 0);
  1481. memcpy(&extradata[12], track->codec_priv.data,
  1482. track->codec_priv.size);
  1483. } else if (codec_id == AV_CODEC_ID_TTA) {
  1484. extradata_size = 30;
  1485. extradata = av_mallocz(extradata_size);
  1486. if (extradata == NULL)
  1487. return AVERROR(ENOMEM);
  1488. ffio_init_context(&b, extradata, extradata_size, 1,
  1489. NULL, NULL, NULL, NULL);
  1490. avio_write(&b, "TTA1", 4);
  1491. avio_wl16(&b, 1);
  1492. avio_wl16(&b, track->audio.channels);
  1493. avio_wl16(&b, track->audio.bitdepth);
  1494. avio_wl32(&b, track->audio.out_samplerate);
  1495. avio_wl32(&b, matroska->ctx->duration *
  1496. track->audio.out_samplerate);
  1497. } else if (codec_id == AV_CODEC_ID_RV10 ||
  1498. codec_id == AV_CODEC_ID_RV20 ||
  1499. codec_id == AV_CODEC_ID_RV30 ||
  1500. codec_id == AV_CODEC_ID_RV40) {
  1501. extradata_offset = 26;
  1502. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1503. track->audio.out_samplerate = 8000;
  1504. track->audio.channels = 1;
  1505. } else if (codec_id == AV_CODEC_ID_RA_288 ||
  1506. codec_id == AV_CODEC_ID_COOK ||
  1507. codec_id == AV_CODEC_ID_ATRAC3 ||
  1508. codec_id == AV_CODEC_ID_SIPR) {
  1509. int flavor;
  1510. ffio_init_context(&b, track->codec_priv.data,
  1511. track->codec_priv.size,
  1512. 0, NULL, NULL, NULL, NULL);
  1513. avio_skip(&b, 22);
  1514. flavor = avio_rb16(&b);
  1515. track->audio.coded_framesize = avio_rb32(&b);
  1516. avio_skip(&b, 12);
  1517. track->audio.sub_packet_h = avio_rb16(&b);
  1518. track->audio.frame_size = avio_rb16(&b);
  1519. track->audio.sub_packet_size = avio_rb16(&b);
  1520. if (flavor <= 0 ||
  1521. track->audio.coded_framesize <= 0 ||
  1522. track->audio.sub_packet_h <= 0 ||
  1523. track->audio.frame_size <= 0 ||
  1524. track->audio.sub_packet_size <= 0)
  1525. return AVERROR_INVALIDDATA;
  1526. track->audio.buf = av_malloc(track->audio.frame_size *
  1527. track->audio.sub_packet_h);
  1528. if (codec_id == AV_CODEC_ID_RA_288) {
  1529. st->codec->block_align = track->audio.coded_framesize;
  1530. track->codec_priv.size = 0;
  1531. } else {
  1532. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1533. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1534. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1535. st->codec->bit_rate = sipr_bit_rate[flavor];
  1536. }
  1537. st->codec->block_align = track->audio.sub_packet_size;
  1538. extradata_offset = 78;
  1539. }
  1540. }
  1541. track->codec_priv.size -= extradata_offset;
  1542. if (codec_id == AV_CODEC_ID_NONE)
  1543. av_log(matroska->ctx, AV_LOG_INFO,
  1544. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1545. if (track->time_scale < 0.01)
  1546. track->time_scale = 1.0;
  1547. avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
  1548. 1000 * 1000 * 1000); /* 64 bit pts in ns */
  1549. st->codec->codec_id = codec_id;
  1550. st->start_time = 0;
  1551. if (strcmp(track->language, "und"))
  1552. av_dict_set(&st->metadata, "language", track->language, 0);
  1553. av_dict_set(&st->metadata, "title", track->name, 0);
  1554. if (track->flag_default)
  1555. st->disposition |= AV_DISPOSITION_DEFAULT;
  1556. if (track->flag_forced)
  1557. st->disposition |= AV_DISPOSITION_FORCED;
  1558. if (!st->codec->extradata) {
  1559. if (extradata) {
  1560. st->codec->extradata = extradata;
  1561. st->codec->extradata_size = extradata_size;
  1562. } else if (track->codec_priv.data && track->codec_priv.size > 0) {
  1563. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1564. FF_INPUT_BUFFER_PADDING_SIZE);
  1565. if (st->codec->extradata == NULL)
  1566. return AVERROR(ENOMEM);
  1567. st->codec->extradata_size = track->codec_priv.size;
  1568. memcpy(st->codec->extradata,
  1569. track->codec_priv.data + extradata_offset,
  1570. track->codec_priv.size);
  1571. }
  1572. }
  1573. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1574. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1575. st->codec->codec_tag = track->video.fourcc;
  1576. st->codec->width = track->video.pixel_width;
  1577. st->codec->height = track->video.pixel_height;
  1578. av_reduce(&st->sample_aspect_ratio.num,
  1579. &st->sample_aspect_ratio.den,
  1580. st->codec->height * track->video.display_width,
  1581. st->codec->width * track->video.display_height,
  1582. 255);
  1583. if (st->codec->codec_id != AV_CODEC_ID_H264 &&
  1584. st->codec->codec_id != AV_CODEC_ID_HEVC)
  1585. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1586. if (track->default_duration) {
  1587. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1588. 1000000000, track->default_duration, 30000);
  1589. }
  1590. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1591. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1592. st->codec->sample_rate = track->audio.out_samplerate;
  1593. st->codec->channels = track->audio.channels;
  1594. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1595. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1596. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1597. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1598. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1599. matroska->contains_ssa = 1;
  1600. }
  1601. }
  1602. attachments = attachments_list->elem;
  1603. for (j = 0; j < attachments_list->nb_elem; j++) {
  1604. if (!(attachments[j].filename && attachments[j].mime &&
  1605. attachments[j].bin.data && attachments[j].bin.size > 0)) {
  1606. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1607. } else {
  1608. AVStream *st = avformat_new_stream(s, NULL);
  1609. if (st == NULL)
  1610. break;
  1611. av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
  1612. av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
  1613. st->codec->codec_id = AV_CODEC_ID_NONE;
  1614. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1615. st->codec->extradata = av_malloc(attachments[j].bin.size);
  1616. if (st->codec->extradata == NULL)
  1617. break;
  1618. st->codec->extradata_size = attachments[j].bin.size;
  1619. memcpy(st->codec->extradata, attachments[j].bin.data,
  1620. attachments[j].bin.size);
  1621. for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1622. if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
  1623. strlen(ff_mkv_mime_tags[i].str))) {
  1624. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1625. break;
  1626. }
  1627. }
  1628. attachments[j].stream = st;
  1629. }
  1630. }
  1631. chapters = chapters_list->elem;
  1632. for (i = 0; i < chapters_list->nb_elem; i++)
  1633. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
  1634. (max_start == 0 || chapters[i].start > max_start)) {
  1635. chapters[i].chapter =
  1636. avpriv_new_chapter(s, chapters[i].uid,
  1637. (AVRational) { 1, 1000000000 },
  1638. chapters[i].start, chapters[i].end,
  1639. chapters[i].title);
  1640. av_dict_set(&chapters[i].chapter->metadata,
  1641. "title", chapters[i].title, 0);
  1642. max_start = chapters[i].start;
  1643. }
  1644. matroska_convert_tags(s);
  1645. return 0;
  1646. }
  1647. /*
  1648. * Put one packet in an application-supplied AVPacket struct.
  1649. * Returns 0 on success or -1 on failure.
  1650. */
  1651. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1652. AVPacket *pkt)
  1653. {
  1654. if (matroska->num_packets > 0) {
  1655. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1656. av_free(matroska->packets[0]);
  1657. if (matroska->num_packets > 1) {
  1658. void *newpackets;
  1659. memmove(&matroska->packets[0], &matroska->packets[1],
  1660. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1661. newpackets = av_realloc(matroska->packets,
  1662. (matroska->num_packets - 1) *
  1663. sizeof(AVPacket *));
  1664. if (newpackets)
  1665. matroska->packets = newpackets;
  1666. } else {
  1667. av_freep(&matroska->packets);
  1668. matroska->prev_pkt = NULL;
  1669. }
  1670. matroska->num_packets--;
  1671. return 0;
  1672. }
  1673. return -1;
  1674. }
  1675. /*
  1676. * Free all packets in our internal queue.
  1677. */
  1678. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1679. {
  1680. matroska->prev_pkt = NULL;
  1681. if (matroska->packets) {
  1682. int n;
  1683. for (n = 0; n < matroska->num_packets; n++) {
  1684. av_free_packet(matroska->packets[n]);
  1685. av_free(matroska->packets[n]);
  1686. }
  1687. av_freep(&matroska->packets);
  1688. matroska->num_packets = 0;
  1689. }
  1690. }
  1691. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1692. int *buf_size, int type,
  1693. uint32_t **lace_buf, int *laces)
  1694. {
  1695. int res = 0, n, size = *buf_size;
  1696. uint8_t *data = *buf;
  1697. uint32_t *lace_size;
  1698. if (!type) {
  1699. *laces = 1;
  1700. *lace_buf = av_mallocz(sizeof(int));
  1701. if (!*lace_buf)
  1702. return AVERROR(ENOMEM);
  1703. *lace_buf[0] = size;
  1704. return 0;
  1705. }
  1706. assert(size > 0);
  1707. *laces = *data + 1;
  1708. data += 1;
  1709. size -= 1;
  1710. lace_size = av_mallocz(*laces * sizeof(int));
  1711. if (!lace_size)
  1712. return AVERROR(ENOMEM);
  1713. switch (type) {
  1714. case 0x1: /* Xiph lacing */
  1715. {
  1716. uint8_t temp;
  1717. uint32_t total = 0;
  1718. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1719. while (1) {
  1720. if (size == 0) {
  1721. res = AVERROR_EOF;
  1722. break;
  1723. }
  1724. temp = *data;
  1725. lace_size[n] += temp;
  1726. data += 1;
  1727. size -= 1;
  1728. if (temp != 0xff)
  1729. break;
  1730. }
  1731. total += lace_size[n];
  1732. }
  1733. if (size <= total) {
  1734. res = AVERROR_INVALIDDATA;
  1735. break;
  1736. }
  1737. lace_size[n] = size - total;
  1738. break;
  1739. }
  1740. case 0x2: /* fixed-size lacing */
  1741. if (size % (*laces)) {
  1742. res = AVERROR_INVALIDDATA;
  1743. break;
  1744. }
  1745. for (n = 0; n < *laces; n++)
  1746. lace_size[n] = size / *laces;
  1747. break;
  1748. case 0x3: /* EBML lacing */
  1749. {
  1750. uint64_t num;
  1751. uint64_t total;
  1752. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1753. if (n < 0) {
  1754. av_log(matroska->ctx, AV_LOG_INFO,
  1755. "EBML block data error\n");
  1756. res = n;
  1757. break;
  1758. }
  1759. data += n;
  1760. size -= n;
  1761. total = lace_size[0] = num;
  1762. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1763. int64_t snum;
  1764. int r;
  1765. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1766. if (r < 0) {
  1767. av_log(matroska->ctx, AV_LOG_INFO,
  1768. "EBML block data error\n");
  1769. res = r;
  1770. break;
  1771. }
  1772. data += r;
  1773. size -= r;
  1774. lace_size[n] = lace_size[n - 1] + snum;
  1775. total += lace_size[n];
  1776. }
  1777. if (size <= total) {
  1778. res = AVERROR_INVALIDDATA;
  1779. break;
  1780. }
  1781. lace_size[*laces - 1] = size - total;
  1782. break;
  1783. }
  1784. }
  1785. *buf = data;
  1786. *lace_buf = lace_size;
  1787. *buf_size = size;
  1788. return res;
  1789. }
  1790. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1791. MatroskaTrack *track, AVStream *st,
  1792. uint8_t *data, int size, uint64_t timecode,
  1793. uint64_t duration, int64_t pos)
  1794. {
  1795. int a = st->codec->block_align;
  1796. int sps = track->audio.sub_packet_size;
  1797. int cfs = track->audio.coded_framesize;
  1798. int h = track->audio.sub_packet_h;
  1799. int y = track->audio.sub_packet_cnt;
  1800. int w = track->audio.frame_size;
  1801. int x;
  1802. if (!track->audio.pkt_cnt) {
  1803. if (track->audio.sub_packet_cnt == 0)
  1804. track->audio.buf_timecode = timecode;
  1805. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1806. if (size < cfs * h / 2) {
  1807. av_log(matroska->ctx, AV_LOG_ERROR,
  1808. "Corrupt int4 RM-style audio packet size\n");
  1809. return AVERROR_INVALIDDATA;
  1810. }
  1811. for (x = 0; x < h / 2; x++)
  1812. memcpy(track->audio.buf + x * 2 * w + y * cfs,
  1813. data + x * cfs, cfs);
  1814. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1815. if (size < w) {
  1816. av_log(matroska->ctx, AV_LOG_ERROR,
  1817. "Corrupt sipr RM-style audio packet size\n");
  1818. return AVERROR_INVALIDDATA;
  1819. }
  1820. memcpy(track->audio.buf + y * w, data, w);
  1821. } else {
  1822. if (size < sps * w / sps) {
  1823. av_log(matroska->ctx, AV_LOG_ERROR,
  1824. "Corrupt generic RM-style audio packet size\n");
  1825. return AVERROR_INVALIDDATA;
  1826. }
  1827. for (x = 0; x < w / sps; x++)
  1828. memcpy(track->audio.buf +
  1829. sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
  1830. data + x * sps, sps);
  1831. }
  1832. if (++track->audio.sub_packet_cnt >= h) {
  1833. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1834. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1835. track->audio.sub_packet_cnt = 0;
  1836. track->audio.pkt_cnt = h * w / a;
  1837. }
  1838. }
  1839. while (track->audio.pkt_cnt) {
  1840. AVPacket *pkt = av_mallocz(sizeof(AVPacket));
  1841. av_new_packet(pkt, a);
  1842. memcpy(pkt->data,
  1843. track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
  1844. a);
  1845. pkt->pts = track->audio.buf_timecode;
  1846. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1847. pkt->pos = pos;
  1848. pkt->stream_index = st->index;
  1849. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  1850. }
  1851. return 0;
  1852. }
  1853. /* reconstruct full wavpack blocks from mangled matroska ones */
  1854. static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
  1855. uint8_t **pdst, int *size)
  1856. {
  1857. uint8_t *dst = NULL;
  1858. int dstlen = 0;
  1859. int srclen = *size;
  1860. uint32_t samples;
  1861. uint16_t ver;
  1862. int ret, offset = 0;
  1863. if (srclen < 12 || track->stream->codec->extradata_size < 2)
  1864. return AVERROR_INVALIDDATA;
  1865. ver = AV_RL16(track->stream->codec->extradata);
  1866. samples = AV_RL32(src);
  1867. src += 4;
  1868. srclen -= 4;
  1869. while (srclen >= 8) {
  1870. int multiblock;
  1871. uint32_t blocksize;
  1872. uint8_t *tmp;
  1873. uint32_t flags = AV_RL32(src);
  1874. uint32_t crc = AV_RL32(src + 4);
  1875. src += 8;
  1876. srclen -= 8;
  1877. multiblock = (flags & 0x1800) != 0x1800;
  1878. if (multiblock) {
  1879. if (srclen < 4) {
  1880. ret = AVERROR_INVALIDDATA;
  1881. goto fail;
  1882. }
  1883. blocksize = AV_RL32(src);
  1884. src += 4;
  1885. srclen -= 4;
  1886. } else
  1887. blocksize = srclen;
  1888. if (blocksize > srclen) {
  1889. ret = AVERROR_INVALIDDATA;
  1890. goto fail;
  1891. }
  1892. tmp = av_realloc(dst, dstlen + blocksize + 32);
  1893. if (!tmp) {
  1894. ret = AVERROR(ENOMEM);
  1895. goto fail;
  1896. }
  1897. dst = tmp;
  1898. dstlen += blocksize + 32;
  1899. AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
  1900. AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
  1901. AV_WL16(dst + offset + 8, ver); // version
  1902. AV_WL16(dst + offset + 10, 0); // track/index_no
  1903. AV_WL32(dst + offset + 12, 0); // total samples
  1904. AV_WL32(dst + offset + 16, 0); // block index
  1905. AV_WL32(dst + offset + 20, samples); // number of samples
  1906. AV_WL32(dst + offset + 24, flags); // flags
  1907. AV_WL32(dst + offset + 28, crc); // crc
  1908. memcpy(dst + offset + 32, src, blocksize); // block data
  1909. src += blocksize;
  1910. srclen -= blocksize;
  1911. offset += blocksize + 32;
  1912. }
  1913. *pdst = dst;
  1914. *size = dstlen;
  1915. return 0;
  1916. fail:
  1917. av_freep(&dst);
  1918. return ret;
  1919. }
  1920. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  1921. MatroskaTrack *track, AVStream *st,
  1922. uint8_t *data, int pkt_size,
  1923. uint64_t timecode, uint64_t duration,
  1924. int64_t pos, int is_keyframe)
  1925. {
  1926. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1927. uint8_t *pkt_data = data;
  1928. int offset = 0, res;
  1929. AVPacket *pkt;
  1930. if (encodings && encodings->scope & 1) {
  1931. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  1932. if (res < 0)
  1933. return res;
  1934. }
  1935. if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
  1936. uint8_t *wv_data;
  1937. res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
  1938. if (res < 0) {
  1939. av_log(matroska->ctx, AV_LOG_ERROR,
  1940. "Error parsing a wavpack block.\n");
  1941. goto fail;
  1942. }
  1943. if (pkt_data != data)
  1944. av_freep(&pkt_data);
  1945. pkt_data = wv_data;
  1946. }
  1947. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  1948. offset = 8;
  1949. pkt = av_mallocz(sizeof(AVPacket));
  1950. /* XXX: prevent data copy... */
  1951. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  1952. av_free(pkt);
  1953. return AVERROR(ENOMEM);
  1954. }
  1955. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  1956. uint8_t *buf = pkt->data;
  1957. bytestream_put_be32(&buf, pkt_size);
  1958. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  1959. }
  1960. memcpy(pkt->data + offset, pkt_data, pkt_size);
  1961. if (pkt_data != data)
  1962. av_free(pkt_data);
  1963. pkt->flags = is_keyframe;
  1964. pkt->stream_index = st->index;
  1965. if (track->ms_compat)
  1966. pkt->dts = timecode;
  1967. else
  1968. pkt->pts = timecode;
  1969. pkt->pos = pos;
  1970. if (st->codec->codec_id == AV_CODEC_ID_TEXT)
  1971. pkt->convergence_duration = duration;
  1972. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1973. pkt->duration = duration;
  1974. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1975. matroska_fix_ass_packet(matroska, pkt, duration);
  1976. if (matroska->prev_pkt &&
  1977. timecode != AV_NOPTS_VALUE &&
  1978. matroska->prev_pkt->pts == timecode &&
  1979. matroska->prev_pkt->stream_index == st->index &&
  1980. st->codec->codec_id == AV_CODEC_ID_SSA)
  1981. matroska_merge_packets(matroska->prev_pkt, pkt);
  1982. else {
  1983. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  1984. matroska->prev_pkt = pkt;
  1985. }
  1986. return 0;
  1987. fail:
  1988. if (pkt_data != data)
  1989. av_freep(&pkt_data);
  1990. return res;
  1991. }
  1992. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1993. int size, int64_t pos, uint64_t cluster_time,
  1994. uint64_t block_duration, int is_keyframe,
  1995. int64_t cluster_pos)
  1996. {
  1997. uint64_t timecode = AV_NOPTS_VALUE;
  1998. MatroskaTrack *track;
  1999. int res = 0;
  2000. AVStream *st;
  2001. int16_t block_time;
  2002. uint32_t *lace_size = NULL;
  2003. int n, flags, laces = 0;
  2004. uint64_t num, duration;
  2005. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  2006. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  2007. return n;
  2008. }
  2009. data += n;
  2010. size -= n;
  2011. track = matroska_find_track_by_num(matroska, num);
  2012. if (!track || !track->stream) {
  2013. av_log(matroska->ctx, AV_LOG_INFO,
  2014. "Invalid stream %"PRIu64" or size %u\n", num, size);
  2015. return AVERROR_INVALIDDATA;
  2016. } else if (size <= 3)
  2017. return 0;
  2018. st = track->stream;
  2019. if (st->discard >= AVDISCARD_ALL)
  2020. return res;
  2021. block_time = AV_RB16(data);
  2022. data += 2;
  2023. flags = *data++;
  2024. size -= 3;
  2025. if (is_keyframe == -1)
  2026. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  2027. if (cluster_time != (uint64_t) -1 &&
  2028. (block_time >= 0 || cluster_time >= -block_time)) {
  2029. timecode = cluster_time + block_time;
  2030. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
  2031. timecode < track->end_timecode)
  2032. is_keyframe = 0; /* overlapping subtitles are not key frame */
  2033. if (is_keyframe)
  2034. av_add_index_entry(st, cluster_pos, timecode, 0, 0,
  2035. AVINDEX_KEYFRAME);
  2036. }
  2037. if (matroska->skip_to_keyframe &&
  2038. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  2039. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  2040. return res;
  2041. matroska->skip_to_keyframe = 0;
  2042. }
  2043. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  2044. &lace_size, &laces);
  2045. if (res)
  2046. goto end;
  2047. if (block_duration != AV_NOPTS_VALUE) {
  2048. duration = block_duration / laces;
  2049. if (block_duration != duration * laces) {
  2050. av_log(matroska->ctx, AV_LOG_WARNING,
  2051. "Incorrect block_duration, possibly corrupted container");
  2052. }
  2053. } else {
  2054. duration = track->default_duration / matroska->time_scale;
  2055. block_duration = duration * laces;
  2056. }
  2057. if (timecode != AV_NOPTS_VALUE)
  2058. track->end_timecode =
  2059. FFMAX(track->end_timecode, timecode + block_duration);
  2060. for (n = 0; n < laces; n++) {
  2061. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  2062. st->codec->codec_id == AV_CODEC_ID_COOK ||
  2063. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  2064. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  2065. st->codec->block_align && track->audio.sub_packet_size) {
  2066. res = matroska_parse_rm_audio(matroska, track, st, data,
  2067. lace_size[n],
  2068. timecode, duration, pos);
  2069. if (res)
  2070. goto end;
  2071. } else {
  2072. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  2073. timecode, duration, pos,
  2074. !n ? is_keyframe : 0);
  2075. if (res)
  2076. goto end;
  2077. }
  2078. if (timecode != AV_NOPTS_VALUE)
  2079. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  2080. data += lace_size[n];
  2081. }
  2082. end:
  2083. av_free(lace_size);
  2084. return res;
  2085. }
  2086. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2087. {
  2088. EbmlList *blocks_list;
  2089. MatroskaBlock *blocks;
  2090. int i, res;
  2091. res = ebml_parse(matroska,
  2092. matroska_cluster_incremental_parsing,
  2093. &matroska->current_cluster);
  2094. if (res == 1) {
  2095. /* New Cluster */
  2096. if (matroska->current_cluster_pos)
  2097. ebml_level_end(matroska);
  2098. ebml_free(matroska_cluster, &matroska->current_cluster);
  2099. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2100. matroska->current_cluster_num_blocks = 0;
  2101. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2102. matroska->prev_pkt = NULL;
  2103. /* sizeof the ID which was already read */
  2104. if (matroska->current_id)
  2105. matroska->current_cluster_pos -= 4;
  2106. res = ebml_parse(matroska,
  2107. matroska_clusters_incremental,
  2108. &matroska->current_cluster);
  2109. /* Try parsing the block again. */
  2110. if (res == 1)
  2111. res = ebml_parse(matroska,
  2112. matroska_cluster_incremental_parsing,
  2113. &matroska->current_cluster);
  2114. }
  2115. if (!res &&
  2116. matroska->current_cluster_num_blocks <
  2117. matroska->current_cluster.blocks.nb_elem) {
  2118. blocks_list = &matroska->current_cluster.blocks;
  2119. blocks = blocks_list->elem;
  2120. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2121. i = blocks_list->nb_elem - 1;
  2122. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2123. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2124. if (!blocks[i].non_simple)
  2125. blocks[i].duration = AV_NOPTS_VALUE;
  2126. res = matroska_parse_block(matroska, blocks[i].bin.data,
  2127. blocks[i].bin.size, blocks[i].bin.pos,
  2128. matroska->current_cluster.timecode,
  2129. blocks[i].duration, is_keyframe,
  2130. matroska->current_cluster_pos);
  2131. }
  2132. }
  2133. if (res < 0)
  2134. matroska->done = 1;
  2135. return res;
  2136. }
  2137. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2138. {
  2139. MatroskaCluster cluster = { 0 };
  2140. EbmlList *blocks_list;
  2141. MatroskaBlock *blocks;
  2142. int i, res;
  2143. int64_t pos;
  2144. if (!matroska->contains_ssa)
  2145. return matroska_parse_cluster_incremental(matroska);
  2146. pos = avio_tell(matroska->ctx->pb);
  2147. matroska->prev_pkt = NULL;
  2148. if (matroska->current_id)
  2149. pos -= 4; /* sizeof the ID which was already read */
  2150. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2151. blocks_list = &cluster.blocks;
  2152. blocks = blocks_list->elem;
  2153. for (i = 0; i < blocks_list->nb_elem && !res; i++)
  2154. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2155. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2156. if (!blocks[i].non_simple)
  2157. blocks[i].duration = AV_NOPTS_VALUE;
  2158. res = matroska_parse_block(matroska, blocks[i].bin.data,
  2159. blocks[i].bin.size, blocks[i].bin.pos,
  2160. cluster.timecode, blocks[i].duration,
  2161. is_keyframe, pos);
  2162. }
  2163. ebml_free(matroska_cluster, &cluster);
  2164. return res;
  2165. }
  2166. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2167. {
  2168. MatroskaDemuxContext *matroska = s->priv_data;
  2169. int ret = 0;
  2170. while (!ret && matroska_deliver_packet(matroska, pkt)) {
  2171. int64_t pos = avio_tell(matroska->ctx->pb);
  2172. if (matroska->done)
  2173. return AVERROR_EOF;
  2174. if (matroska_parse_cluster(matroska) < 0)
  2175. ret = matroska_resync(matroska, pos);
  2176. }
  2177. if (ret == AVERROR_INVALIDDATA && pkt->data) {
  2178. pkt->flags |= AV_PKT_FLAG_CORRUPT;
  2179. return 0;
  2180. }
  2181. return ret;
  2182. }
  2183. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2184. int64_t timestamp, int flags)
  2185. {
  2186. MatroskaDemuxContext *matroska = s->priv_data;
  2187. MatroskaTrack *tracks = matroska->tracks.elem;
  2188. AVStream *st = s->streams[stream_index];
  2189. int i, index, index_sub, index_min;
  2190. /* Parse the CUES now since we need the index data to seek. */
  2191. if (matroska->cues_parsing_deferred) {
  2192. matroska_parse_cues(matroska);
  2193. matroska->cues_parsing_deferred = 0;
  2194. }
  2195. if (!st->nb_index_entries)
  2196. return 0;
  2197. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2198. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2199. avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
  2200. SEEK_SET);
  2201. matroska->current_id = 0;
  2202. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2203. matroska_clear_queue(matroska);
  2204. if (matroska_parse_cluster(matroska) < 0)
  2205. break;
  2206. }
  2207. }
  2208. matroska_clear_queue(matroska);
  2209. if (index < 0)
  2210. return 0;
  2211. index_min = index;
  2212. for (i = 0; i < matroska->tracks.nb_elem; i++) {
  2213. tracks[i].audio.pkt_cnt = 0;
  2214. tracks[i].audio.sub_packet_cnt = 0;
  2215. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2216. tracks[i].end_timecode = 0;
  2217. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
  2218. !tracks[i].stream->discard != AVDISCARD_ALL) {
  2219. index_sub = av_index_search_timestamp(
  2220. tracks[i].stream, st->index_entries[index].timestamp,
  2221. AVSEEK_FLAG_BACKWARD);
  2222. if (index_sub >= 0 &&
  2223. st->index_entries[index_sub].pos < st->index_entries[index_min].pos &&
  2224. st->index_entries[index].timestamp -
  2225. st->index_entries[index_sub].timestamp < 30000000000 / matroska->time_scale)
  2226. index_min = index_sub;
  2227. }
  2228. }
  2229. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2230. matroska->current_id = 0;
  2231. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2232. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2233. matroska->done = 0;
  2234. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2235. return 0;
  2236. }
  2237. static int matroska_read_close(AVFormatContext *s)
  2238. {
  2239. MatroskaDemuxContext *matroska = s->priv_data;
  2240. MatroskaTrack *tracks = matroska->tracks.elem;
  2241. int n;
  2242. matroska_clear_queue(matroska);
  2243. for (n = 0; n < matroska->tracks.nb_elem; n++)
  2244. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2245. av_free(tracks[n].audio.buf);
  2246. ebml_free(matroska_cluster, &matroska->current_cluster);
  2247. ebml_free(matroska_segment, matroska);
  2248. return 0;
  2249. }
  2250. AVInputFormat ff_matroska_demuxer = {
  2251. .name = "matroska,webm",
  2252. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2253. .priv_data_size = sizeof(MatroskaDemuxContext),
  2254. .read_probe = matroska_probe,
  2255. .read_header = matroska_read_header,
  2256. .read_packet = matroska_read_packet,
  2257. .read_close = matroska_read_close,
  2258. .read_seek = matroska_read_seek,
  2259. };