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.

3081 lines
107KB

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