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.

1862 lines
66KB

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