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.

3008 lines
105KB

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