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.

2026 lines
73KB

  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. * by Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * Specs available on the Matroska project page: http://www.matroska.org/.
  28. */
  29. #include <stdio.h>
  30. #include "avformat.h"
  31. #include "internal.h"
  32. #include "avio_internal.h"
  33. /* For ff_codec_get_id(). */
  34. #include "riff.h"
  35. #include "isom.h"
  36. #include "rm.h"
  37. #include "matroska.h"
  38. #include "libavcodec/mpeg4audio.h"
  39. #include "libavutil/intfloat_readwrite.h"
  40. #include "libavutil/intreadwrite.h"
  41. #include "libavutil/avstring.h"
  42. #include "libavutil/lzo.h"
  43. #include "libavutil/dict.h"
  44. #if CONFIG_ZLIB
  45. #include <zlib.h>
  46. #endif
  47. #if CONFIG_BZLIB
  48. #include <bzlib.h>
  49. #endif
  50. typedef enum {
  51. EBML_NONE,
  52. EBML_UINT,
  53. EBML_FLOAT,
  54. EBML_STR,
  55. EBML_UTF8,
  56. EBML_BIN,
  57. EBML_NEST,
  58. EBML_PASS,
  59. EBML_STOP,
  60. EBML_TYPE_COUNT
  61. } EbmlType;
  62. typedef const struct EbmlSyntax {
  63. uint32_t id;
  64. EbmlType type;
  65. int list_elem_size;
  66. int data_offset;
  67. union {
  68. uint64_t u;
  69. double f;
  70. const char *s;
  71. const struct EbmlSyntax *n;
  72. } def;
  73. } EbmlSyntax;
  74. typedef struct {
  75. int nb_elem;
  76. void *elem;
  77. } EbmlList;
  78. typedef struct {
  79. int size;
  80. uint8_t *data;
  81. int64_t pos;
  82. } EbmlBin;
  83. typedef struct {
  84. uint64_t version;
  85. uint64_t max_size;
  86. uint64_t id_length;
  87. char *doctype;
  88. uint64_t doctype_version;
  89. } Ebml;
  90. typedef struct {
  91. uint64_t algo;
  92. EbmlBin settings;
  93. } MatroskaTrackCompression;
  94. typedef struct {
  95. uint64_t scope;
  96. uint64_t type;
  97. MatroskaTrackCompression compression;
  98. } MatroskaTrackEncoding;
  99. typedef struct {
  100. double frame_rate;
  101. uint64_t display_width;
  102. uint64_t display_height;
  103. uint64_t pixel_width;
  104. uint64_t pixel_height;
  105. EbmlBin color_space;
  106. uint64_t stereo_mode;
  107. } MatroskaTrackVideo;
  108. typedef struct {
  109. double samplerate;
  110. double out_samplerate;
  111. uint64_t bitdepth;
  112. uint64_t channels;
  113. /* real audio header (extracted from extradata) */
  114. int coded_framesize;
  115. int sub_packet_h;
  116. int frame_size;
  117. int sub_packet_size;
  118. int sub_packet_cnt;
  119. int pkt_cnt;
  120. uint64_t buf_timecode;
  121. uint8_t *buf;
  122. } MatroskaTrackAudio;
  123. typedef struct {
  124. uint64_t uid;
  125. uint64_t type;
  126. } MatroskaTrackPlane;
  127. typedef struct {
  128. EbmlList combine_planes;
  129. } MatroskaTrackOperation;
  130. typedef struct {
  131. uint64_t num;
  132. uint64_t uid;
  133. uint64_t type;
  134. char *name;
  135. char *codec_id;
  136. EbmlBin codec_priv;
  137. char *language;
  138. double time_scale;
  139. uint64_t default_duration;
  140. uint64_t flag_default;
  141. uint64_t flag_forced;
  142. MatroskaTrackVideo video;
  143. MatroskaTrackAudio audio;
  144. MatroskaTrackOperation operation;
  145. EbmlList encodings;
  146. AVStream *stream;
  147. int64_t end_timecode;
  148. int ms_compat;
  149. } MatroskaTrack;
  150. typedef struct {
  151. uint64_t uid;
  152. char *filename;
  153. char *mime;
  154. EbmlBin bin;
  155. AVStream *stream;
  156. } MatroskaAttachement;
  157. typedef struct {
  158. uint64_t start;
  159. uint64_t end;
  160. uint64_t uid;
  161. char *title;
  162. AVChapter *chapter;
  163. } MatroskaChapter;
  164. typedef struct {
  165. uint64_t track;
  166. uint64_t pos;
  167. } MatroskaIndexPos;
  168. typedef struct {
  169. uint64_t time;
  170. EbmlList pos;
  171. } MatroskaIndex;
  172. typedef struct {
  173. char *name;
  174. char *string;
  175. char *lang;
  176. uint64_t def;
  177. EbmlList sub;
  178. } MatroskaTag;
  179. typedef struct {
  180. char *type;
  181. uint64_t typevalue;
  182. uint64_t trackuid;
  183. uint64_t chapteruid;
  184. uint64_t attachuid;
  185. } MatroskaTagTarget;
  186. typedef struct {
  187. MatroskaTagTarget target;
  188. EbmlList tag;
  189. } MatroskaTags;
  190. typedef struct {
  191. uint64_t id;
  192. uint64_t pos;
  193. } MatroskaSeekhead;
  194. typedef struct {
  195. uint64_t start;
  196. uint64_t length;
  197. } MatroskaLevel;
  198. typedef struct {
  199. AVFormatContext *ctx;
  200. /* EBML stuff */
  201. int num_levels;
  202. MatroskaLevel levels[EBML_MAX_DEPTH];
  203. int level_up;
  204. uint32_t current_id;
  205. uint64_t time_scale;
  206. double duration;
  207. char *title;
  208. EbmlList tracks;
  209. EbmlList attachments;
  210. EbmlList chapters;
  211. EbmlList index;
  212. EbmlList tags;
  213. EbmlList seekhead;
  214. /* byte position of the segment inside the stream */
  215. int64_t segment_start;
  216. /* the packet queue */
  217. AVPacket **packets;
  218. int num_packets;
  219. AVPacket *prev_pkt;
  220. int done;
  221. /* What to skip before effectively reading a packet. */
  222. int skip_to_keyframe;
  223. uint64_t skip_to_timecode;
  224. } MatroskaDemuxContext;
  225. typedef struct {
  226. uint64_t duration;
  227. int64_t reference;
  228. uint64_t non_simple;
  229. EbmlBin bin;
  230. } MatroskaBlock;
  231. typedef struct {
  232. uint64_t timecode;
  233. EbmlList blocks;
  234. } MatroskaCluster;
  235. static EbmlSyntax ebml_header[] = {
  236. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
  237. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
  238. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
  239. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
  240. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
  241. { EBML_ID_EBMLVERSION, EBML_NONE },
  242. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  243. { 0 }
  244. };
  245. static EbmlSyntax ebml_syntax[] = {
  246. { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
  247. { 0 }
  248. };
  249. static EbmlSyntax matroska_info[] = {
  250. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
  251. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
  252. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
  253. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  254. { MATROSKA_ID_MUXINGAPP, EBML_NONE },
  255. { MATROSKA_ID_DATEUTC, EBML_NONE },
  256. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  257. { 0 }
  258. };
  259. static EbmlSyntax matroska_track_video[] = {
  260. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
  261. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
  262. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
  263. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
  264. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
  265. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo,color_space) },
  266. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
  267. { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
  268. { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
  269. { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
  270. { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
  271. { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
  272. { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
  273. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  274. { 0 }
  275. };
  276. static EbmlSyntax matroska_track_audio[] = {
  277. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
  278. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
  279. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
  280. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
  281. { 0 }
  282. };
  283. static EbmlSyntax matroska_track_encoding_compression[] = {
  284. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
  285. { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
  286. { 0 }
  287. };
  288. static EbmlSyntax matroska_track_encoding[] = {
  289. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
  290. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
  291. { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
  292. { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
  293. { 0 }
  294. };
  295. static EbmlSyntax matroska_track_encodings[] = {
  296. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
  297. { 0 }
  298. };
  299. static EbmlSyntax matroska_track_plane[] = {
  300. { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
  301. { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
  302. { 0 }
  303. };
  304. static EbmlSyntax matroska_track_combine_planes[] = {
  305. { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
  306. { 0 }
  307. };
  308. static EbmlSyntax matroska_track_operation[] = {
  309. { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
  310. { 0 }
  311. };
  312. static EbmlSyntax matroska_track[] = {
  313. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
  314. { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
  315. { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
  316. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
  317. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
  318. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
  319. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
  320. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
  321. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
  322. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
  323. { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
  324. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
  325. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
  326. { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
  327. { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
  328. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  329. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  330. { MATROSKA_ID_CODECNAME, EBML_NONE },
  331. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  332. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  333. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  334. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  335. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  336. { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
  337. { 0 }
  338. };
  339. static EbmlSyntax matroska_tracks[] = {
  340. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
  341. { 0 }
  342. };
  343. static EbmlSyntax matroska_attachment[] = {
  344. { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
  345. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
  346. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
  347. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
  348. { MATROSKA_ID_FILEDESC, EBML_NONE },
  349. { 0 }
  350. };
  351. static EbmlSyntax matroska_attachments[] = {
  352. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
  353. { 0 }
  354. };
  355. static EbmlSyntax matroska_chapter_display[] = {
  356. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
  357. { MATROSKA_ID_CHAPLANG, EBML_NONE },
  358. { 0 }
  359. };
  360. static EbmlSyntax matroska_chapter_entry[] = {
  361. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
  362. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
  363. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
  364. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
  365. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  366. { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  367. { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
  368. { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
  369. { 0 }
  370. };
  371. static EbmlSyntax matroska_chapter[] = {
  372. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
  373. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  374. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  375. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  376. { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  377. { 0 }
  378. };
  379. static EbmlSyntax matroska_chapters[] = {
  380. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
  381. { 0 }
  382. };
  383. static EbmlSyntax matroska_index_pos[] = {
  384. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
  385. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
  386. { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
  387. { 0 }
  388. };
  389. static EbmlSyntax matroska_index_entry[] = {
  390. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
  391. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
  392. { 0 }
  393. };
  394. static EbmlSyntax matroska_index[] = {
  395. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
  396. { 0 }
  397. };
  398. static EbmlSyntax matroska_simpletag[] = {
  399. { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
  400. { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
  401. { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
  402. { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  403. { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  404. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
  405. { 0 }
  406. };
  407. static EbmlSyntax matroska_tagtargets[] = {
  408. { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
  409. { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
  410. { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
  411. { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
  412. { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
  413. { 0 }
  414. };
  415. static EbmlSyntax matroska_tag[] = {
  416. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
  417. { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
  418. { 0 }
  419. };
  420. static EbmlSyntax matroska_tags[] = {
  421. { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
  422. { 0 }
  423. };
  424. static EbmlSyntax matroska_seekhead_entry[] = {
  425. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
  426. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
  427. { 0 }
  428. };
  429. static EbmlSyntax matroska_seekhead[] = {
  430. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
  431. { 0 }
  432. };
  433. static EbmlSyntax matroska_segment[] = {
  434. { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
  435. { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
  436. { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
  437. { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
  438. { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
  439. { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
  440. { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
  441. { MATROSKA_ID_CLUSTER, EBML_STOP },
  442. { 0 }
  443. };
  444. static EbmlSyntax matroska_segments[] = {
  445. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
  446. { 0 }
  447. };
  448. static EbmlSyntax matroska_blockgroup[] = {
  449. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  450. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  451. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
  452. { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
  453. { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
  454. { 0 }
  455. };
  456. static EbmlSyntax matroska_cluster[] = {
  457. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  458. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  459. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  460. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  461. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  462. { 0 }
  463. };
  464. static EbmlSyntax matroska_clusters[] = {
  465. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
  466. { MATROSKA_ID_INFO, EBML_NONE },
  467. { MATROSKA_ID_CUES, EBML_NONE },
  468. { MATROSKA_ID_TAGS, EBML_NONE },
  469. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  470. { 0 }
  471. };
  472. static const char *matroska_doctypes[] = { "matroska", "webm" };
  473. /*
  474. * Return: Whether we reached the end of a level in the hierarchy or not.
  475. */
  476. static int ebml_level_end(MatroskaDemuxContext *matroska)
  477. {
  478. AVIOContext *pb = matroska->ctx->pb;
  479. int64_t pos = avio_tell(pb);
  480. if (matroska->num_levels > 0) {
  481. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  482. if (pos - level->start >= level->length || matroska->current_id) {
  483. matroska->num_levels--;
  484. return 1;
  485. }
  486. }
  487. return 0;
  488. }
  489. /*
  490. * Read: an "EBML number", which is defined as a variable-length
  491. * array of bytes. The first byte indicates the length by giving a
  492. * number of 0-bits followed by a one. The position of the first
  493. * "one" bit inside the first byte indicates the length of this
  494. * number.
  495. * Returns: number of bytes read, < 0 on error
  496. */
  497. static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  498. int max_size, uint64_t *number)
  499. {
  500. int read = 1, n = 1;
  501. uint64_t total = 0;
  502. /* The first byte tells us the length in bytes - avio_r8() can normally
  503. * return 0, but since that's not a valid first ebmlID byte, we can
  504. * use it safely here to catch EOS. */
  505. if (!(total = avio_r8(pb))) {
  506. /* we might encounter EOS here */
  507. if (!url_feof(pb)) {
  508. int64_t pos = avio_tell(pb);
  509. av_log(matroska->ctx, AV_LOG_ERROR,
  510. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  511. pos, pos);
  512. }
  513. return AVERROR(EIO); /* EOS or actual I/O error */
  514. }
  515. /* get the length of the EBML number */
  516. read = 8 - ff_log2_tab[total];
  517. if (read > max_size) {
  518. int64_t pos = avio_tell(pb) - 1;
  519. av_log(matroska->ctx, AV_LOG_ERROR,
  520. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  521. (uint8_t) total, pos, pos);
  522. return AVERROR_INVALIDDATA;
  523. }
  524. /* read out length */
  525. total ^= 1 << ff_log2_tab[total];
  526. while (n++ < read)
  527. total = (total << 8) | avio_r8(pb);
  528. *number = total;
  529. return read;
  530. }
  531. /**
  532. * Read a EBML length value.
  533. * This needs special handling for the "unknown length" case which has multiple
  534. * encodings.
  535. */
  536. static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  537. uint64_t *number)
  538. {
  539. int res = ebml_read_num(matroska, pb, 8, number);
  540. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  541. *number = 0xffffffffffffffULL;
  542. return res;
  543. }
  544. /*
  545. * Read the next element as an unsigned int.
  546. * 0 is success, < 0 is failure.
  547. */
  548. static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  549. {
  550. int n = 0;
  551. if (size > 8)
  552. return AVERROR_INVALIDDATA;
  553. /* big-endian ordering; build up number */
  554. *num = 0;
  555. while (n++ < size)
  556. *num = (*num << 8) | avio_r8(pb);
  557. return 0;
  558. }
  559. /*
  560. * Read the next element as a float.
  561. * 0 is success, < 0 is failure.
  562. */
  563. static int ebml_read_float(AVIOContext *pb, int size, double *num)
  564. {
  565. if (size == 0) {
  566. *num = 0;
  567. } else if (size == 4) {
  568. *num= av_int2flt(avio_rb32(pb));
  569. } else if(size==8){
  570. *num= av_int2dbl(avio_rb64(pb));
  571. } else
  572. return AVERROR_INVALIDDATA;
  573. return 0;
  574. }
  575. /*
  576. * Read the next element as an ASCII string.
  577. * 0 is success, < 0 is failure.
  578. */
  579. static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  580. {
  581. av_free(*str);
  582. /* EBML strings are usually not 0-terminated, so we allocate one
  583. * byte more, read the string and NULL-terminate it ourselves. */
  584. if (!(*str = av_malloc(size + 1)))
  585. return AVERROR(ENOMEM);
  586. if (avio_read(pb, (uint8_t *) *str, size) != size) {
  587. av_freep(str);
  588. return AVERROR(EIO);
  589. }
  590. (*str)[size] = '\0';
  591. return 0;
  592. }
  593. /*
  594. * Read the next element as binary data.
  595. * 0 is success, < 0 is failure.
  596. */
  597. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  598. {
  599. av_free(bin->data);
  600. if (!(bin->data = av_malloc(length)))
  601. return AVERROR(ENOMEM);
  602. bin->size = length;
  603. bin->pos = avio_tell(pb);
  604. if (avio_read(pb, bin->data, length) != length) {
  605. av_freep(&bin->data);
  606. return AVERROR(EIO);
  607. }
  608. return 0;
  609. }
  610. /*
  611. * Read the next element, but only the header. The contents
  612. * are supposed to be sub-elements which can be read separately.
  613. * 0 is success, < 0 is failure.
  614. */
  615. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  616. {
  617. AVIOContext *pb = matroska->ctx->pb;
  618. MatroskaLevel *level;
  619. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  620. av_log(matroska->ctx, AV_LOG_ERROR,
  621. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  622. return AVERROR(ENOSYS);
  623. }
  624. level = &matroska->levels[matroska->num_levels++];
  625. level->start = avio_tell(pb);
  626. level->length = length;
  627. return 0;
  628. }
  629. /*
  630. * Read signed/unsigned "EBML" numbers.
  631. * Return: number of bytes processed, < 0 on error
  632. */
  633. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  634. uint8_t *data, uint32_t size, uint64_t *num)
  635. {
  636. AVIOContext pb;
  637. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  638. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  639. }
  640. /*
  641. * Same as above, but signed.
  642. */
  643. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  644. uint8_t *data, uint32_t size, int64_t *num)
  645. {
  646. uint64_t unum;
  647. int res;
  648. /* read as unsigned number first */
  649. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  650. return res;
  651. /* make signed (weird way) */
  652. *num = unum - ((1LL << (7*res - 1)) - 1);
  653. return res;
  654. }
  655. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  656. EbmlSyntax *syntax, void *data);
  657. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  658. uint32_t id, void *data)
  659. {
  660. int i;
  661. for (i=0; syntax[i].id; i++)
  662. if (id == syntax[i].id)
  663. break;
  664. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  665. matroska->num_levels > 0 &&
  666. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  667. return 0; // we reached the end of an unknown size cluster
  668. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
  669. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  670. return ebml_parse_elem(matroska, &syntax[i], data);
  671. }
  672. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  673. void *data)
  674. {
  675. if (!matroska->current_id) {
  676. uint64_t id;
  677. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  678. if (res < 0)
  679. return res;
  680. matroska->current_id = id | 1 << 7*res;
  681. }
  682. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  683. }
  684. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  685. void *data)
  686. {
  687. int i, res = 0;
  688. for (i=0; syntax[i].id; i++)
  689. switch (syntax[i].type) {
  690. case EBML_UINT:
  691. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  692. break;
  693. case EBML_FLOAT:
  694. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  695. break;
  696. case EBML_STR:
  697. case EBML_UTF8:
  698. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  699. break;
  700. }
  701. while (!res && !ebml_level_end(matroska))
  702. res = ebml_parse(matroska, syntax, data);
  703. return res;
  704. }
  705. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  706. EbmlSyntax *syntax, void *data)
  707. {
  708. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  709. [EBML_UINT] = 8,
  710. [EBML_FLOAT] = 8,
  711. // max. 16 MB for strings
  712. [EBML_STR] = 0x1000000,
  713. [EBML_UTF8] = 0x1000000,
  714. // max. 256 MB for binary data
  715. [EBML_BIN] = 0x10000000,
  716. // no limits for anything else
  717. };
  718. AVIOContext *pb = matroska->ctx->pb;
  719. uint32_t id = syntax->id;
  720. uint64_t length;
  721. int res;
  722. data = (char *)data + syntax->data_offset;
  723. if (syntax->list_elem_size) {
  724. EbmlList *list = data;
  725. list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  726. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  727. memset(data, 0, syntax->list_elem_size);
  728. list->nb_elem++;
  729. }
  730. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  731. matroska->current_id = 0;
  732. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  733. return res;
  734. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  735. av_log(matroska->ctx, AV_LOG_ERROR,
  736. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  737. length, max_lengths[syntax->type], syntax->type);
  738. return AVERROR_INVALIDDATA;
  739. }
  740. }
  741. switch (syntax->type) {
  742. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  743. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  744. case EBML_STR:
  745. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  746. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  747. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  748. return res;
  749. if (id == MATROSKA_ID_SEGMENT)
  750. matroska->segment_start = avio_tell(matroska->ctx->pb);
  751. return ebml_parse_nest(matroska, syntax->def.n, data);
  752. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  753. case EBML_STOP: return 1;
  754. default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  755. }
  756. if (res == AVERROR_INVALIDDATA)
  757. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  758. else if (res == AVERROR(EIO))
  759. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  760. return res;
  761. }
  762. static void ebml_free(EbmlSyntax *syntax, void *data)
  763. {
  764. int i, j;
  765. for (i=0; syntax[i].id; i++) {
  766. void *data_off = (char *)data + syntax[i].data_offset;
  767. switch (syntax[i].type) {
  768. case EBML_STR:
  769. case EBML_UTF8: av_freep(data_off); break;
  770. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  771. case EBML_NEST:
  772. if (syntax[i].list_elem_size) {
  773. EbmlList *list = data_off;
  774. char *ptr = list->elem;
  775. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  776. ebml_free(syntax[i].def.n, ptr);
  777. av_free(list->elem);
  778. } else
  779. ebml_free(syntax[i].def.n, data_off);
  780. default: break;
  781. }
  782. }
  783. }
  784. /*
  785. * Autodetecting...
  786. */
  787. static int matroska_probe(AVProbeData *p)
  788. {
  789. uint64_t total = 0;
  790. int len_mask = 0x80, size = 1, n = 1, i;
  791. /* EBML header? */
  792. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  793. return 0;
  794. /* length of header */
  795. total = p->buf[4];
  796. while (size <= 8 && !(total & len_mask)) {
  797. size++;
  798. len_mask >>= 1;
  799. }
  800. if (size > 8)
  801. return 0;
  802. total &= (len_mask - 1);
  803. while (n < size)
  804. total = (total << 8) | p->buf[4 + n++];
  805. /* Does the probe data contain the whole header? */
  806. if (p->buf_size < 4 + size + total)
  807. return 0;
  808. /* The header should contain a known document type. For now,
  809. * we don't parse the whole header but simply check for the
  810. * availability of that array of characters inside the header.
  811. * Not fully fool-proof, but good enough. */
  812. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  813. int probelen = strlen(matroska_doctypes[i]);
  814. for (n = 4+size; n <= 4+size+total-probelen; n++)
  815. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  816. return AVPROBE_SCORE_MAX;
  817. }
  818. // probably valid EBML header but no recognized doctype
  819. return AVPROBE_SCORE_MAX/2;
  820. }
  821. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  822. int num)
  823. {
  824. MatroskaTrack *tracks = matroska->tracks.elem;
  825. int i;
  826. for (i=0; i < matroska->tracks.nb_elem; i++)
  827. if (tracks[i].num == num)
  828. return &tracks[i];
  829. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  830. return NULL;
  831. }
  832. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  833. MatroskaTrack *track)
  834. {
  835. MatroskaTrackEncoding *encodings = track->encodings.elem;
  836. uint8_t* data = *buf;
  837. int isize = *buf_size;
  838. uint8_t* pkt_data = NULL;
  839. int pkt_size = isize;
  840. int result = 0;
  841. int olen;
  842. if (pkt_size >= 10000000)
  843. return -1;
  844. switch (encodings[0].compression.algo) {
  845. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  846. return encodings[0].compression.settings.size;
  847. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  848. do {
  849. olen = pkt_size *= 3;
  850. pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
  851. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  852. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  853. if (result)
  854. goto failed;
  855. pkt_size -= olen;
  856. break;
  857. #if CONFIG_ZLIB
  858. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  859. z_stream zstream = {0};
  860. if (inflateInit(&zstream) != Z_OK)
  861. return -1;
  862. zstream.next_in = data;
  863. zstream.avail_in = isize;
  864. do {
  865. pkt_size *= 3;
  866. pkt_data = av_realloc(pkt_data, pkt_size);
  867. zstream.avail_out = pkt_size - zstream.total_out;
  868. zstream.next_out = pkt_data + zstream.total_out;
  869. result = inflate(&zstream, Z_NO_FLUSH);
  870. } while (result==Z_OK && pkt_size<10000000);
  871. pkt_size = zstream.total_out;
  872. inflateEnd(&zstream);
  873. if (result != Z_STREAM_END)
  874. goto failed;
  875. break;
  876. }
  877. #endif
  878. #if CONFIG_BZLIB
  879. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  880. bz_stream bzstream = {0};
  881. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  882. return -1;
  883. bzstream.next_in = data;
  884. bzstream.avail_in = isize;
  885. do {
  886. pkt_size *= 3;
  887. pkt_data = av_realloc(pkt_data, pkt_size);
  888. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  889. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  890. result = BZ2_bzDecompress(&bzstream);
  891. } while (result==BZ_OK && pkt_size<10000000);
  892. pkt_size = bzstream.total_out_lo32;
  893. BZ2_bzDecompressEnd(&bzstream);
  894. if (result != BZ_STREAM_END)
  895. goto failed;
  896. break;
  897. }
  898. #endif
  899. default:
  900. return -1;
  901. }
  902. *buf = pkt_data;
  903. *buf_size = pkt_size;
  904. return 0;
  905. failed:
  906. av_free(pkt_data);
  907. return -1;
  908. }
  909. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  910. AVPacket *pkt, uint64_t display_duration)
  911. {
  912. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  913. for (; *ptr!=',' && ptr<end-1; ptr++);
  914. if (*ptr == ',')
  915. ptr++;
  916. layer = ptr;
  917. for (; *ptr!=',' && ptr<end-1; ptr++);
  918. if (*ptr == ',') {
  919. int64_t end_pts = pkt->pts + display_duration;
  920. int sc = matroska->time_scale * pkt->pts / 10000000;
  921. int ec = matroska->time_scale * end_pts / 10000000;
  922. int sh, sm, ss, eh, em, es, len;
  923. sh = sc/360000; sc -= 360000*sh;
  924. sm = sc/ 6000; sc -= 6000*sm;
  925. ss = sc/ 100; sc -= 100*ss;
  926. eh = ec/360000; ec -= 360000*eh;
  927. em = ec/ 6000; ec -= 6000*em;
  928. es = ec/ 100; ec -= 100*es;
  929. *ptr++ = '\0';
  930. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  931. if (!(line = av_malloc(len)))
  932. return;
  933. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  934. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  935. av_free(pkt->data);
  936. pkt->data = line;
  937. pkt->size = strlen(line);
  938. }
  939. }
  940. static void matroska_merge_packets(AVPacket *out, AVPacket *in)
  941. {
  942. out->data = av_realloc(out->data, out->size+in->size);
  943. memcpy(out->data+out->size, in->data, in->size);
  944. out->size += in->size;
  945. av_destruct_packet(in);
  946. av_free(in);
  947. }
  948. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  949. AVDictionary **metadata, char *prefix)
  950. {
  951. MatroskaTag *tags = list->elem;
  952. char key[1024];
  953. int i;
  954. for (i=0; i < list->nb_elem; i++) {
  955. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  956. if (!tags[i].name) {
  957. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  958. continue;
  959. }
  960. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  961. else av_strlcpy(key, tags[i].name, sizeof(key));
  962. if (tags[i].def || !lang) {
  963. av_dict_set(metadata, key, tags[i].string, 0);
  964. if (tags[i].sub.nb_elem)
  965. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  966. }
  967. if (lang) {
  968. av_strlcat(key, "-", sizeof(key));
  969. av_strlcat(key, lang, sizeof(key));
  970. av_dict_set(metadata, key, tags[i].string, 0);
  971. if (tags[i].sub.nb_elem)
  972. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  973. }
  974. }
  975. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  976. }
  977. static void matroska_convert_tags(AVFormatContext *s)
  978. {
  979. MatroskaDemuxContext *matroska = s->priv_data;
  980. MatroskaTags *tags = matroska->tags.elem;
  981. int i, j;
  982. for (i=0; i < matroska->tags.nb_elem; i++) {
  983. if (tags[i].target.attachuid) {
  984. MatroskaAttachement *attachment = matroska->attachments.elem;
  985. for (j=0; j<matroska->attachments.nb_elem; j++)
  986. if (attachment[j].uid == tags[i].target.attachuid
  987. && attachment[j].stream)
  988. matroska_convert_tag(s, &tags[i].tag,
  989. &attachment[j].stream->metadata, NULL);
  990. } else if (tags[i].target.chapteruid) {
  991. MatroskaChapter *chapter = matroska->chapters.elem;
  992. for (j=0; j<matroska->chapters.nb_elem; j++)
  993. if (chapter[j].uid == tags[i].target.chapteruid
  994. && chapter[j].chapter)
  995. matroska_convert_tag(s, &tags[i].tag,
  996. &chapter[j].chapter->metadata, NULL);
  997. } else if (tags[i].target.trackuid) {
  998. MatroskaTrack *track = matroska->tracks.elem;
  999. for (j=0; j<matroska->tracks.nb_elem; j++)
  1000. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1001. matroska_convert_tag(s, &tags[i].tag,
  1002. &track[j].stream->metadata, NULL);
  1003. } else {
  1004. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1005. tags[i].target.type);
  1006. }
  1007. }
  1008. }
  1009. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1010. {
  1011. EbmlList *seekhead_list = &matroska->seekhead;
  1012. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1013. uint32_t level_up = matroska->level_up;
  1014. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1015. uint32_t saved_id = matroska->current_id;
  1016. MatroskaLevel level;
  1017. int i;
  1018. // we should not do any seeking in the streaming case
  1019. if (!matroska->ctx->pb->seekable ||
  1020. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1021. return;
  1022. for (i=0; i<seekhead_list->nb_elem; i++) {
  1023. int64_t offset = seekhead[i].pos + matroska->segment_start;
  1024. if (seekhead[i].pos <= before_pos
  1025. || seekhead[i].id == MATROSKA_ID_SEEKHEAD
  1026. || seekhead[i].id == MATROSKA_ID_CLUSTER)
  1027. continue;
  1028. /* seek */
  1029. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) != offset)
  1030. continue;
  1031. /* We don't want to lose our seekhead level, so we add
  1032. * a dummy. This is a crude hack. */
  1033. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1034. av_log(matroska->ctx, AV_LOG_INFO,
  1035. "Max EBML element depth (%d) reached, "
  1036. "cannot parse further.\n", EBML_MAX_DEPTH);
  1037. break;
  1038. }
  1039. level.start = 0;
  1040. level.length = (uint64_t)-1;
  1041. matroska->levels[matroska->num_levels] = level;
  1042. matroska->num_levels++;
  1043. matroska->current_id = 0;
  1044. ebml_parse(matroska, matroska_segment, matroska);
  1045. /* remove dummy level */
  1046. while (matroska->num_levels) {
  1047. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1048. if (length == (uint64_t)-1)
  1049. break;
  1050. }
  1051. }
  1052. /* seek back */
  1053. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1054. matroska->level_up = level_up;
  1055. matroska->current_id = saved_id;
  1056. }
  1057. static int matroska_aac_profile(char *codec_id)
  1058. {
  1059. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1060. int profile;
  1061. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1062. if (strstr(codec_id, aac_profiles[profile]))
  1063. break;
  1064. return profile + 1;
  1065. }
  1066. static int matroska_aac_sri(int samplerate)
  1067. {
  1068. int sri;
  1069. for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
  1070. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  1071. break;
  1072. return sri;
  1073. }
  1074. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1075. {
  1076. MatroskaDemuxContext *matroska = s->priv_data;
  1077. EbmlList *attachements_list = &matroska->attachments;
  1078. MatroskaAttachement *attachements;
  1079. EbmlList *chapters_list = &matroska->chapters;
  1080. MatroskaChapter *chapters;
  1081. MatroskaTrack *tracks;
  1082. EbmlList *index_list;
  1083. MatroskaIndex *index;
  1084. int index_scale = 1;
  1085. uint64_t max_start = 0;
  1086. Ebml ebml = { 0 };
  1087. AVStream *st;
  1088. int i, j, k, res;
  1089. matroska->ctx = s;
  1090. /* First read the EBML header. */
  1091. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1092. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1093. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3) {
  1094. av_log(matroska->ctx, AV_LOG_ERROR,
  1095. "EBML header using unsupported features\n"
  1096. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1097. ebml.version, ebml.doctype, ebml.doctype_version);
  1098. ebml_free(ebml_syntax, &ebml);
  1099. return AVERROR_PATCHWELCOME;
  1100. } else if (ebml.doctype_version == 3) {
  1101. av_log(matroska->ctx, AV_LOG_WARNING,
  1102. "EBML header using unsupported features\n"
  1103. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1104. ebml.version, ebml.doctype, ebml.doctype_version);
  1105. }
  1106. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1107. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1108. break;
  1109. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1110. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1111. }
  1112. ebml_free(ebml_syntax, &ebml);
  1113. /* The next thing is a segment. */
  1114. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1115. return res;
  1116. matroska_execute_seekhead(matroska);
  1117. if (!matroska->time_scale)
  1118. matroska->time_scale = 1000000;
  1119. if (matroska->duration)
  1120. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1121. * 1000 / AV_TIME_BASE;
  1122. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1123. tracks = matroska->tracks.elem;
  1124. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1125. MatroskaTrack *track = &tracks[i];
  1126. enum CodecID codec_id = CODEC_ID_NONE;
  1127. EbmlList *encodings_list = &tracks->encodings;
  1128. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1129. uint8_t *extradata = NULL;
  1130. int extradata_size = 0;
  1131. int extradata_offset = 0;
  1132. uint32_t fourcc = 0;
  1133. AVIOContext b;
  1134. /* Apply some sanity checks. */
  1135. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1136. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1137. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1138. av_log(matroska->ctx, AV_LOG_INFO,
  1139. "Unknown or unsupported track type %"PRIu64"\n",
  1140. track->type);
  1141. continue;
  1142. }
  1143. if (track->codec_id == NULL)
  1144. continue;
  1145. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1146. if (!track->default_duration)
  1147. track->default_duration = 1000000000/track->video.frame_rate;
  1148. if (!track->video.display_width)
  1149. track->video.display_width = track->video.pixel_width;
  1150. if (!track->video.display_height)
  1151. track->video.display_height = track->video.pixel_height;
  1152. if (track->video.color_space.size == 4)
  1153. fourcc = AV_RL32(track->video.color_space.data);
  1154. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1155. if (!track->audio.out_samplerate)
  1156. track->audio.out_samplerate = track->audio.samplerate;
  1157. }
  1158. if (encodings_list->nb_elem > 1) {
  1159. av_log(matroska->ctx, AV_LOG_ERROR,
  1160. "Multiple combined encodings no supported");
  1161. } else if (encodings_list->nb_elem == 1) {
  1162. if (encodings[0].type ||
  1163. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1164. #if CONFIG_ZLIB
  1165. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1166. #endif
  1167. #if CONFIG_BZLIB
  1168. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1169. #endif
  1170. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1171. encodings[0].scope = 0;
  1172. av_log(matroska->ctx, AV_LOG_ERROR,
  1173. "Unsupported encoding type");
  1174. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1175. uint8_t *codec_priv = track->codec_priv.data;
  1176. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1177. &track->codec_priv.size,
  1178. track);
  1179. if (offset < 0) {
  1180. track->codec_priv.data = NULL;
  1181. track->codec_priv.size = 0;
  1182. av_log(matroska->ctx, AV_LOG_ERROR,
  1183. "Failed to decode codec private data\n");
  1184. } else if (offset > 0) {
  1185. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1186. memcpy(track->codec_priv.data,
  1187. encodings[0].compression.settings.data, offset);
  1188. memcpy(track->codec_priv.data+offset, codec_priv,
  1189. track->codec_priv.size);
  1190. track->codec_priv.size += offset;
  1191. }
  1192. if (codec_priv != track->codec_priv.data)
  1193. av_free(codec_priv);
  1194. }
  1195. }
  1196. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1197. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1198. strlen(ff_mkv_codec_tags[j].str))){
  1199. codec_id= ff_mkv_codec_tags[j].id;
  1200. break;
  1201. }
  1202. }
  1203. st = track->stream = av_new_stream(s, 0);
  1204. if (st == NULL)
  1205. return AVERROR(ENOMEM);
  1206. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1207. && track->codec_priv.size >= 40
  1208. && track->codec_priv.data != NULL) {
  1209. track->ms_compat = 1;
  1210. fourcc = AV_RL32(track->codec_priv.data + 16);
  1211. codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
  1212. extradata_offset = 40;
  1213. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1214. && track->codec_priv.size >= 14
  1215. && track->codec_priv.data != NULL) {
  1216. int ret;
  1217. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1218. AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
  1219. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1220. if (ret < 0)
  1221. return ret;
  1222. codec_id = st->codec->codec_id;
  1223. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1224. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1225. && (track->codec_priv.size >= 86)
  1226. && (track->codec_priv.data != NULL)) {
  1227. fourcc = AV_RL32(track->codec_priv.data);
  1228. codec_id = ff_codec_get_id(codec_movvideo_tags, fourcc);
  1229. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1230. switch (track->audio.bitdepth) {
  1231. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1232. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1233. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1234. }
  1235. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1236. switch (track->audio.bitdepth) {
  1237. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1238. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1239. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1240. }
  1241. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1242. codec_id = CODEC_ID_PCM_F64LE;
  1243. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1244. int profile = matroska_aac_profile(track->codec_id);
  1245. int sri = matroska_aac_sri(track->audio.samplerate);
  1246. extradata = av_malloc(5);
  1247. if (extradata == NULL)
  1248. return AVERROR(ENOMEM);
  1249. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1250. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1251. if (strstr(track->codec_id, "SBR")) {
  1252. sri = matroska_aac_sri(track->audio.out_samplerate);
  1253. extradata[2] = 0x56;
  1254. extradata[3] = 0xE5;
  1255. extradata[4] = 0x80 | (sri<<3);
  1256. extradata_size = 5;
  1257. } else
  1258. extradata_size = 2;
  1259. } else if (codec_id == CODEC_ID_TTA) {
  1260. extradata_size = 30;
  1261. extradata = av_mallocz(extradata_size);
  1262. if (extradata == NULL)
  1263. return AVERROR(ENOMEM);
  1264. ffio_init_context(&b, extradata, extradata_size, 1,
  1265. NULL, NULL, NULL, NULL);
  1266. avio_write(&b, "TTA1", 4);
  1267. avio_wl16(&b, 1);
  1268. avio_wl16(&b, track->audio.channels);
  1269. avio_wl16(&b, track->audio.bitdepth);
  1270. avio_wl32(&b, track->audio.out_samplerate);
  1271. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1272. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1273. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1274. extradata_offset = 26;
  1275. } else if (codec_id == CODEC_ID_RA_144) {
  1276. track->audio.out_samplerate = 8000;
  1277. track->audio.channels = 1;
  1278. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1279. codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
  1280. int flavor;
  1281. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1282. 0, NULL, NULL, NULL, NULL);
  1283. avio_skip(&b, 22);
  1284. flavor = avio_rb16(&b);
  1285. track->audio.coded_framesize = avio_rb32(&b);
  1286. avio_skip(&b, 12);
  1287. track->audio.sub_packet_h = avio_rb16(&b);
  1288. track->audio.frame_size = avio_rb16(&b);
  1289. track->audio.sub_packet_size = avio_rb16(&b);
  1290. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1291. if (codec_id == CODEC_ID_RA_288) {
  1292. st->codec->block_align = track->audio.coded_framesize;
  1293. track->codec_priv.size = 0;
  1294. } else {
  1295. if (codec_id == CODEC_ID_SIPR && flavor < 4) {
  1296. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1297. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1298. st->codec->bit_rate = sipr_bit_rate[flavor];
  1299. }
  1300. st->codec->block_align = track->audio.sub_packet_size;
  1301. extradata_offset = 78;
  1302. }
  1303. }
  1304. track->codec_priv.size -= extradata_offset;
  1305. if (codec_id == CODEC_ID_NONE)
  1306. av_log(matroska->ctx, AV_LOG_INFO,
  1307. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1308. if (track->time_scale < 0.01)
  1309. track->time_scale = 1.0;
  1310. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1311. st->codec->codec_id = codec_id;
  1312. st->start_time = 0;
  1313. if (strcmp(track->language, "und"))
  1314. av_dict_set(&st->metadata, "language", track->language, 0);
  1315. av_dict_set(&st->metadata, "title", track->name, 0);
  1316. if (track->flag_default)
  1317. st->disposition |= AV_DISPOSITION_DEFAULT;
  1318. if (track->flag_forced)
  1319. st->disposition |= AV_DISPOSITION_FORCED;
  1320. if (track->default_duration)
  1321. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1322. track->default_duration, 1000000000, 30000);
  1323. if (!st->codec->extradata) {
  1324. if(extradata){
  1325. st->codec->extradata = extradata;
  1326. st->codec->extradata_size = extradata_size;
  1327. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1328. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1329. FF_INPUT_BUFFER_PADDING_SIZE);
  1330. if(st->codec->extradata == NULL)
  1331. return AVERROR(ENOMEM);
  1332. st->codec->extradata_size = track->codec_priv.size;
  1333. memcpy(st->codec->extradata,
  1334. track->codec_priv.data + extradata_offset,
  1335. track->codec_priv.size);
  1336. }
  1337. }
  1338. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1339. MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
  1340. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1341. st->codec->codec_tag = fourcc;
  1342. st->codec->width = track->video.pixel_width;
  1343. st->codec->height = track->video.pixel_height;
  1344. av_reduce(&st->sample_aspect_ratio.num,
  1345. &st->sample_aspect_ratio.den,
  1346. st->codec->height * track->video.display_width,
  1347. st->codec-> width * track->video.display_height,
  1348. 255);
  1349. if (st->codec->codec_id != CODEC_ID_H264)
  1350. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1351. if (track->default_duration)
  1352. st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
  1353. /* export stereo mode flag as metadata tag */
  1354. if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
  1355. av_dict_set(&st->metadata, "stereo_mode", matroska_video_stereo_mode[track->video.stereo_mode], 0);
  1356. /* if we have virtual track, mark the real tracks */
  1357. for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
  1358. char buf[32];
  1359. if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
  1360. continue;
  1361. snprintf(buf, sizeof(buf), "%s_%d",
  1362. matroska_video_stereo_plane[planes[j].type], i);
  1363. for (k=0; k < matroska->tracks.nb_elem; k++)
  1364. if (planes[j].uid == tracks[k].uid) {
  1365. av_dict_set(&s->streams[k]->metadata,
  1366. "stereo_mode", buf, 0);
  1367. break;
  1368. }
  1369. }
  1370. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1371. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1372. st->codec->sample_rate = track->audio.out_samplerate;
  1373. st->codec->channels = track->audio.channels;
  1374. if (st->codec->codec_id != CODEC_ID_AAC)
  1375. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1376. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1377. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1378. }
  1379. }
  1380. attachements = attachements_list->elem;
  1381. for (j=0; j<attachements_list->nb_elem; j++) {
  1382. if (!(attachements[j].filename && attachements[j].mime &&
  1383. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1384. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1385. } else {
  1386. AVStream *st = av_new_stream(s, 0);
  1387. if (st == NULL)
  1388. break;
  1389. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1390. st->codec->codec_id = CODEC_ID_NONE;
  1391. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1392. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1393. if(st->codec->extradata == NULL)
  1394. break;
  1395. st->codec->extradata_size = attachements[j].bin.size;
  1396. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1397. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1398. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1399. strlen(ff_mkv_mime_tags[i].str))) {
  1400. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1401. break;
  1402. }
  1403. }
  1404. attachements[j].stream = st;
  1405. }
  1406. }
  1407. chapters = chapters_list->elem;
  1408. for (i=0; i<chapters_list->nb_elem; i++)
  1409. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1410. && (max_start==0 || chapters[i].start > max_start)) {
  1411. chapters[i].chapter =
  1412. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1413. chapters[i].start, chapters[i].end,
  1414. chapters[i].title);
  1415. av_dict_set(&chapters[i].chapter->metadata,
  1416. "title", chapters[i].title, 0);
  1417. max_start = chapters[i].start;
  1418. }
  1419. index_list = &matroska->index;
  1420. index = index_list->elem;
  1421. if (index_list->nb_elem
  1422. && index[0].time > 100000000000000/matroska->time_scale) {
  1423. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1424. index_scale = matroska->time_scale;
  1425. }
  1426. for (i=0; i<index_list->nb_elem; i++) {
  1427. EbmlList *pos_list = &index[i].pos;
  1428. MatroskaIndexPos *pos = pos_list->elem;
  1429. for (j=0; j<pos_list->nb_elem; j++) {
  1430. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1431. pos[j].track);
  1432. if (track && track->stream)
  1433. av_add_index_entry(track->stream,
  1434. pos[j].pos + matroska->segment_start,
  1435. index[i].time/index_scale, 0, 0,
  1436. AVINDEX_KEYFRAME);
  1437. }
  1438. }
  1439. matroska_convert_tags(s);
  1440. return 0;
  1441. }
  1442. /*
  1443. * Put one packet in an application-supplied AVPacket struct.
  1444. * Returns 0 on success or -1 on failure.
  1445. */
  1446. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1447. AVPacket *pkt)
  1448. {
  1449. if (matroska->num_packets > 0) {
  1450. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1451. av_free(matroska->packets[0]);
  1452. if (matroska->num_packets > 1) {
  1453. memmove(&matroska->packets[0], &matroska->packets[1],
  1454. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1455. matroska->packets =
  1456. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1457. sizeof(AVPacket *));
  1458. } else {
  1459. av_freep(&matroska->packets);
  1460. }
  1461. matroska->num_packets--;
  1462. return 0;
  1463. }
  1464. return -1;
  1465. }
  1466. /*
  1467. * Free all packets in our internal queue.
  1468. */
  1469. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1470. {
  1471. if (matroska->packets) {
  1472. int n;
  1473. for (n = 0; n < matroska->num_packets; n++) {
  1474. av_free_packet(matroska->packets[n]);
  1475. av_free(matroska->packets[n]);
  1476. }
  1477. av_freep(&matroska->packets);
  1478. matroska->num_packets = 0;
  1479. }
  1480. }
  1481. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1482. int size, int64_t pos, uint64_t cluster_time,
  1483. uint64_t duration, int is_keyframe,
  1484. int64_t cluster_pos)
  1485. {
  1486. uint64_t timecode = AV_NOPTS_VALUE;
  1487. MatroskaTrack *track;
  1488. int res = 0;
  1489. AVStream *st;
  1490. AVPacket *pkt;
  1491. int16_t block_time;
  1492. uint32_t *lace_size = NULL;
  1493. int n, flags, laces = 0;
  1494. uint64_t num;
  1495. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1496. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1497. return res;
  1498. }
  1499. data += n;
  1500. size -= n;
  1501. track = matroska_find_track_by_num(matroska, num);
  1502. if (size <= 3 || !track || !track->stream) {
  1503. av_log(matroska->ctx, AV_LOG_INFO,
  1504. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1505. return AVERROR_INVALIDDATA;
  1506. }
  1507. st = track->stream;
  1508. if (st->discard >= AVDISCARD_ALL)
  1509. return res;
  1510. if (!duration)
  1511. duration = track->default_duration / matroska->time_scale;
  1512. block_time = AV_RB16(data);
  1513. data += 2;
  1514. flags = *data++;
  1515. size -= 3;
  1516. if (is_keyframe == -1)
  1517. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1518. if (cluster_time != (uint64_t)-1
  1519. && (block_time >= 0 || cluster_time >= -block_time)) {
  1520. timecode = cluster_time + block_time;
  1521. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1522. && timecode < track->end_timecode)
  1523. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1524. if (is_keyframe)
  1525. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1526. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1527. }
  1528. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1529. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1530. return res;
  1531. matroska->skip_to_keyframe = 0;
  1532. }
  1533. switch ((flags & 0x06) >> 1) {
  1534. case 0x0: /* no lacing */
  1535. laces = 1;
  1536. lace_size = av_mallocz(sizeof(int));
  1537. lace_size[0] = size;
  1538. break;
  1539. case 0x1: /* Xiph lacing */
  1540. case 0x2: /* fixed-size lacing */
  1541. case 0x3: /* EBML lacing */
  1542. assert(size>0); // size <=3 is checked before size-=3 above
  1543. laces = (*data) + 1;
  1544. data += 1;
  1545. size -= 1;
  1546. lace_size = av_mallocz(laces * sizeof(int));
  1547. switch ((flags & 0x06) >> 1) {
  1548. case 0x1: /* Xiph lacing */ {
  1549. uint8_t temp;
  1550. uint32_t total = 0;
  1551. for (n = 0; res == 0 && n < laces - 1; n++) {
  1552. while (1) {
  1553. if (size == 0) {
  1554. res = -1;
  1555. break;
  1556. }
  1557. temp = *data;
  1558. lace_size[n] += temp;
  1559. data += 1;
  1560. size -= 1;
  1561. if (temp != 0xff)
  1562. break;
  1563. }
  1564. total += lace_size[n];
  1565. }
  1566. lace_size[n] = size - total;
  1567. break;
  1568. }
  1569. case 0x2: /* fixed-size lacing */
  1570. for (n = 0; n < laces; n++)
  1571. lace_size[n] = size / laces;
  1572. break;
  1573. case 0x3: /* EBML lacing */ {
  1574. uint32_t total;
  1575. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1576. if (n < 0) {
  1577. av_log(matroska->ctx, AV_LOG_INFO,
  1578. "EBML block data error\n");
  1579. break;
  1580. }
  1581. data += n;
  1582. size -= n;
  1583. total = lace_size[0] = num;
  1584. for (n = 1; res == 0 && n < laces - 1; n++) {
  1585. int64_t snum;
  1586. int r;
  1587. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1588. if (r < 0) {
  1589. av_log(matroska->ctx, AV_LOG_INFO,
  1590. "EBML block data error\n");
  1591. break;
  1592. }
  1593. data += r;
  1594. size -= r;
  1595. lace_size[n] = lace_size[n - 1] + snum;
  1596. total += lace_size[n];
  1597. }
  1598. lace_size[n] = size - total;
  1599. break;
  1600. }
  1601. }
  1602. break;
  1603. }
  1604. if (res == 0) {
  1605. for (n = 0; n < laces; n++) {
  1606. if ((st->codec->codec_id == CODEC_ID_RA_288 ||
  1607. st->codec->codec_id == CODEC_ID_COOK ||
  1608. st->codec->codec_id == CODEC_ID_SIPR ||
  1609. st->codec->codec_id == CODEC_ID_ATRAC3) &&
  1610. st->codec->block_align && track->audio.sub_packet_size) {
  1611. int a = st->codec->block_align;
  1612. int sps = track->audio.sub_packet_size;
  1613. int cfs = track->audio.coded_framesize;
  1614. int h = track->audio.sub_packet_h;
  1615. int y = track->audio.sub_packet_cnt;
  1616. int w = track->audio.frame_size;
  1617. int x;
  1618. if (!track->audio.pkt_cnt) {
  1619. if (track->audio.sub_packet_cnt == 0)
  1620. track->audio.buf_timecode = timecode;
  1621. if (st->codec->codec_id == CODEC_ID_RA_288)
  1622. for (x=0; x<h/2; x++)
  1623. memcpy(track->audio.buf+x*2*w+y*cfs,
  1624. data+x*cfs, cfs);
  1625. else if (st->codec->codec_id == CODEC_ID_SIPR)
  1626. memcpy(track->audio.buf + y*w, data, w);
  1627. else
  1628. for (x=0; x<w/sps; x++)
  1629. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1630. if (++track->audio.sub_packet_cnt >= h) {
  1631. if (st->codec->codec_id == CODEC_ID_SIPR)
  1632. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1633. track->audio.sub_packet_cnt = 0;
  1634. track->audio.pkt_cnt = h*w / a;
  1635. }
  1636. }
  1637. while (track->audio.pkt_cnt) {
  1638. pkt = av_mallocz(sizeof(AVPacket));
  1639. av_new_packet(pkt, a);
  1640. memcpy(pkt->data, track->audio.buf
  1641. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1642. pkt->pts = track->audio.buf_timecode;
  1643. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1644. pkt->pos = pos;
  1645. pkt->stream_index = st->index;
  1646. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1647. }
  1648. } else {
  1649. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1650. int offset = 0, pkt_size = lace_size[n];
  1651. uint8_t *pkt_data = data;
  1652. if (pkt_size > size) {
  1653. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1654. break;
  1655. }
  1656. if (encodings && encodings->scope & 1) {
  1657. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1658. if (offset < 0)
  1659. continue;
  1660. }
  1661. pkt = av_mallocz(sizeof(AVPacket));
  1662. /* XXX: prevent data copy... */
  1663. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1664. av_free(pkt);
  1665. res = AVERROR(ENOMEM);
  1666. break;
  1667. }
  1668. if (offset)
  1669. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1670. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1671. if (pkt_data != data)
  1672. av_free(pkt_data);
  1673. if (n == 0)
  1674. pkt->flags = is_keyframe;
  1675. pkt->stream_index = st->index;
  1676. if (track->ms_compat)
  1677. pkt->dts = timecode;
  1678. else
  1679. pkt->pts = timecode;
  1680. pkt->pos = pos;
  1681. if (st->codec->codec_id == CODEC_ID_TEXT)
  1682. pkt->convergence_duration = duration;
  1683. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1684. pkt->duration = duration;
  1685. if (st->codec->codec_id == CODEC_ID_SSA)
  1686. matroska_fix_ass_packet(matroska, pkt, duration);
  1687. if (matroska->prev_pkt &&
  1688. timecode != AV_NOPTS_VALUE &&
  1689. matroska->prev_pkt->pts == timecode &&
  1690. matroska->prev_pkt->stream_index == st->index &&
  1691. st->codec->codec_id == CODEC_ID_SSA)
  1692. matroska_merge_packets(matroska->prev_pkt, pkt);
  1693. else {
  1694. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1695. matroska->prev_pkt = pkt;
  1696. }
  1697. }
  1698. if (timecode != AV_NOPTS_VALUE)
  1699. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1700. data += lace_size[n];
  1701. size -= lace_size[n];
  1702. }
  1703. }
  1704. av_free(lace_size);
  1705. return res;
  1706. }
  1707. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1708. {
  1709. MatroskaCluster cluster = { 0 };
  1710. EbmlList *blocks_list;
  1711. MatroskaBlock *blocks;
  1712. int i, res;
  1713. int64_t pos = avio_tell(matroska->ctx->pb);
  1714. matroska->prev_pkt = NULL;
  1715. if (matroska->current_id)
  1716. pos -= 4; /* sizeof the ID which was already read */
  1717. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1718. blocks_list = &cluster.blocks;
  1719. blocks = blocks_list->elem;
  1720. for (i=0; i<blocks_list->nb_elem && !res; i++)
  1721. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1722. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1723. res=matroska_parse_block(matroska,
  1724. blocks[i].bin.data, blocks[i].bin.size,
  1725. blocks[i].bin.pos, cluster.timecode,
  1726. blocks[i].duration, is_keyframe,
  1727. pos);
  1728. }
  1729. ebml_free(matroska_cluster, &cluster);
  1730. if (res < 0) matroska->done = 1;
  1731. return res;
  1732. }
  1733. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1734. {
  1735. MatroskaDemuxContext *matroska = s->priv_data;
  1736. int ret = 0;
  1737. while (!ret && matroska_deliver_packet(matroska, pkt)) {
  1738. if (matroska->done)
  1739. return AVERROR_EOF;
  1740. ret = matroska_parse_cluster(matroska);
  1741. }
  1742. return ret;
  1743. }
  1744. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1745. int64_t timestamp, int flags)
  1746. {
  1747. MatroskaDemuxContext *matroska = s->priv_data;
  1748. MatroskaTrack *tracks = matroska->tracks.elem;
  1749. AVStream *st = s->streams[stream_index];
  1750. int i, index, index_sub, index_min;
  1751. if (!st->nb_index_entries)
  1752. return 0;
  1753. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1754. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1755. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1756. matroska->current_id = 0;
  1757. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1758. matroska_clear_queue(matroska);
  1759. if (matroska_parse_cluster(matroska) < 0)
  1760. break;
  1761. }
  1762. }
  1763. matroska_clear_queue(matroska);
  1764. if (index < 0)
  1765. return 0;
  1766. index_min = index;
  1767. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1768. tracks[i].audio.pkt_cnt = 0;
  1769. tracks[i].audio.sub_packet_cnt = 0;
  1770. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  1771. tracks[i].end_timecode = 0;
  1772. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1773. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1774. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1775. if (index_sub >= 0
  1776. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1777. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1778. index_min = index_sub;
  1779. }
  1780. }
  1781. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1782. matroska->current_id = 0;
  1783. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1784. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1785. matroska->done = 0;
  1786. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1787. return 0;
  1788. }
  1789. static int matroska_read_close(AVFormatContext *s)
  1790. {
  1791. MatroskaDemuxContext *matroska = s->priv_data;
  1792. MatroskaTrack *tracks = matroska->tracks.elem;
  1793. int n;
  1794. matroska_clear_queue(matroska);
  1795. for (n=0; n < matroska->tracks.nb_elem; n++)
  1796. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1797. av_free(tracks[n].audio.buf);
  1798. ebml_free(matroska_segment, matroska);
  1799. return 0;
  1800. }
  1801. AVInputFormat ff_matroska_demuxer = {
  1802. "matroska,webm",
  1803. NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
  1804. sizeof(MatroskaDemuxContext),
  1805. matroska_probe,
  1806. matroska_read_header,
  1807. matroska_read_packet,
  1808. matroska_read_close,
  1809. matroska_read_seek,
  1810. };