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.

3811 lines
139KB

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