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.

2996 lines
104KB

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