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.

2552 lines
88KB

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