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.

3519 lines
125KB

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