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.

3966 lines
145KB

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