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.

2541 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 "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_read_header(AVFormatContext *s)
  1272. {
  1273. MatroskaDemuxContext *matroska = s->priv_data;
  1274. EbmlList *attachments_list = &matroska->attachments;
  1275. EbmlList *chapters_list = &matroska->chapters;
  1276. MatroskaAttachment *attachments;
  1277. MatroskaChapter *chapters;
  1278. MatroskaTrack *tracks;
  1279. uint64_t max_start = 0;
  1280. int64_t pos;
  1281. Ebml ebml = { 0 };
  1282. AVStream *st;
  1283. int i, j, res;
  1284. matroska->ctx = s;
  1285. /* First read the EBML header. */
  1286. if (ebml_parse(matroska, ebml_syntax, &ebml) ||
  1287. ebml.version > EBML_VERSION ||
  1288. ebml.max_size > sizeof(uint64_t) ||
  1289. ebml.id_length > sizeof(uint32_t) ||
  1290. ebml.doctype_version > 2) {
  1291. av_log(matroska->ctx, AV_LOG_ERROR,
  1292. "EBML header using unsupported features\n"
  1293. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1294. ebml.version, ebml.doctype, ebml.doctype_version);
  1295. ebml_free(ebml_syntax, &ebml);
  1296. return AVERROR_PATCHWELCOME;
  1297. }
  1298. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1299. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1300. break;
  1301. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1302. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1303. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1304. ebml_free(ebml_syntax, &ebml);
  1305. return AVERROR_INVALIDDATA;
  1306. }
  1307. }
  1308. ebml_free(ebml_syntax, &ebml);
  1309. /* The next thing is a segment. */
  1310. pos = avio_tell(matroska->ctx->pb);
  1311. res = ebml_parse(matroska, matroska_segments, matroska);
  1312. // try resyncing until we find a EBML_STOP type element.
  1313. while (res != 1) {
  1314. res = matroska_resync(matroska, pos);
  1315. if (res < 0)
  1316. return res;
  1317. pos = avio_tell(matroska->ctx->pb);
  1318. res = ebml_parse(matroska, matroska_segment, matroska);
  1319. }
  1320. matroska_execute_seekhead(matroska);
  1321. if (!matroska->time_scale)
  1322. matroska->time_scale = 1000000;
  1323. if (matroska->duration)
  1324. matroska->ctx->duration = matroska->duration * matroska->time_scale *
  1325. 1000 / AV_TIME_BASE;
  1326. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1327. tracks = matroska->tracks.elem;
  1328. for (i = 0; i < matroska->tracks.nb_elem; i++) {
  1329. MatroskaTrack *track = &tracks[i];
  1330. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1331. EbmlList *encodings_list = &track->encodings;
  1332. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1333. uint8_t *extradata = NULL;
  1334. int extradata_size = 0;
  1335. int extradata_offset = 0;
  1336. AVIOContext b;
  1337. /* Apply some sanity checks. */
  1338. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1339. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1340. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1341. av_log(matroska->ctx, AV_LOG_INFO,
  1342. "Unknown or unsupported track type %"PRIu64"\n",
  1343. track->type);
  1344. continue;
  1345. }
  1346. if (track->codec_id == NULL)
  1347. continue;
  1348. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1349. if (!track->default_duration && track->video.frame_rate > 0)
  1350. track->default_duration = 1000000000 / track->video.frame_rate;
  1351. if (!track->video.display_width)
  1352. track->video.display_width = track->video.pixel_width;
  1353. if (!track->video.display_height)
  1354. track->video.display_height = track->video.pixel_height;
  1355. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1356. if (!track->audio.out_samplerate)
  1357. track->audio.out_samplerate = track->audio.samplerate;
  1358. }
  1359. if (encodings_list->nb_elem > 1) {
  1360. av_log(matroska->ctx, AV_LOG_ERROR,
  1361. "Multiple combined encodings not supported");
  1362. } else if (encodings_list->nb_elem == 1) {
  1363. if (encodings[0].type ||
  1364. (
  1365. #if CONFIG_ZLIB
  1366. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1367. #endif
  1368. #if CONFIG_BZLIB
  1369. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1370. #endif
  1371. #if CONFIG_LZO
  1372. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1373. #endif
  1374. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
  1375. encodings[0].scope = 0;
  1376. av_log(matroska->ctx, AV_LOG_ERROR,
  1377. "Unsupported encoding type");
  1378. } else if (track->codec_priv.size && encodings[0].scope & 2) {
  1379. uint8_t *codec_priv = track->codec_priv.data;
  1380. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1381. &track->codec_priv.size,
  1382. track);
  1383. if (ret < 0) {
  1384. track->codec_priv.data = NULL;
  1385. track->codec_priv.size = 0;
  1386. av_log(matroska->ctx, AV_LOG_ERROR,
  1387. "Failed to decode codec private data\n");
  1388. }
  1389. if (codec_priv != track->codec_priv.data)
  1390. av_free(codec_priv);
  1391. }
  1392. }
  1393. for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
  1394. if (!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1395. strlen(ff_mkv_codec_tags[j].str))) {
  1396. codec_id = ff_mkv_codec_tags[j].id;
  1397. break;
  1398. }
  1399. }
  1400. st = track->stream = avformat_new_stream(s, NULL);
  1401. if (st == NULL)
  1402. return AVERROR(ENOMEM);
  1403. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
  1404. track->codec_priv.size >= 40 &&
  1405. track->codec_priv.data != NULL) {
  1406. track->ms_compat = 1;
  1407. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1408. codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  1409. track->video.fourcc);
  1410. extradata_offset = 40;
  1411. } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
  1412. track->codec_priv.size >= 14 &&
  1413. track->codec_priv.data != NULL) {
  1414. int ret;
  1415. ffio_init_context(&b, track->codec_priv.data,
  1416. track->codec_priv.size,
  1417. 0, NULL, NULL, NULL, NULL);
  1418. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1419. if (ret < 0)
  1420. return ret;
  1421. codec_id = st->codec->codec_id;
  1422. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1423. } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
  1424. (track->codec_priv.size >= 86) &&
  1425. (track->codec_priv.data != NULL)) {
  1426. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1427. codec_id = ff_codec_get_id(ff_codec_movvideo_tags,
  1428. track->video.fourcc);
  1429. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1430. switch (track->audio.bitdepth) {
  1431. case 8:
  1432. codec_id = AV_CODEC_ID_PCM_U8;
  1433. break;
  1434. case 24:
  1435. codec_id = AV_CODEC_ID_PCM_S24BE;
  1436. break;
  1437. case 32:
  1438. codec_id = AV_CODEC_ID_PCM_S32BE;
  1439. break;
  1440. }
  1441. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1442. switch (track->audio.bitdepth) {
  1443. case 8:
  1444. codec_id = AV_CODEC_ID_PCM_U8;
  1445. break;
  1446. case 24:
  1447. codec_id = AV_CODEC_ID_PCM_S24LE;
  1448. break;
  1449. case 32:
  1450. codec_id = AV_CODEC_ID_PCM_S32LE;
  1451. break;
  1452. }
  1453. } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
  1454. track->audio.bitdepth == 64) {
  1455. codec_id = AV_CODEC_ID_PCM_F64LE;
  1456. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1457. int profile = matroska_aac_profile(track->codec_id);
  1458. int sri = matroska_aac_sri(track->audio.samplerate);
  1459. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1460. if (extradata == NULL)
  1461. return AVERROR(ENOMEM);
  1462. extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
  1463. extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
  1464. if (strstr(track->codec_id, "SBR")) {
  1465. sri = matroska_aac_sri(track->audio.out_samplerate);
  1466. extradata[2] = 0x56;
  1467. extradata[3] = 0xE5;
  1468. extradata[4] = 0x80 | (sri << 3);
  1469. extradata_size = 5;
  1470. } else
  1471. extradata_size = 2;
  1472. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
  1473. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1474. * Create the "atom size", "tag", and "tag version" fields the
  1475. * decoder expects manually. */
  1476. extradata_size = 12 + track->codec_priv.size;
  1477. extradata = av_mallocz(extradata_size +
  1478. FF_INPUT_BUFFER_PADDING_SIZE);
  1479. if (extradata == NULL)
  1480. return AVERROR(ENOMEM);
  1481. AV_WB32(extradata, extradata_size);
  1482. memcpy(&extradata[4], "alac", 4);
  1483. AV_WB32(&extradata[8], 0);
  1484. memcpy(&extradata[12], track->codec_priv.data,
  1485. track->codec_priv.size);
  1486. } else if (codec_id == AV_CODEC_ID_TTA) {
  1487. extradata_size = 30;
  1488. extradata = av_mallocz(extradata_size);
  1489. if (extradata == NULL)
  1490. return AVERROR(ENOMEM);
  1491. ffio_init_context(&b, extradata, extradata_size, 1,
  1492. NULL, NULL, NULL, NULL);
  1493. avio_write(&b, "TTA1", 4);
  1494. avio_wl16(&b, 1);
  1495. avio_wl16(&b, track->audio.channels);
  1496. avio_wl16(&b, track->audio.bitdepth);
  1497. avio_wl32(&b, track->audio.out_samplerate);
  1498. avio_wl32(&b, matroska->ctx->duration *
  1499. track->audio.out_samplerate);
  1500. } else if (codec_id == AV_CODEC_ID_RV10 ||
  1501. codec_id == AV_CODEC_ID_RV20 ||
  1502. codec_id == AV_CODEC_ID_RV30 ||
  1503. codec_id == AV_CODEC_ID_RV40) {
  1504. extradata_offset = 26;
  1505. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1506. track->audio.out_samplerate = 8000;
  1507. track->audio.channels = 1;
  1508. } else if (codec_id == AV_CODEC_ID_RA_288 ||
  1509. codec_id == AV_CODEC_ID_COOK ||
  1510. codec_id == AV_CODEC_ID_ATRAC3 ||
  1511. codec_id == AV_CODEC_ID_SIPR) {
  1512. int flavor;
  1513. ffio_init_context(&b, track->codec_priv.data,
  1514. track->codec_priv.size,
  1515. 0, NULL, NULL, NULL, NULL);
  1516. avio_skip(&b, 22);
  1517. flavor = avio_rb16(&b);
  1518. track->audio.coded_framesize = avio_rb32(&b);
  1519. avio_skip(&b, 12);
  1520. track->audio.sub_packet_h = avio_rb16(&b);
  1521. track->audio.frame_size = avio_rb16(&b);
  1522. track->audio.sub_packet_size = avio_rb16(&b);
  1523. if (flavor <= 0 ||
  1524. track->audio.coded_framesize <= 0 ||
  1525. track->audio.sub_packet_h <= 0 ||
  1526. track->audio.frame_size <= 0 ||
  1527. track->audio.sub_packet_size <= 0)
  1528. return AVERROR_INVALIDDATA;
  1529. track->audio.buf = av_malloc(track->audio.frame_size *
  1530. track->audio.sub_packet_h);
  1531. if (codec_id == AV_CODEC_ID_RA_288) {
  1532. st->codec->block_align = track->audio.coded_framesize;
  1533. track->codec_priv.size = 0;
  1534. } else {
  1535. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1536. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1537. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1538. st->codec->bit_rate = sipr_bit_rate[flavor];
  1539. }
  1540. st->codec->block_align = track->audio.sub_packet_size;
  1541. extradata_offset = 78;
  1542. }
  1543. }
  1544. track->codec_priv.size -= extradata_offset;
  1545. if (codec_id == AV_CODEC_ID_NONE)
  1546. av_log(matroska->ctx, AV_LOG_INFO,
  1547. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1548. if (track->time_scale < 0.01)
  1549. track->time_scale = 1.0;
  1550. avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
  1551. 1000 * 1000 * 1000); /* 64 bit pts in ns */
  1552. /* convert the delay from ns to the track timebase */
  1553. track->codec_delay = av_rescale_q(track->codec_delay,
  1554. (AVRational){ 1, 1000000000 },
  1555. st->time_base);
  1556. st->codec->codec_id = codec_id;
  1557. st->start_time = 0;
  1558. if (strcmp(track->language, "und"))
  1559. av_dict_set(&st->metadata, "language", track->language, 0);
  1560. av_dict_set(&st->metadata, "title", track->name, 0);
  1561. if (track->flag_default)
  1562. st->disposition |= AV_DISPOSITION_DEFAULT;
  1563. if (track->flag_forced)
  1564. st->disposition |= AV_DISPOSITION_FORCED;
  1565. if (!st->codec->extradata) {
  1566. if (extradata) {
  1567. st->codec->extradata = extradata;
  1568. st->codec->extradata_size = extradata_size;
  1569. } else if (track->codec_priv.data && track->codec_priv.size > 0) {
  1570. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1571. FF_INPUT_BUFFER_PADDING_SIZE);
  1572. if (st->codec->extradata == NULL)
  1573. return AVERROR(ENOMEM);
  1574. st->codec->extradata_size = track->codec_priv.size;
  1575. memcpy(st->codec->extradata,
  1576. track->codec_priv.data + extradata_offset,
  1577. track->codec_priv.size);
  1578. }
  1579. }
  1580. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1581. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1582. st->codec->codec_tag = track->video.fourcc;
  1583. st->codec->width = track->video.pixel_width;
  1584. st->codec->height = track->video.pixel_height;
  1585. av_reduce(&st->sample_aspect_ratio.num,
  1586. &st->sample_aspect_ratio.den,
  1587. st->codec->height * track->video.display_width,
  1588. st->codec->width * track->video.display_height,
  1589. 255);
  1590. if (st->codec->codec_id != AV_CODEC_ID_H264 &&
  1591. st->codec->codec_id != AV_CODEC_ID_HEVC)
  1592. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1593. if (track->default_duration) {
  1594. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1595. 1000000000, track->default_duration, 30000);
  1596. }
  1597. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1598. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1599. st->codec->sample_rate = track->audio.out_samplerate;
  1600. st->codec->channels = track->audio.channels;
  1601. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1602. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1603. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1604. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1605. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1606. matroska->contains_ssa = 1;
  1607. }
  1608. }
  1609. attachments = attachments_list->elem;
  1610. for (j = 0; j < attachments_list->nb_elem; j++) {
  1611. if (!(attachments[j].filename && attachments[j].mime &&
  1612. attachments[j].bin.data && attachments[j].bin.size > 0)) {
  1613. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1614. } else {
  1615. AVStream *st = avformat_new_stream(s, NULL);
  1616. if (st == NULL)
  1617. break;
  1618. av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
  1619. av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
  1620. st->codec->codec_id = AV_CODEC_ID_NONE;
  1621. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1622. st->codec->extradata = av_malloc(attachments[j].bin.size);
  1623. if (st->codec->extradata == NULL)
  1624. break;
  1625. st->codec->extradata_size = attachments[j].bin.size;
  1626. memcpy(st->codec->extradata, attachments[j].bin.data,
  1627. attachments[j].bin.size);
  1628. for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1629. if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
  1630. strlen(ff_mkv_mime_tags[i].str))) {
  1631. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1632. break;
  1633. }
  1634. }
  1635. attachments[j].stream = st;
  1636. }
  1637. }
  1638. chapters = chapters_list->elem;
  1639. for (i = 0; i < chapters_list->nb_elem; i++)
  1640. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
  1641. (max_start == 0 || chapters[i].start > max_start)) {
  1642. chapters[i].chapter =
  1643. avpriv_new_chapter(s, chapters[i].uid,
  1644. (AVRational) { 1, 1000000000 },
  1645. chapters[i].start, chapters[i].end,
  1646. chapters[i].title);
  1647. av_dict_set(&chapters[i].chapter->metadata,
  1648. "title", chapters[i].title, 0);
  1649. max_start = chapters[i].start;
  1650. }
  1651. matroska_convert_tags(s);
  1652. return 0;
  1653. }
  1654. /*
  1655. * Put one packet in an application-supplied AVPacket struct.
  1656. * Returns 0 on success or -1 on failure.
  1657. */
  1658. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1659. AVPacket *pkt)
  1660. {
  1661. if (matroska->num_packets > 0) {
  1662. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1663. av_free(matroska->packets[0]);
  1664. if (matroska->num_packets > 1) {
  1665. void *newpackets;
  1666. memmove(&matroska->packets[0], &matroska->packets[1],
  1667. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1668. newpackets = av_realloc(matroska->packets,
  1669. (matroska->num_packets - 1) *
  1670. sizeof(AVPacket *));
  1671. if (newpackets)
  1672. matroska->packets = newpackets;
  1673. } else {
  1674. av_freep(&matroska->packets);
  1675. matroska->prev_pkt = NULL;
  1676. }
  1677. matroska->num_packets--;
  1678. return 0;
  1679. }
  1680. return -1;
  1681. }
  1682. /*
  1683. * Free all packets in our internal queue.
  1684. */
  1685. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1686. {
  1687. matroska->prev_pkt = NULL;
  1688. if (matroska->packets) {
  1689. int n;
  1690. for (n = 0; n < matroska->num_packets; n++) {
  1691. av_free_packet(matroska->packets[n]);
  1692. av_free(matroska->packets[n]);
  1693. }
  1694. av_freep(&matroska->packets);
  1695. matroska->num_packets = 0;
  1696. }
  1697. }
  1698. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1699. int *buf_size, int type,
  1700. uint32_t **lace_buf, int *laces)
  1701. {
  1702. int res = 0, n, size = *buf_size;
  1703. uint8_t *data = *buf;
  1704. uint32_t *lace_size;
  1705. if (!type) {
  1706. *laces = 1;
  1707. *lace_buf = av_mallocz(sizeof(int));
  1708. if (!*lace_buf)
  1709. return AVERROR(ENOMEM);
  1710. *lace_buf[0] = size;
  1711. return 0;
  1712. }
  1713. assert(size > 0);
  1714. *laces = *data + 1;
  1715. data += 1;
  1716. size -= 1;
  1717. lace_size = av_mallocz(*laces * sizeof(int));
  1718. if (!lace_size)
  1719. return AVERROR(ENOMEM);
  1720. switch (type) {
  1721. case 0x1: /* Xiph lacing */
  1722. {
  1723. uint8_t temp;
  1724. uint32_t total = 0;
  1725. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1726. while (1) {
  1727. if (size == 0) {
  1728. res = AVERROR_EOF;
  1729. break;
  1730. }
  1731. temp = *data;
  1732. lace_size[n] += temp;
  1733. data += 1;
  1734. size -= 1;
  1735. if (temp != 0xff)
  1736. break;
  1737. }
  1738. total += lace_size[n];
  1739. }
  1740. if (size <= total) {
  1741. res = AVERROR_INVALIDDATA;
  1742. break;
  1743. }
  1744. lace_size[n] = size - total;
  1745. break;
  1746. }
  1747. case 0x2: /* fixed-size lacing */
  1748. if (size % (*laces)) {
  1749. res = AVERROR_INVALIDDATA;
  1750. break;
  1751. }
  1752. for (n = 0; n < *laces; n++)
  1753. lace_size[n] = size / *laces;
  1754. break;
  1755. case 0x3: /* EBML lacing */
  1756. {
  1757. uint64_t num;
  1758. uint64_t total;
  1759. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1760. if (n < 0) {
  1761. av_log(matroska->ctx, AV_LOG_INFO,
  1762. "EBML block data error\n");
  1763. res = n;
  1764. break;
  1765. }
  1766. data += n;
  1767. size -= n;
  1768. total = lace_size[0] = num;
  1769. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1770. int64_t snum;
  1771. int r;
  1772. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1773. if (r < 0) {
  1774. av_log(matroska->ctx, AV_LOG_INFO,
  1775. "EBML block data error\n");
  1776. res = r;
  1777. break;
  1778. }
  1779. data += r;
  1780. size -= r;
  1781. lace_size[n] = lace_size[n - 1] + snum;
  1782. total += lace_size[n];
  1783. }
  1784. if (size <= total) {
  1785. res = AVERROR_INVALIDDATA;
  1786. break;
  1787. }
  1788. lace_size[*laces - 1] = size - total;
  1789. break;
  1790. }
  1791. }
  1792. *buf = data;
  1793. *lace_buf = lace_size;
  1794. *buf_size = size;
  1795. return res;
  1796. }
  1797. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1798. MatroskaTrack *track, AVStream *st,
  1799. uint8_t *data, int size, uint64_t timecode,
  1800. uint64_t duration, int64_t pos)
  1801. {
  1802. int a = st->codec->block_align;
  1803. int sps = track->audio.sub_packet_size;
  1804. int cfs = track->audio.coded_framesize;
  1805. int h = track->audio.sub_packet_h;
  1806. int y = track->audio.sub_packet_cnt;
  1807. int w = track->audio.frame_size;
  1808. int x;
  1809. if (!track->audio.pkt_cnt) {
  1810. if (track->audio.sub_packet_cnt == 0)
  1811. track->audio.buf_timecode = timecode;
  1812. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1813. if (size < cfs * h / 2) {
  1814. av_log(matroska->ctx, AV_LOG_ERROR,
  1815. "Corrupt int4 RM-style audio packet size\n");
  1816. return AVERROR_INVALIDDATA;
  1817. }
  1818. for (x = 0; x < h / 2; x++)
  1819. memcpy(track->audio.buf + x * 2 * w + y * cfs,
  1820. data + x * cfs, cfs);
  1821. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1822. if (size < w) {
  1823. av_log(matroska->ctx, AV_LOG_ERROR,
  1824. "Corrupt sipr RM-style audio packet size\n");
  1825. return AVERROR_INVALIDDATA;
  1826. }
  1827. memcpy(track->audio.buf + y * w, data, w);
  1828. } else {
  1829. if (size < sps * w / sps) {
  1830. av_log(matroska->ctx, AV_LOG_ERROR,
  1831. "Corrupt generic RM-style audio packet size\n");
  1832. return AVERROR_INVALIDDATA;
  1833. }
  1834. for (x = 0; x < w / sps; x++)
  1835. memcpy(track->audio.buf +
  1836. sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
  1837. data + x * sps, sps);
  1838. }
  1839. if (++track->audio.sub_packet_cnt >= h) {
  1840. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1841. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1842. track->audio.sub_packet_cnt = 0;
  1843. track->audio.pkt_cnt = h * w / a;
  1844. }
  1845. }
  1846. while (track->audio.pkt_cnt) {
  1847. AVPacket *pkt = av_mallocz(sizeof(AVPacket));
  1848. av_new_packet(pkt, a);
  1849. memcpy(pkt->data,
  1850. track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
  1851. a);
  1852. pkt->pts = track->audio.buf_timecode;
  1853. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1854. pkt->pos = pos;
  1855. pkt->stream_index = st->index;
  1856. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  1857. }
  1858. return 0;
  1859. }
  1860. /* reconstruct full wavpack blocks from mangled matroska ones */
  1861. static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
  1862. uint8_t **pdst, int *size)
  1863. {
  1864. uint8_t *dst = NULL;
  1865. int dstlen = 0;
  1866. int srclen = *size;
  1867. uint32_t samples;
  1868. uint16_t ver;
  1869. int ret, offset = 0;
  1870. if (srclen < 12 || track->stream->codec->extradata_size < 2)
  1871. return AVERROR_INVALIDDATA;
  1872. ver = AV_RL16(track->stream->codec->extradata);
  1873. samples = AV_RL32(src);
  1874. src += 4;
  1875. srclen -= 4;
  1876. while (srclen >= 8) {
  1877. int multiblock;
  1878. uint32_t blocksize;
  1879. uint8_t *tmp;
  1880. uint32_t flags = AV_RL32(src);
  1881. uint32_t crc = AV_RL32(src + 4);
  1882. src += 8;
  1883. srclen -= 8;
  1884. multiblock = (flags & 0x1800) != 0x1800;
  1885. if (multiblock) {
  1886. if (srclen < 4) {
  1887. ret = AVERROR_INVALIDDATA;
  1888. goto fail;
  1889. }
  1890. blocksize = AV_RL32(src);
  1891. src += 4;
  1892. srclen -= 4;
  1893. } else
  1894. blocksize = srclen;
  1895. if (blocksize > srclen) {
  1896. ret = AVERROR_INVALIDDATA;
  1897. goto fail;
  1898. }
  1899. tmp = av_realloc(dst, dstlen + blocksize + 32);
  1900. if (!tmp) {
  1901. ret = AVERROR(ENOMEM);
  1902. goto fail;
  1903. }
  1904. dst = tmp;
  1905. dstlen += blocksize + 32;
  1906. AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
  1907. AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
  1908. AV_WL16(dst + offset + 8, ver); // version
  1909. AV_WL16(dst + offset + 10, 0); // track/index_no
  1910. AV_WL32(dst + offset + 12, 0); // total samples
  1911. AV_WL32(dst + offset + 16, 0); // block index
  1912. AV_WL32(dst + offset + 20, samples); // number of samples
  1913. AV_WL32(dst + offset + 24, flags); // flags
  1914. AV_WL32(dst + offset + 28, crc); // crc
  1915. memcpy(dst + offset + 32, src, blocksize); // block data
  1916. src += blocksize;
  1917. srclen -= blocksize;
  1918. offset += blocksize + 32;
  1919. }
  1920. *pdst = dst;
  1921. *size = dstlen;
  1922. return 0;
  1923. fail:
  1924. av_freep(&dst);
  1925. return ret;
  1926. }
  1927. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  1928. MatroskaTrack *track, AVStream *st,
  1929. uint8_t *data, int pkt_size,
  1930. uint64_t timecode, uint64_t duration,
  1931. int64_t pos, int is_keyframe)
  1932. {
  1933. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1934. uint8_t *pkt_data = data;
  1935. int offset = 0, res;
  1936. AVPacket *pkt;
  1937. if (encodings && encodings->scope & 1) {
  1938. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  1939. if (res < 0)
  1940. return res;
  1941. }
  1942. if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
  1943. uint8_t *wv_data;
  1944. res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
  1945. if (res < 0) {
  1946. av_log(matroska->ctx, AV_LOG_ERROR,
  1947. "Error parsing a wavpack block.\n");
  1948. goto fail;
  1949. }
  1950. if (pkt_data != data)
  1951. av_freep(&pkt_data);
  1952. pkt_data = wv_data;
  1953. }
  1954. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  1955. offset = 8;
  1956. pkt = av_mallocz(sizeof(AVPacket));
  1957. /* XXX: prevent data copy... */
  1958. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  1959. av_free(pkt);
  1960. return AVERROR(ENOMEM);
  1961. }
  1962. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  1963. uint8_t *buf = pkt->data;
  1964. bytestream_put_be32(&buf, pkt_size);
  1965. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  1966. }
  1967. memcpy(pkt->data + offset, pkt_data, pkt_size);
  1968. if (pkt_data != data)
  1969. av_free(pkt_data);
  1970. pkt->flags = is_keyframe;
  1971. pkt->stream_index = st->index;
  1972. if (track->ms_compat)
  1973. pkt->dts = timecode;
  1974. else
  1975. pkt->pts = timecode;
  1976. pkt->pos = pos;
  1977. if (st->codec->codec_id == AV_CODEC_ID_TEXT)
  1978. pkt->convergence_duration = duration;
  1979. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1980. pkt->duration = duration;
  1981. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1982. matroska_fix_ass_packet(matroska, pkt, duration);
  1983. if (matroska->prev_pkt &&
  1984. timecode != AV_NOPTS_VALUE &&
  1985. matroska->prev_pkt->pts == timecode &&
  1986. matroska->prev_pkt->stream_index == st->index &&
  1987. st->codec->codec_id == AV_CODEC_ID_SSA)
  1988. matroska_merge_packets(matroska->prev_pkt, pkt);
  1989. else {
  1990. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  1991. matroska->prev_pkt = pkt;
  1992. }
  1993. return 0;
  1994. fail:
  1995. if (pkt_data != data)
  1996. av_freep(&pkt_data);
  1997. return res;
  1998. }
  1999. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  2000. int size, int64_t pos, uint64_t cluster_time,
  2001. uint64_t block_duration, int is_keyframe,
  2002. int64_t cluster_pos)
  2003. {
  2004. uint64_t timecode = AV_NOPTS_VALUE;
  2005. MatroskaTrack *track;
  2006. int res = 0;
  2007. AVStream *st;
  2008. int16_t block_time;
  2009. uint32_t *lace_size = NULL;
  2010. int n, flags, laces = 0;
  2011. uint64_t num, duration;
  2012. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  2013. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  2014. return n;
  2015. }
  2016. data += n;
  2017. size -= n;
  2018. track = matroska_find_track_by_num(matroska, num);
  2019. if (!track || !track->stream) {
  2020. av_log(matroska->ctx, AV_LOG_INFO,
  2021. "Invalid stream %"PRIu64" or size %u\n", num, size);
  2022. return AVERROR_INVALIDDATA;
  2023. } else if (size <= 3)
  2024. return 0;
  2025. st = track->stream;
  2026. if (st->discard >= AVDISCARD_ALL)
  2027. return res;
  2028. block_time = AV_RB16(data);
  2029. data += 2;
  2030. flags = *data++;
  2031. size -= 3;
  2032. if (is_keyframe == -1)
  2033. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  2034. if (cluster_time != (uint64_t) -1 &&
  2035. (block_time >= 0 || cluster_time >= -block_time)) {
  2036. timecode = cluster_time + block_time - track->codec_delay;
  2037. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
  2038. timecode < track->end_timecode)
  2039. is_keyframe = 0; /* overlapping subtitles are not key frame */
  2040. if (is_keyframe)
  2041. av_add_index_entry(st, cluster_pos, timecode, 0, 0,
  2042. AVINDEX_KEYFRAME);
  2043. }
  2044. if (matroska->skip_to_keyframe &&
  2045. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  2046. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  2047. return res;
  2048. matroska->skip_to_keyframe = 0;
  2049. }
  2050. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  2051. &lace_size, &laces);
  2052. if (res)
  2053. goto end;
  2054. if (block_duration != AV_NOPTS_VALUE) {
  2055. duration = block_duration / laces;
  2056. if (block_duration != duration * laces) {
  2057. av_log(matroska->ctx, AV_LOG_WARNING,
  2058. "Incorrect block_duration, possibly corrupted container");
  2059. }
  2060. } else {
  2061. duration = track->default_duration / matroska->time_scale;
  2062. block_duration = duration * laces;
  2063. }
  2064. if (timecode != AV_NOPTS_VALUE)
  2065. track->end_timecode =
  2066. FFMAX(track->end_timecode, timecode + block_duration);
  2067. for (n = 0; n < laces; n++) {
  2068. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  2069. st->codec->codec_id == AV_CODEC_ID_COOK ||
  2070. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  2071. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  2072. st->codec->block_align && track->audio.sub_packet_size) {
  2073. res = matroska_parse_rm_audio(matroska, track, st, data,
  2074. lace_size[n],
  2075. timecode, duration, pos);
  2076. if (res)
  2077. goto end;
  2078. } else {
  2079. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  2080. timecode, duration, pos,
  2081. !n ? is_keyframe : 0);
  2082. if (res)
  2083. goto end;
  2084. }
  2085. if (timecode != AV_NOPTS_VALUE)
  2086. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  2087. data += lace_size[n];
  2088. }
  2089. end:
  2090. av_free(lace_size);
  2091. return res;
  2092. }
  2093. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2094. {
  2095. EbmlList *blocks_list;
  2096. MatroskaBlock *blocks;
  2097. int i, res;
  2098. res = ebml_parse(matroska,
  2099. matroska_cluster_incremental_parsing,
  2100. &matroska->current_cluster);
  2101. if (res == 1) {
  2102. /* New Cluster */
  2103. if (matroska->current_cluster_pos)
  2104. ebml_level_end(matroska);
  2105. ebml_free(matroska_cluster, &matroska->current_cluster);
  2106. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2107. matroska->current_cluster_num_blocks = 0;
  2108. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2109. matroska->prev_pkt = NULL;
  2110. /* sizeof the ID which was already read */
  2111. if (matroska->current_id)
  2112. matroska->current_cluster_pos -= 4;
  2113. res = ebml_parse(matroska,
  2114. matroska_clusters_incremental,
  2115. &matroska->current_cluster);
  2116. /* Try parsing the block again. */
  2117. if (res == 1)
  2118. res = ebml_parse(matroska,
  2119. matroska_cluster_incremental_parsing,
  2120. &matroska->current_cluster);
  2121. }
  2122. if (!res &&
  2123. matroska->current_cluster_num_blocks <
  2124. matroska->current_cluster.blocks.nb_elem) {
  2125. blocks_list = &matroska->current_cluster.blocks;
  2126. blocks = blocks_list->elem;
  2127. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2128. i = blocks_list->nb_elem - 1;
  2129. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2130. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2131. if (!blocks[i].non_simple)
  2132. blocks[i].duration = AV_NOPTS_VALUE;
  2133. res = matroska_parse_block(matroska, blocks[i].bin.data,
  2134. blocks[i].bin.size, blocks[i].bin.pos,
  2135. matroska->current_cluster.timecode,
  2136. blocks[i].duration, is_keyframe,
  2137. matroska->current_cluster_pos);
  2138. }
  2139. }
  2140. if (res < 0)
  2141. matroska->done = 1;
  2142. return res;
  2143. }
  2144. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2145. {
  2146. MatroskaCluster cluster = { 0 };
  2147. EbmlList *blocks_list;
  2148. MatroskaBlock *blocks;
  2149. int i, res;
  2150. int64_t pos;
  2151. if (!matroska->contains_ssa)
  2152. return matroska_parse_cluster_incremental(matroska);
  2153. pos = avio_tell(matroska->ctx->pb);
  2154. matroska->prev_pkt = NULL;
  2155. if (matroska->current_id)
  2156. pos -= 4; /* sizeof the ID which was already read */
  2157. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2158. blocks_list = &cluster.blocks;
  2159. blocks = blocks_list->elem;
  2160. for (i = 0; i < blocks_list->nb_elem && !res; i++)
  2161. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2162. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2163. if (!blocks[i].non_simple)
  2164. blocks[i].duration = AV_NOPTS_VALUE;
  2165. res = matroska_parse_block(matroska, blocks[i].bin.data,
  2166. blocks[i].bin.size, blocks[i].bin.pos,
  2167. cluster.timecode, blocks[i].duration,
  2168. is_keyframe, pos);
  2169. }
  2170. ebml_free(matroska_cluster, &cluster);
  2171. return res;
  2172. }
  2173. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2174. {
  2175. MatroskaDemuxContext *matroska = s->priv_data;
  2176. int ret = 0;
  2177. while (!ret && matroska_deliver_packet(matroska, pkt)) {
  2178. int64_t pos = avio_tell(matroska->ctx->pb);
  2179. if (matroska->done)
  2180. return AVERROR_EOF;
  2181. if (matroska_parse_cluster(matroska) < 0)
  2182. ret = matroska_resync(matroska, pos);
  2183. }
  2184. if (ret == AVERROR_INVALIDDATA && pkt->data) {
  2185. pkt->flags |= AV_PKT_FLAG_CORRUPT;
  2186. return 0;
  2187. }
  2188. return ret;
  2189. }
  2190. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2191. int64_t timestamp, int flags)
  2192. {
  2193. MatroskaDemuxContext *matroska = s->priv_data;
  2194. MatroskaTrack *tracks = matroska->tracks.elem;
  2195. AVStream *st = s->streams[stream_index];
  2196. int i, index, index_sub, index_min;
  2197. /* Parse the CUES now since we need the index data to seek. */
  2198. if (matroska->cues_parsing_deferred) {
  2199. matroska_parse_cues(matroska);
  2200. matroska->cues_parsing_deferred = 0;
  2201. }
  2202. if (!st->nb_index_entries)
  2203. return 0;
  2204. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2205. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2206. avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
  2207. SEEK_SET);
  2208. matroska->current_id = 0;
  2209. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2210. matroska_clear_queue(matroska);
  2211. if (matroska_parse_cluster(matroska) < 0)
  2212. break;
  2213. }
  2214. }
  2215. matroska_clear_queue(matroska);
  2216. if (index < 0)
  2217. return 0;
  2218. index_min = index;
  2219. for (i = 0; i < matroska->tracks.nb_elem; i++) {
  2220. tracks[i].audio.pkt_cnt = 0;
  2221. tracks[i].audio.sub_packet_cnt = 0;
  2222. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2223. tracks[i].end_timecode = 0;
  2224. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
  2225. !tracks[i].stream->discard != AVDISCARD_ALL) {
  2226. index_sub = av_index_search_timestamp(
  2227. tracks[i].stream, st->index_entries[index].timestamp,
  2228. AVSEEK_FLAG_BACKWARD);
  2229. if (index_sub >= 0 &&
  2230. st->index_entries[index_sub].pos < st->index_entries[index_min].pos &&
  2231. st->index_entries[index].timestamp -
  2232. st->index_entries[index_sub].timestamp < 30000000000 / matroska->time_scale)
  2233. index_min = index_sub;
  2234. }
  2235. }
  2236. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2237. matroska->current_id = 0;
  2238. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2239. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2240. matroska->done = 0;
  2241. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2242. return 0;
  2243. }
  2244. static int matroska_read_close(AVFormatContext *s)
  2245. {
  2246. MatroskaDemuxContext *matroska = s->priv_data;
  2247. MatroskaTrack *tracks = matroska->tracks.elem;
  2248. int n;
  2249. matroska_clear_queue(matroska);
  2250. for (n = 0; n < matroska->tracks.nb_elem; n++)
  2251. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2252. av_free(tracks[n].audio.buf);
  2253. ebml_free(matroska_cluster, &matroska->current_cluster);
  2254. ebml_free(matroska_segment, matroska);
  2255. return 0;
  2256. }
  2257. AVInputFormat ff_matroska_demuxer = {
  2258. .name = "matroska,webm",
  2259. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2260. .priv_data_size = sizeof(MatroskaDemuxContext),
  2261. .read_probe = matroska_probe,
  2262. .read_header = matroska_read_header,
  2263. .read_packet = matroska_read_packet,
  2264. .read_close = matroska_read_close,
  2265. .read_seek = matroska_read_seek,
  2266. };