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.

2612 lines
90KB

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