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.

3839 lines
141KB

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