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.

1760 lines
62KB

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