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 len_mask = 0x80, read = 1, n = 1;
  474. int64_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. while (read <= max_size && !(total & len_mask)) {
  490. read++;
  491. len_mask >>= 1;
  492. }
  493. if (read > max_size) {
  494. int64_t pos = url_ftell(pb) - 1;
  495. av_log(matroska->ctx, AV_LOG_ERROR,
  496. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  497. (uint8_t) total, pos, pos);
  498. return AVERROR_INVALIDDATA;
  499. }
  500. /* read out length */
  501. total &= ~len_mask;
  502. while (n++ < read)
  503. total = (total << 8) | get_byte(pb);
  504. *number = total;
  505. return read;
  506. }
  507. /*
  508. * Read the next element as an unsigned int.
  509. * 0 is success, < 0 is failure.
  510. */
  511. static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
  512. {
  513. int n = 0;
  514. if (size < 1 || size > 8)
  515. return AVERROR_INVALIDDATA;
  516. /* big-endian ordering; build up number */
  517. *num = 0;
  518. while (n++ < size)
  519. *num = (*num << 8) | get_byte(pb);
  520. return 0;
  521. }
  522. /*
  523. * Read the next element as a float.
  524. * 0 is success, < 0 is failure.
  525. */
  526. static int ebml_read_float(ByteIOContext *pb, int size, double *num)
  527. {
  528. if (size == 4) {
  529. *num= av_int2flt(get_be32(pb));
  530. } else if(size==8){
  531. *num= av_int2dbl(get_be64(pb));
  532. } else
  533. return AVERROR_INVALIDDATA;
  534. return 0;
  535. }
  536. /*
  537. * Read the next element as an ASCII string.
  538. * 0 is success, < 0 is failure.
  539. */
  540. static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
  541. {
  542. av_free(*str);
  543. /* EBML strings are usually not 0-terminated, so we allocate one
  544. * byte more, read the string and NULL-terminate it ourselves. */
  545. if (!(*str = av_malloc(size + 1)))
  546. return AVERROR(ENOMEM);
  547. if (get_buffer(pb, (uint8_t *) *str, size) != size) {
  548. av_freep(str);
  549. return AVERROR(EIO);
  550. }
  551. (*str)[size] = '\0';
  552. return 0;
  553. }
  554. /*
  555. * Read the next element as binary data.
  556. * 0 is success, < 0 is failure.
  557. */
  558. static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
  559. {
  560. av_free(bin->data);
  561. if (!(bin->data = av_malloc(length)))
  562. return AVERROR(ENOMEM);
  563. bin->size = length;
  564. bin->pos = url_ftell(pb);
  565. if (get_buffer(pb, bin->data, length) != length) {
  566. av_freep(&bin->data);
  567. return AVERROR(EIO);
  568. }
  569. return 0;
  570. }
  571. /*
  572. * Read the next element, but only the header. The contents
  573. * are supposed to be sub-elements which can be read separately.
  574. * 0 is success, < 0 is failure.
  575. */
  576. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  577. {
  578. ByteIOContext *pb = matroska->ctx->pb;
  579. MatroskaLevel *level;
  580. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  581. av_log(matroska->ctx, AV_LOG_ERROR,
  582. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  583. return AVERROR(ENOSYS);
  584. }
  585. level = &matroska->levels[matroska->num_levels++];
  586. level->start = url_ftell(pb);
  587. level->length = length;
  588. return 0;
  589. }
  590. /*
  591. * Read signed/unsigned "EBML" numbers.
  592. * Return: number of bytes processed, < 0 on error
  593. */
  594. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  595. uint8_t *data, uint32_t size, uint64_t *num)
  596. {
  597. ByteIOContext pb;
  598. init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  599. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  600. }
  601. /*
  602. * Same as above, but signed.
  603. */
  604. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  605. uint8_t *data, uint32_t size, int64_t *num)
  606. {
  607. uint64_t unum;
  608. int res;
  609. /* read as unsigned number first */
  610. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  611. return res;
  612. /* make signed (weird way) */
  613. *num = unum - ((1LL << (7*res - 1)) - 1);
  614. return res;
  615. }
  616. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  617. EbmlSyntax *syntax, void *data);
  618. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  619. uint32_t id, void *data)
  620. {
  621. int i;
  622. for (i=0; syntax[i].id; i++)
  623. if (id == syntax[i].id)
  624. break;
  625. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  626. matroska->num_levels > 0 &&
  627. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  628. return 0; // we reached the end of an unknown size cluster
  629. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
  630. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  631. return ebml_parse_elem(matroska, &syntax[i], data);
  632. }
  633. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  634. void *data)
  635. {
  636. if (!matroska->current_id) {
  637. uint64_t id;
  638. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  639. if (res < 0)
  640. return res;
  641. matroska->current_id = id | 1 << 7*res;
  642. }
  643. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  644. }
  645. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  646. void *data)
  647. {
  648. int i, res = 0;
  649. for (i=0; syntax[i].id; i++)
  650. switch (syntax[i].type) {
  651. case EBML_UINT:
  652. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  653. break;
  654. case EBML_FLOAT:
  655. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  656. break;
  657. case EBML_STR:
  658. case EBML_UTF8:
  659. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  660. break;
  661. }
  662. while (!res && !ebml_level_end(matroska))
  663. res = ebml_parse(matroska, syntax, data);
  664. return res;
  665. }
  666. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  667. EbmlSyntax *syntax, void *data)
  668. {
  669. ByteIOContext *pb = matroska->ctx->pb;
  670. uint32_t id = syntax->id;
  671. uint64_t length;
  672. int res;
  673. data = (char *)data + syntax->data_offset;
  674. if (syntax->list_elem_size) {
  675. EbmlList *list = data;
  676. list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  677. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  678. memset(data, 0, syntax->list_elem_size);
  679. list->nb_elem++;
  680. }
  681. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  682. matroska->current_id = 0;
  683. if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
  684. return res;
  685. }
  686. switch (syntax->type) {
  687. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  688. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  689. case EBML_STR:
  690. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  691. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  692. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  693. return res;
  694. if (id == MATROSKA_ID_SEGMENT)
  695. matroska->segment_start = url_ftell(matroska->ctx->pb);
  696. return ebml_parse_nest(matroska, syntax->def.n, data);
  697. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  698. case EBML_STOP: return 1;
  699. default: return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
  700. }
  701. if (res == AVERROR_INVALIDDATA)
  702. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  703. else if (res == AVERROR(EIO))
  704. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  705. return res;
  706. }
  707. static void ebml_free(EbmlSyntax *syntax, void *data)
  708. {
  709. int i, j;
  710. for (i=0; syntax[i].id; i++) {
  711. void *data_off = (char *)data + syntax[i].data_offset;
  712. switch (syntax[i].type) {
  713. case EBML_STR:
  714. case EBML_UTF8: av_freep(data_off); break;
  715. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  716. case EBML_NEST:
  717. if (syntax[i].list_elem_size) {
  718. EbmlList *list = data_off;
  719. char *ptr = list->elem;
  720. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  721. ebml_free(syntax[i].def.n, ptr);
  722. av_free(list->elem);
  723. } else
  724. ebml_free(syntax[i].def.n, data_off);
  725. default: break;
  726. }
  727. }
  728. }
  729. /*
  730. * Autodetecting...
  731. */
  732. static int matroska_probe(AVProbeData *p)
  733. {
  734. uint64_t total = 0;
  735. int len_mask = 0x80, size = 1, n = 1, i;
  736. /* EBML header? */
  737. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  738. return 0;
  739. /* length of header */
  740. total = p->buf[4];
  741. while (size <= 8 && !(total & len_mask)) {
  742. size++;
  743. len_mask >>= 1;
  744. }
  745. if (size > 8)
  746. return 0;
  747. total &= (len_mask - 1);
  748. while (n < size)
  749. total = (total << 8) | p->buf[4 + n++];
  750. /* Does the probe data contain the whole header? */
  751. if (p->buf_size < 4 + size + total)
  752. return 0;
  753. /* The header should contain a known document type. For now,
  754. * we don't parse the whole header but simply check for the
  755. * availability of that array of characters inside the header.
  756. * Not fully fool-proof, but good enough. */
  757. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  758. int probelen = strlen(matroska_doctypes[i]);
  759. for (n = 4+size; n <= 4+size+total-probelen; n++)
  760. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  761. return AVPROBE_SCORE_MAX;
  762. }
  763. // probably valid EBML header but no recognized doctype
  764. return AVPROBE_SCORE_MAX/2;
  765. }
  766. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  767. int num)
  768. {
  769. MatroskaTrack *tracks = matroska->tracks.elem;
  770. int i;
  771. for (i=0; i < matroska->tracks.nb_elem; i++)
  772. if (tracks[i].num == num)
  773. return &tracks[i];
  774. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  775. return NULL;
  776. }
  777. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  778. MatroskaTrack *track)
  779. {
  780. MatroskaTrackEncoding *encodings = track->encodings.elem;
  781. uint8_t* data = *buf;
  782. int isize = *buf_size;
  783. uint8_t* pkt_data = NULL;
  784. int pkt_size = isize;
  785. int result = 0;
  786. int olen;
  787. switch (encodings[0].compression.algo) {
  788. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  789. return encodings[0].compression.settings.size;
  790. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  791. do {
  792. olen = pkt_size *= 3;
  793. pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
  794. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  795. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  796. if (result)
  797. goto failed;
  798. pkt_size -= olen;
  799. break;
  800. #if CONFIG_ZLIB
  801. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  802. z_stream zstream = {0};
  803. if (inflateInit(&zstream) != Z_OK)
  804. return -1;
  805. zstream.next_in = data;
  806. zstream.avail_in = isize;
  807. do {
  808. pkt_size *= 3;
  809. pkt_data = av_realloc(pkt_data, pkt_size);
  810. zstream.avail_out = pkt_size - zstream.total_out;
  811. zstream.next_out = pkt_data + zstream.total_out;
  812. result = inflate(&zstream, Z_NO_FLUSH);
  813. } while (result==Z_OK && pkt_size<10000000);
  814. pkt_size = zstream.total_out;
  815. inflateEnd(&zstream);
  816. if (result != Z_STREAM_END)
  817. goto failed;
  818. break;
  819. }
  820. #endif
  821. #if CONFIG_BZLIB
  822. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  823. bz_stream bzstream = {0};
  824. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  825. return -1;
  826. bzstream.next_in = data;
  827. bzstream.avail_in = isize;
  828. do {
  829. pkt_size *= 3;
  830. pkt_data = av_realloc(pkt_data, pkt_size);
  831. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  832. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  833. result = BZ2_bzDecompress(&bzstream);
  834. } while (result==BZ_OK && pkt_size<10000000);
  835. pkt_size = bzstream.total_out_lo32;
  836. BZ2_bzDecompressEnd(&bzstream);
  837. if (result != BZ_STREAM_END)
  838. goto failed;
  839. break;
  840. }
  841. #endif
  842. default:
  843. return -1;
  844. }
  845. *buf = pkt_data;
  846. *buf_size = pkt_size;
  847. return 0;
  848. failed:
  849. av_free(pkt_data);
  850. return -1;
  851. }
  852. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  853. AVPacket *pkt, uint64_t display_duration)
  854. {
  855. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  856. for (; *ptr!=',' && ptr<end-1; ptr++);
  857. if (*ptr == ',')
  858. layer = ++ptr;
  859. for (; *ptr!=',' && ptr<end-1; ptr++);
  860. if (*ptr == ',') {
  861. int64_t end_pts = pkt->pts + display_duration;
  862. int sc = matroska->time_scale * pkt->pts / 10000000;
  863. int ec = matroska->time_scale * end_pts / 10000000;
  864. int sh, sm, ss, eh, em, es, len;
  865. sh = sc/360000; sc -= 360000*sh;
  866. sm = sc/ 6000; sc -= 6000*sm;
  867. ss = sc/ 100; sc -= 100*ss;
  868. eh = ec/360000; ec -= 360000*eh;
  869. em = ec/ 6000; ec -= 6000*em;
  870. es = ec/ 100; ec -= 100*es;
  871. *ptr++ = '\0';
  872. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  873. if (!(line = av_malloc(len)))
  874. return;
  875. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  876. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  877. av_free(pkt->data);
  878. pkt->data = line;
  879. pkt->size = strlen(line);
  880. }
  881. }
  882. static void matroska_merge_packets(AVPacket *out, AVPacket *in)
  883. {
  884. out->data = av_realloc(out->data, out->size+in->size);
  885. memcpy(out->data+out->size, in->data, in->size);
  886. out->size += in->size;
  887. av_destruct_packet(in);
  888. av_free(in);
  889. }
  890. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  891. AVMetadata **metadata, char *prefix)
  892. {
  893. MatroskaTag *tags = list->elem;
  894. char key[1024];
  895. int i;
  896. for (i=0; i < list->nb_elem; i++) {
  897. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  898. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  899. else av_strlcpy(key, tags[i].name, sizeof(key));
  900. if (tags[i].def || !lang) {
  901. av_metadata_set2(metadata, key, tags[i].string, 0);
  902. if (tags[i].sub.nb_elem)
  903. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  904. }
  905. if (lang) {
  906. av_strlcat(key, "-", sizeof(key));
  907. av_strlcat(key, lang, sizeof(key));
  908. av_metadata_set2(metadata, key, tags[i].string, 0);
  909. if (tags[i].sub.nb_elem)
  910. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  911. }
  912. }
  913. }
  914. static void matroska_convert_tags(AVFormatContext *s)
  915. {
  916. MatroskaDemuxContext *matroska = s->priv_data;
  917. MatroskaTags *tags = matroska->tags.elem;
  918. int i, j;
  919. for (i=0; i < matroska->tags.nb_elem; i++) {
  920. if (tags[i].target.attachuid) {
  921. MatroskaAttachement *attachment = matroska->attachments.elem;
  922. for (j=0; j<matroska->attachments.nb_elem; j++)
  923. if (attachment[j].uid == tags[i].target.attachuid)
  924. matroska_convert_tag(s, &tags[i].tag,
  925. &attachment[j].stream->metadata, NULL);
  926. } else if (tags[i].target.chapteruid) {
  927. MatroskaChapter *chapter = matroska->chapters.elem;
  928. for (j=0; j<matroska->chapters.nb_elem; j++)
  929. if (chapter[j].uid == tags[i].target.chapteruid)
  930. matroska_convert_tag(s, &tags[i].tag,
  931. &chapter[j].chapter->metadata, NULL);
  932. } else if (tags[i].target.trackuid) {
  933. MatroskaTrack *track = matroska->tracks.elem;
  934. for (j=0; j<matroska->tracks.nb_elem; j++)
  935. if (track[j].uid == tags[i].target.trackuid)
  936. matroska_convert_tag(s, &tags[i].tag,
  937. &track[j].stream->metadata, NULL);
  938. } else {
  939. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  940. tags[i].target.type);
  941. }
  942. }
  943. }
  944. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  945. {
  946. EbmlList *seekhead_list = &matroska->seekhead;
  947. MatroskaSeekhead *seekhead = seekhead_list->elem;
  948. uint32_t level_up = matroska->level_up;
  949. int64_t before_pos = url_ftell(matroska->ctx->pb);
  950. uint32_t saved_id = matroska->current_id;
  951. MatroskaLevel level;
  952. int i;
  953. // we should not do any seeking in the streaming case
  954. if (url_is_streamed(matroska->ctx->pb) ||
  955. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  956. return;
  957. for (i=0; i<seekhead_list->nb_elem; i++) {
  958. int64_t offset = seekhead[i].pos + matroska->segment_start;
  959. if (seekhead[i].pos <= before_pos
  960. || seekhead[i].id == MATROSKA_ID_SEEKHEAD
  961. || seekhead[i].id == MATROSKA_ID_CLUSTER)
  962. continue;
  963. /* seek */
  964. if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
  965. continue;
  966. /* We don't want to lose our seekhead level, so we add
  967. * a dummy. This is a crude hack. */
  968. if (matroska->num_levels == EBML_MAX_DEPTH) {
  969. av_log(matroska->ctx, AV_LOG_INFO,
  970. "Max EBML element depth (%d) reached, "
  971. "cannot parse further.\n", EBML_MAX_DEPTH);
  972. break;
  973. }
  974. level.start = 0;
  975. level.length = (uint64_t)-1;
  976. matroska->levels[matroska->num_levels] = level;
  977. matroska->num_levels++;
  978. matroska->current_id = 0;
  979. ebml_parse(matroska, matroska_segment, matroska);
  980. /* remove dummy level */
  981. while (matroska->num_levels) {
  982. uint64_t length = matroska->levels[--matroska->num_levels].length;
  983. if (length == (uint64_t)-1)
  984. break;
  985. }
  986. }
  987. /* seek back */
  988. url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
  989. matroska->level_up = level_up;
  990. matroska->current_id = saved_id;
  991. }
  992. static int matroska_aac_profile(char *codec_id)
  993. {
  994. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  995. int profile;
  996. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  997. if (strstr(codec_id, aac_profiles[profile]))
  998. break;
  999. return profile + 1;
  1000. }
  1001. static int matroska_aac_sri(int samplerate)
  1002. {
  1003. int sri;
  1004. for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
  1005. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  1006. break;
  1007. return sri;
  1008. }
  1009. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1010. {
  1011. MatroskaDemuxContext *matroska = s->priv_data;
  1012. EbmlList *attachements_list = &matroska->attachments;
  1013. MatroskaAttachement *attachements;
  1014. EbmlList *chapters_list = &matroska->chapters;
  1015. MatroskaChapter *chapters;
  1016. MatroskaTrack *tracks;
  1017. EbmlList *index_list;
  1018. MatroskaIndex *index;
  1019. int index_scale = 1;
  1020. uint64_t max_start = 0;
  1021. Ebml ebml = { 0 };
  1022. AVStream *st;
  1023. int i, j, res;
  1024. matroska->ctx = s;
  1025. /* First read the EBML header. */
  1026. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1027. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1028. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1029. av_log(matroska->ctx, AV_LOG_ERROR,
  1030. "EBML header using unsupported features\n"
  1031. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1032. ebml.version, ebml.doctype, ebml.doctype_version);
  1033. ebml_free(ebml_syntax, &ebml);
  1034. return AVERROR_PATCHWELCOME;
  1035. }
  1036. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1037. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1038. break;
  1039. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1040. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1041. }
  1042. ebml_free(ebml_syntax, &ebml);
  1043. /* The next thing is a segment. */
  1044. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1045. return res;
  1046. matroska_execute_seekhead(matroska);
  1047. if (!matroska->time_scale)
  1048. matroska->time_scale = 1000000;
  1049. if (matroska->duration)
  1050. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1051. * 1000 / AV_TIME_BASE;
  1052. av_metadata_set2(&s->metadata, "title", matroska->title, 0);
  1053. tracks = matroska->tracks.elem;
  1054. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1055. MatroskaTrack *track = &tracks[i];
  1056. enum CodecID codec_id = CODEC_ID_NONE;
  1057. EbmlList *encodings_list = &tracks->encodings;
  1058. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1059. uint8_t *extradata = NULL;
  1060. int extradata_size = 0;
  1061. int extradata_offset = 0;
  1062. ByteIOContext b;
  1063. /* Apply some sanity checks. */
  1064. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1065. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1066. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1067. av_log(matroska->ctx, AV_LOG_INFO,
  1068. "Unknown or unsupported track type %"PRIu64"\n",
  1069. track->type);
  1070. continue;
  1071. }
  1072. if (track->codec_id == NULL)
  1073. continue;
  1074. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1075. if (!track->default_duration)
  1076. track->default_duration = 1000000000/track->video.frame_rate;
  1077. if (!track->video.display_width)
  1078. track->video.display_width = track->video.pixel_width;
  1079. if (!track->video.display_height)
  1080. track->video.display_height = track->video.pixel_height;
  1081. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1082. if (!track->audio.out_samplerate)
  1083. track->audio.out_samplerate = track->audio.samplerate;
  1084. }
  1085. if (encodings_list->nb_elem > 1) {
  1086. av_log(matroska->ctx, AV_LOG_ERROR,
  1087. "Multiple combined encodings no supported");
  1088. } else if (encodings_list->nb_elem == 1) {
  1089. if (encodings[0].type ||
  1090. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1091. #if CONFIG_ZLIB
  1092. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1093. #endif
  1094. #if CONFIG_BZLIB
  1095. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1096. #endif
  1097. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1098. encodings[0].scope = 0;
  1099. av_log(matroska->ctx, AV_LOG_ERROR,
  1100. "Unsupported encoding type");
  1101. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1102. uint8_t *codec_priv = track->codec_priv.data;
  1103. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1104. &track->codec_priv.size,
  1105. track);
  1106. if (offset < 0) {
  1107. track->codec_priv.data = NULL;
  1108. track->codec_priv.size = 0;
  1109. av_log(matroska->ctx, AV_LOG_ERROR,
  1110. "Failed to decode codec private data\n");
  1111. } else if (offset > 0) {
  1112. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1113. memcpy(track->codec_priv.data,
  1114. encodings[0].compression.settings.data, offset);
  1115. memcpy(track->codec_priv.data+offset, codec_priv,
  1116. track->codec_priv.size);
  1117. track->codec_priv.size += offset;
  1118. }
  1119. if (codec_priv != track->codec_priv.data)
  1120. av_free(codec_priv);
  1121. }
  1122. }
  1123. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1124. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1125. strlen(ff_mkv_codec_tags[j].str))){
  1126. codec_id= ff_mkv_codec_tags[j].id;
  1127. break;
  1128. }
  1129. }
  1130. st = track->stream = av_new_stream(s, 0);
  1131. if (st == NULL)
  1132. return AVERROR(ENOMEM);
  1133. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1134. && track->codec_priv.size >= 40
  1135. && track->codec_priv.data != NULL) {
  1136. track->ms_compat = 1;
  1137. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1138. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1139. extradata_offset = 40;
  1140. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1141. && track->codec_priv.size >= 14
  1142. && track->codec_priv.data != NULL) {
  1143. init_put_byte(&b, track->codec_priv.data, track->codec_priv.size,
  1144. URL_RDONLY, NULL, NULL, NULL, NULL);
  1145. ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1146. codec_id = st->codec->codec_id;
  1147. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1148. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1149. && (track->codec_priv.size >= 86)
  1150. && (track->codec_priv.data != NULL)) {
  1151. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1152. codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
  1153. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1154. switch (track->audio.bitdepth) {
  1155. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1156. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1157. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1158. }
  1159. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1160. switch (track->audio.bitdepth) {
  1161. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1162. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1163. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1164. }
  1165. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1166. codec_id = CODEC_ID_PCM_F64LE;
  1167. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1168. int profile = matroska_aac_profile(track->codec_id);
  1169. int sri = matroska_aac_sri(track->audio.samplerate);
  1170. extradata = av_malloc(5);
  1171. if (extradata == NULL)
  1172. return AVERROR(ENOMEM);
  1173. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1174. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1175. if (strstr(track->codec_id, "SBR")) {
  1176. sri = matroska_aac_sri(track->audio.out_samplerate);
  1177. extradata[2] = 0x56;
  1178. extradata[3] = 0xE5;
  1179. extradata[4] = 0x80 | (sri<<3);
  1180. extradata_size = 5;
  1181. } else
  1182. extradata_size = 2;
  1183. } else if (codec_id == CODEC_ID_TTA) {
  1184. extradata_size = 30;
  1185. extradata = av_mallocz(extradata_size);
  1186. if (extradata == NULL)
  1187. return AVERROR(ENOMEM);
  1188. init_put_byte(&b, extradata, extradata_size, 1,
  1189. NULL, NULL, NULL, NULL);
  1190. put_buffer(&b, "TTA1", 4);
  1191. put_le16(&b, 1);
  1192. put_le16(&b, track->audio.channels);
  1193. put_le16(&b, track->audio.bitdepth);
  1194. put_le32(&b, track->audio.out_samplerate);
  1195. put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1196. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1197. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1198. extradata_offset = 26;
  1199. } else if (codec_id == CODEC_ID_RA_144) {
  1200. track->audio.out_samplerate = 8000;
  1201. track->audio.channels = 1;
  1202. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1203. codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
  1204. int flavor;
  1205. init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
  1206. 0, NULL, NULL, NULL, NULL);
  1207. url_fskip(&b, 22);
  1208. flavor = get_be16(&b);
  1209. track->audio.coded_framesize = get_be32(&b);
  1210. url_fskip(&b, 12);
  1211. track->audio.sub_packet_h = get_be16(&b);
  1212. track->audio.frame_size = get_be16(&b);
  1213. track->audio.sub_packet_size = get_be16(&b);
  1214. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1215. if (codec_id == CODEC_ID_RA_288) {
  1216. st->codec->block_align = track->audio.coded_framesize;
  1217. track->codec_priv.size = 0;
  1218. } else {
  1219. if (codec_id == CODEC_ID_SIPR && flavor < 4) {
  1220. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1221. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1222. st->codec->bit_rate = sipr_bit_rate[flavor];
  1223. }
  1224. st->codec->block_align = track->audio.sub_packet_size;
  1225. extradata_offset = 78;
  1226. }
  1227. }
  1228. track->codec_priv.size -= extradata_offset;
  1229. if (codec_id == CODEC_ID_NONE)
  1230. av_log(matroska->ctx, AV_LOG_INFO,
  1231. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1232. if (track->time_scale < 0.01)
  1233. track->time_scale = 1.0;
  1234. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1235. st->codec->codec_id = codec_id;
  1236. st->start_time = 0;
  1237. if (strcmp(track->language, "und"))
  1238. av_metadata_set2(&st->metadata, "language", track->language, 0);
  1239. av_metadata_set2(&st->metadata, "title", track->name, 0);
  1240. if (track->flag_default)
  1241. st->disposition |= AV_DISPOSITION_DEFAULT;
  1242. if (track->flag_forced)
  1243. st->disposition |= AV_DISPOSITION_FORCED;
  1244. if (track->default_duration)
  1245. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1246. track->default_duration, 1000000000, 30000);
  1247. if (!st->codec->extradata) {
  1248. if(extradata){
  1249. st->codec->extradata = extradata;
  1250. st->codec->extradata_size = extradata_size;
  1251. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1252. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1253. FF_INPUT_BUFFER_PADDING_SIZE);
  1254. if(st->codec->extradata == NULL)
  1255. return AVERROR(ENOMEM);
  1256. st->codec->extradata_size = track->codec_priv.size;
  1257. memcpy(st->codec->extradata,
  1258. track->codec_priv.data + extradata_offset,
  1259. track->codec_priv.size);
  1260. }
  1261. }
  1262. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1263. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1264. st->codec->codec_tag = track->video.fourcc;
  1265. st->codec->width = track->video.pixel_width;
  1266. st->codec->height = track->video.pixel_height;
  1267. av_reduce(&st->sample_aspect_ratio.num,
  1268. &st->sample_aspect_ratio.den,
  1269. st->codec->height * track->video.display_width,
  1270. st->codec-> width * track->video.display_height,
  1271. 255);
  1272. if (st->codec->codec_id != CODEC_ID_H264)
  1273. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1274. if (track->default_duration)
  1275. st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
  1276. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1277. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1278. st->codec->sample_rate = track->audio.out_samplerate;
  1279. st->codec->channels = track->audio.channels;
  1280. if (st->codec->codec_id != CODEC_ID_AAC)
  1281. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1282. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1283. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1284. }
  1285. }
  1286. attachements = attachements_list->elem;
  1287. for (j=0; j<attachements_list->nb_elem; j++) {
  1288. if (!(attachements[j].filename && attachements[j].mime &&
  1289. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1290. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1291. } else {
  1292. AVStream *st = av_new_stream(s, 0);
  1293. if (st == NULL)
  1294. break;
  1295. av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
  1296. st->codec->codec_id = CODEC_ID_NONE;
  1297. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1298. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1299. if(st->codec->extradata == NULL)
  1300. break;
  1301. st->codec->extradata_size = attachements[j].bin.size;
  1302. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1303. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1304. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1305. strlen(ff_mkv_mime_tags[i].str))) {
  1306. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1307. break;
  1308. }
  1309. }
  1310. attachements[j].stream = st;
  1311. }
  1312. }
  1313. chapters = chapters_list->elem;
  1314. for (i=0; i<chapters_list->nb_elem; i++)
  1315. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1316. && (max_start==0 || chapters[i].start > max_start)) {
  1317. chapters[i].chapter =
  1318. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1319. chapters[i].start, chapters[i].end,
  1320. chapters[i].title);
  1321. av_metadata_set2(&chapters[i].chapter->metadata,
  1322. "title", chapters[i].title, 0);
  1323. max_start = chapters[i].start;
  1324. }
  1325. index_list = &matroska->index;
  1326. index = index_list->elem;
  1327. if (index_list->nb_elem
  1328. && index[0].time > 100000000000000/matroska->time_scale) {
  1329. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1330. index_scale = matroska->time_scale;
  1331. }
  1332. for (i=0; i<index_list->nb_elem; i++) {
  1333. EbmlList *pos_list = &index[i].pos;
  1334. MatroskaIndexPos *pos = pos_list->elem;
  1335. for (j=0; j<pos_list->nb_elem; j++) {
  1336. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1337. pos[j].track);
  1338. if (track && track->stream)
  1339. av_add_index_entry(track->stream,
  1340. pos[j].pos + matroska->segment_start,
  1341. index[i].time/index_scale, 0, 0,
  1342. AVINDEX_KEYFRAME);
  1343. }
  1344. }
  1345. matroska_convert_tags(s);
  1346. return 0;
  1347. }
  1348. /*
  1349. * Put one packet in an application-supplied AVPacket struct.
  1350. * Returns 0 on success or -1 on failure.
  1351. */
  1352. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1353. AVPacket *pkt)
  1354. {
  1355. if (matroska->num_packets > 0) {
  1356. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1357. av_free(matroska->packets[0]);
  1358. if (matroska->num_packets > 1) {
  1359. memmove(&matroska->packets[0], &matroska->packets[1],
  1360. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1361. matroska->packets =
  1362. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1363. sizeof(AVPacket *));
  1364. } else {
  1365. av_freep(&matroska->packets);
  1366. }
  1367. matroska->num_packets--;
  1368. return 0;
  1369. }
  1370. return -1;
  1371. }
  1372. /*
  1373. * Free all packets in our internal queue.
  1374. */
  1375. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1376. {
  1377. if (matroska->packets) {
  1378. int n;
  1379. for (n = 0; n < matroska->num_packets; n++) {
  1380. av_free_packet(matroska->packets[n]);
  1381. av_free(matroska->packets[n]);
  1382. }
  1383. av_freep(&matroska->packets);
  1384. matroska->num_packets = 0;
  1385. }
  1386. }
  1387. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1388. int size, int64_t pos, uint64_t cluster_time,
  1389. uint64_t duration, int is_keyframe,
  1390. int64_t cluster_pos)
  1391. {
  1392. uint64_t timecode = AV_NOPTS_VALUE;
  1393. MatroskaTrack *track;
  1394. int res = 0;
  1395. AVStream *st;
  1396. AVPacket *pkt;
  1397. int16_t block_time;
  1398. uint32_t *lace_size = NULL;
  1399. int n, flags, laces = 0;
  1400. uint64_t num;
  1401. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1402. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1403. return res;
  1404. }
  1405. data += n;
  1406. size -= n;
  1407. track = matroska_find_track_by_num(matroska, num);
  1408. if (size <= 3 || !track || !track->stream) {
  1409. av_log(matroska->ctx, AV_LOG_INFO,
  1410. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1411. return res;
  1412. }
  1413. st = track->stream;
  1414. if (st->discard >= AVDISCARD_ALL)
  1415. return res;
  1416. if (duration == AV_NOPTS_VALUE)
  1417. duration = track->default_duration / matroska->time_scale;
  1418. block_time = AV_RB16(data);
  1419. data += 2;
  1420. flags = *data++;
  1421. size -= 3;
  1422. if (is_keyframe == -1)
  1423. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1424. if (cluster_time != (uint64_t)-1
  1425. && (block_time >= 0 || cluster_time >= -block_time)) {
  1426. timecode = cluster_time + block_time;
  1427. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1428. && timecode < track->end_timecode)
  1429. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1430. if (is_keyframe)
  1431. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1432. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1433. }
  1434. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1435. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1436. return res;
  1437. matroska->skip_to_keyframe = 0;
  1438. }
  1439. switch ((flags & 0x06) >> 1) {
  1440. case 0x0: /* no lacing */
  1441. laces = 1;
  1442. lace_size = av_mallocz(sizeof(int));
  1443. lace_size[0] = size;
  1444. break;
  1445. case 0x1: /* Xiph lacing */
  1446. case 0x2: /* fixed-size lacing */
  1447. case 0x3: /* EBML lacing */
  1448. assert(size>0); // size <=3 is checked before size-=3 above
  1449. laces = (*data) + 1;
  1450. data += 1;
  1451. size -= 1;
  1452. lace_size = av_mallocz(laces * sizeof(int));
  1453. switch ((flags & 0x06) >> 1) {
  1454. case 0x1: /* Xiph lacing */ {
  1455. uint8_t temp;
  1456. uint32_t total = 0;
  1457. for (n = 0; res == 0 && n < laces - 1; n++) {
  1458. while (1) {
  1459. if (size == 0) {
  1460. res = -1;
  1461. break;
  1462. }
  1463. temp = *data;
  1464. lace_size[n] += temp;
  1465. data += 1;
  1466. size -= 1;
  1467. if (temp != 0xff)
  1468. break;
  1469. }
  1470. total += lace_size[n];
  1471. }
  1472. lace_size[n] = size - total;
  1473. break;
  1474. }
  1475. case 0x2: /* fixed-size lacing */
  1476. for (n = 0; n < laces; n++)
  1477. lace_size[n] = size / laces;
  1478. break;
  1479. case 0x3: /* EBML lacing */ {
  1480. uint32_t total;
  1481. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1482. if (n < 0) {
  1483. av_log(matroska->ctx, AV_LOG_INFO,
  1484. "EBML block data error\n");
  1485. break;
  1486. }
  1487. data += n;
  1488. size -= n;
  1489. total = lace_size[0] = num;
  1490. for (n = 1; res == 0 && n < laces - 1; n++) {
  1491. int64_t snum;
  1492. int r;
  1493. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1494. if (r < 0) {
  1495. av_log(matroska->ctx, AV_LOG_INFO,
  1496. "EBML block data error\n");
  1497. break;
  1498. }
  1499. data += r;
  1500. size -= r;
  1501. lace_size[n] = lace_size[n - 1] + snum;
  1502. total += lace_size[n];
  1503. }
  1504. lace_size[n] = size - total;
  1505. break;
  1506. }
  1507. }
  1508. break;
  1509. }
  1510. if (res == 0) {
  1511. for (n = 0; n < laces; n++) {
  1512. if ((st->codec->codec_id == CODEC_ID_RA_288 ||
  1513. st->codec->codec_id == CODEC_ID_COOK ||
  1514. st->codec->codec_id == CODEC_ID_SIPR ||
  1515. st->codec->codec_id == CODEC_ID_ATRAC3) &&
  1516. st->codec->block_align && track->audio.sub_packet_size) {
  1517. int a = st->codec->block_align;
  1518. int sps = track->audio.sub_packet_size;
  1519. int cfs = track->audio.coded_framesize;
  1520. int h = track->audio.sub_packet_h;
  1521. int y = track->audio.sub_packet_cnt;
  1522. int w = track->audio.frame_size;
  1523. int x;
  1524. if (!track->audio.pkt_cnt) {
  1525. if (st->codec->codec_id == CODEC_ID_RA_288)
  1526. for (x=0; x<h/2; x++)
  1527. memcpy(track->audio.buf+x*2*w+y*cfs,
  1528. data+x*cfs, cfs);
  1529. else if (st->codec->codec_id == CODEC_ID_SIPR)
  1530. memcpy(track->audio.buf + y*w, data, w);
  1531. else
  1532. for (x=0; x<w/sps; x++)
  1533. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1534. if (++track->audio.sub_packet_cnt >= h) {
  1535. if (st->codec->codec_id == CODEC_ID_SIPR)
  1536. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1537. track->audio.sub_packet_cnt = 0;
  1538. track->audio.pkt_cnt = h*w / a;
  1539. }
  1540. }
  1541. while (track->audio.pkt_cnt) {
  1542. pkt = av_mallocz(sizeof(AVPacket));
  1543. av_new_packet(pkt, a);
  1544. memcpy(pkt->data, track->audio.buf
  1545. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1546. pkt->pos = pos;
  1547. pkt->stream_index = st->index;
  1548. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1549. }
  1550. } else {
  1551. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1552. int offset = 0, pkt_size = lace_size[n];
  1553. uint8_t *pkt_data = data;
  1554. if (lace_size[n] > size) {
  1555. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1556. break;
  1557. }
  1558. if (encodings && encodings->scope & 1) {
  1559. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1560. if (offset < 0)
  1561. continue;
  1562. }
  1563. pkt = av_mallocz(sizeof(AVPacket));
  1564. /* XXX: prevent data copy... */
  1565. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1566. av_free(pkt);
  1567. res = AVERROR(ENOMEM);
  1568. break;
  1569. }
  1570. if (offset)
  1571. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1572. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1573. if (pkt_data != data)
  1574. av_free(pkt_data);
  1575. if (n == 0)
  1576. pkt->flags = is_keyframe;
  1577. pkt->stream_index = st->index;
  1578. if (track->ms_compat)
  1579. pkt->dts = timecode;
  1580. else
  1581. pkt->pts = timecode;
  1582. pkt->pos = pos;
  1583. if (st->codec->codec_id == CODEC_ID_TEXT)
  1584. pkt->convergence_duration = duration;
  1585. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1586. pkt->duration = duration;
  1587. if (st->codec->codec_id == CODEC_ID_SSA)
  1588. matroska_fix_ass_packet(matroska, pkt, duration);
  1589. if (matroska->prev_pkt &&
  1590. timecode != AV_NOPTS_VALUE &&
  1591. matroska->prev_pkt->pts == timecode &&
  1592. matroska->prev_pkt->stream_index == st->index &&
  1593. st->codec->codec_id == CODEC_ID_SSA)
  1594. matroska_merge_packets(matroska->prev_pkt, pkt);
  1595. else {
  1596. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1597. matroska->prev_pkt = pkt;
  1598. }
  1599. }
  1600. if (timecode != AV_NOPTS_VALUE)
  1601. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1602. data += lace_size[n];
  1603. size -= lace_size[n];
  1604. }
  1605. }
  1606. av_free(lace_size);
  1607. return res;
  1608. }
  1609. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1610. {
  1611. MatroskaCluster cluster = { 0 };
  1612. EbmlList *blocks_list;
  1613. MatroskaBlock *blocks;
  1614. int i, res;
  1615. int64_t pos = url_ftell(matroska->ctx->pb);
  1616. matroska->prev_pkt = NULL;
  1617. if (matroska->current_id)
  1618. pos -= 4; /* sizeof the ID which was already read */
  1619. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1620. blocks_list = &cluster.blocks;
  1621. blocks = blocks_list->elem;
  1622. for (i=0; i<blocks_list->nb_elem; i++)
  1623. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1624. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1625. res=matroska_parse_block(matroska,
  1626. blocks[i].bin.data, blocks[i].bin.size,
  1627. blocks[i].bin.pos, cluster.timecode,
  1628. blocks[i].duration, is_keyframe,
  1629. pos);
  1630. }
  1631. ebml_free(matroska_cluster, &cluster);
  1632. if (res < 0) matroska->done = 1;
  1633. return res;
  1634. }
  1635. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1636. {
  1637. MatroskaDemuxContext *matroska = s->priv_data;
  1638. while (matroska_deliver_packet(matroska, pkt)) {
  1639. if (matroska->done)
  1640. return AVERROR_EOF;
  1641. matroska_parse_cluster(matroska);
  1642. }
  1643. return 0;
  1644. }
  1645. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1646. int64_t timestamp, int flags)
  1647. {
  1648. MatroskaDemuxContext *matroska = s->priv_data;
  1649. MatroskaTrack *tracks = matroska->tracks.elem;
  1650. AVStream *st = s->streams[stream_index];
  1651. int i, index, index_sub, index_min;
  1652. if (!st->nb_index_entries)
  1653. return 0;
  1654. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1655. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1656. url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1657. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1658. matroska_clear_queue(matroska);
  1659. if (matroska_parse_cluster(matroska) < 0)
  1660. break;
  1661. }
  1662. }
  1663. matroska_clear_queue(matroska);
  1664. if (index < 0)
  1665. return 0;
  1666. index_min = index;
  1667. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1668. tracks[i].end_timecode = 0;
  1669. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1670. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1671. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1672. if (index_sub >= 0
  1673. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1674. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1675. index_min = index_sub;
  1676. }
  1677. }
  1678. url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1679. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1680. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1681. matroska->done = 0;
  1682. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1683. return 0;
  1684. }
  1685. static int matroska_read_close(AVFormatContext *s)
  1686. {
  1687. MatroskaDemuxContext *matroska = s->priv_data;
  1688. MatroskaTrack *tracks = matroska->tracks.elem;
  1689. int n;
  1690. matroska_clear_queue(matroska);
  1691. for (n=0; n < matroska->tracks.nb_elem; n++)
  1692. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1693. av_free(tracks[n].audio.buf);
  1694. ebml_free(matroska_segment, matroska);
  1695. return 0;
  1696. }
  1697. AVInputFormat matroska_demuxer = {
  1698. "matroska",
  1699. NULL_IF_CONFIG_SMALL("Matroska file format"),
  1700. sizeof(MatroskaDemuxContext),
  1701. matroska_probe,
  1702. matroska_read_header,
  1703. matroska_read_packet,
  1704. matroska_read_close,
  1705. matroska_read_seek,
  1706. .metadata_conv = ff_mkv_metadata_conv,
  1707. };