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.

4027 lines
148KB

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