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.

3497 lines
124KB

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