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.

1912 lines
68KB

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