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.

3517 lines
125KB

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