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.

1784 lines
63KB

  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. int64_t segment_start;
  179. /* the packet queue */
  180. AVPacket **packets;
  181. int num_packets;
  182. AVPacket *prev_pkt;
  183. int done;
  184. int has_cluster_id;
  185. /* What to skip before effectively reading a packet. */
  186. int skip_to_keyframe;
  187. uint64_t skip_to_timecode;
  188. } MatroskaDemuxContext;
  189. typedef struct {
  190. uint64_t duration;
  191. int64_t reference;
  192. EbmlBin bin;
  193. } MatroskaBlock;
  194. typedef struct {
  195. uint64_t timecode;
  196. EbmlList blocks;
  197. } MatroskaCluster;
  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. int64_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. int64_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. int64_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, uint64_t display_duration)
  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 + display_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\r\n",
  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_merge_packets(AVPacket *out, AVPacket *in)
  852. {
  853. out->data = av_realloc(out->data, out->size+in->size);
  854. memcpy(out->data+out->size, in->data, in->size);
  855. out->size += in->size;
  856. av_destruct_packet(in);
  857. av_free(in);
  858. }
  859. static void matroska_convert_tags(AVFormatContext *s, EbmlList *list)
  860. {
  861. MatroskaTag *tags = list->elem;
  862. int i, j;
  863. for (i=0; i < list->nb_elem; i++) {
  864. for (j=0; j < FF_ARRAY_ELEMS(metadata); j++){
  865. if (!strcmp(tags[i].name, metadata[j].name)) {
  866. int *ptr = (int *)((char *)s + metadata[j].offset);
  867. if (*ptr) continue;
  868. if (metadata[j].size > sizeof(int))
  869. av_strlcpy((char *)ptr, tags[i].string, metadata[j].size);
  870. else
  871. *ptr = atoi(tags[i].string);
  872. }
  873. }
  874. if (tags[i].sub.nb_elem)
  875. matroska_convert_tags(s, &tags[i].sub);
  876. }
  877. }
  878. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  879. {
  880. EbmlList *seekhead_list = &matroska->seekhead;
  881. MatroskaSeekhead *seekhead = seekhead_list->elem;
  882. uint32_t level_up = matroska->level_up;
  883. int64_t before_pos = url_ftell(matroska->ctx->pb);
  884. MatroskaLevel level;
  885. int i;
  886. for (i=0; i<seekhead_list->nb_elem; i++) {
  887. int64_t offset = seekhead[i].pos + matroska->segment_start;
  888. if (seekhead[i].pos <= before_pos
  889. || seekhead[i].id == MATROSKA_ID_SEEKHEAD
  890. || seekhead[i].id == MATROSKA_ID_CLUSTER)
  891. continue;
  892. /* seek */
  893. if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
  894. continue;
  895. /* We don't want to lose our seekhead level, so we add
  896. * a dummy. This is a crude hack. */
  897. if (matroska->num_levels == EBML_MAX_DEPTH) {
  898. av_log(matroska->ctx, AV_LOG_INFO,
  899. "Max EBML element depth (%d) reached, "
  900. "cannot parse further.\n", EBML_MAX_DEPTH);
  901. break;
  902. }
  903. level.start = 0;
  904. level.length = (uint64_t)-1;
  905. matroska->levels[matroska->num_levels] = level;
  906. matroska->num_levels++;
  907. ebml_parse(matroska, matroska_segment, matroska);
  908. /* remove dummy level */
  909. while (matroska->num_levels) {
  910. uint64_t length = matroska->levels[--matroska->num_levels].length;
  911. if (length == (uint64_t)-1)
  912. break;
  913. }
  914. }
  915. /* seek back */
  916. url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
  917. matroska->level_up = level_up;
  918. }
  919. static int matroska_aac_profile(char *codec_id)
  920. {
  921. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  922. int profile;
  923. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  924. if (strstr(codec_id, aac_profiles[profile]))
  925. break;
  926. return profile + 1;
  927. }
  928. static int matroska_aac_sri(int samplerate)
  929. {
  930. int sri;
  931. for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
  932. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  933. break;
  934. return sri;
  935. }
  936. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  937. {
  938. MatroskaDemuxContext *matroska = s->priv_data;
  939. EbmlList *attachements_list = &matroska->attachments;
  940. MatroskaAttachement *attachements;
  941. EbmlList *chapters_list = &matroska->chapters;
  942. MatroskaChapter *chapters;
  943. MatroskaTrack *tracks;
  944. EbmlList *index_list;
  945. MatroskaIndex *index;
  946. int index_scale = 1;
  947. Ebml ebml = { 0 };
  948. AVStream *st;
  949. int i, j;
  950. matroska->ctx = s;
  951. /* First read the EBML header. */
  952. if (ebml_parse(matroska, ebml_syntax, &ebml)
  953. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  954. || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
  955. || ebml.doctype_version > 2) {
  956. av_log(matroska->ctx, AV_LOG_ERROR,
  957. "EBML header using unsupported features\n"
  958. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  959. ebml.version, ebml.doctype, ebml.doctype_version);
  960. return AVERROR_NOFMT;
  961. }
  962. ebml_free(ebml_syntax, &ebml);
  963. /* The next thing is a segment. */
  964. if (ebml_parse(matroska, matroska_segments, matroska) < 0)
  965. return -1;
  966. matroska_execute_seekhead(matroska);
  967. if (matroska->duration)
  968. matroska->ctx->duration = matroska->duration * matroska->time_scale
  969. * 1000 / AV_TIME_BASE;
  970. if (matroska->title)
  971. strncpy(matroska->ctx->title, matroska->title,
  972. sizeof(matroska->ctx->title)-1);
  973. matroska_convert_tags(s, &matroska->tags);
  974. tracks = matroska->tracks.elem;
  975. for (i=0; i < matroska->tracks.nb_elem; i++) {
  976. MatroskaTrack *track = &tracks[i];
  977. enum CodecID codec_id = CODEC_ID_NONE;
  978. EbmlList *encodings_list = &tracks->encodings;
  979. MatroskaTrackEncoding *encodings = encodings_list->elem;
  980. uint8_t *extradata = NULL;
  981. int extradata_size = 0;
  982. int extradata_offset = 0;
  983. /* Apply some sanity checks. */
  984. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  985. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  986. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  987. av_log(matroska->ctx, AV_LOG_INFO,
  988. "Unknown or unsupported track type %"PRIu64"\n",
  989. track->type);
  990. continue;
  991. }
  992. if (track->codec_id == NULL)
  993. continue;
  994. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  995. if (!track->default_duration)
  996. track->default_duration = 1000000000/track->video.frame_rate;
  997. if (!track->video.display_width)
  998. track->video.display_width = track->video.pixel_width;
  999. if (!track->video.display_height)
  1000. track->video.display_height = track->video.pixel_height;
  1001. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1002. if (!track->audio.out_samplerate)
  1003. track->audio.out_samplerate = track->audio.samplerate;
  1004. }
  1005. if (encodings_list->nb_elem > 1) {
  1006. av_log(matroska->ctx, AV_LOG_ERROR,
  1007. "Multiple combined encodings no supported");
  1008. } else if (encodings_list->nb_elem == 1) {
  1009. if (encodings[0].type ||
  1010. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1011. #ifdef CONFIG_ZLIB
  1012. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1013. #endif
  1014. #ifdef CONFIG_BZLIB
  1015. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1016. #endif
  1017. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1018. encodings[0].scope = 0;
  1019. av_log(matroska->ctx, AV_LOG_ERROR,
  1020. "Unsupported encoding type");
  1021. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1022. uint8_t *codec_priv = track->codec_priv.data;
  1023. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1024. &track->codec_priv.size,
  1025. track);
  1026. if (offset < 0) {
  1027. track->codec_priv.data = NULL;
  1028. track->codec_priv.size = 0;
  1029. av_log(matroska->ctx, AV_LOG_ERROR,
  1030. "Failed to decode codec private data\n");
  1031. } else if (offset > 0) {
  1032. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1033. memcpy(track->codec_priv.data,
  1034. encodings[0].compression.settings.data, offset);
  1035. memcpy(track->codec_priv.data+offset, codec_priv,
  1036. track->codec_priv.size);
  1037. track->codec_priv.size += offset;
  1038. }
  1039. if (codec_priv != track->codec_priv.data)
  1040. av_free(codec_priv);
  1041. }
  1042. }
  1043. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1044. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1045. strlen(ff_mkv_codec_tags[j].str))){
  1046. codec_id= ff_mkv_codec_tags[j].id;
  1047. break;
  1048. }
  1049. }
  1050. st = track->stream = av_new_stream(s, 0);
  1051. if (st == NULL)
  1052. return AVERROR(ENOMEM);
  1053. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1054. && track->codec_priv.size >= 40
  1055. && track->codec_priv.data != NULL) {
  1056. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1057. codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
  1058. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1059. && track->codec_priv.size >= 18
  1060. && track->codec_priv.data != NULL) {
  1061. uint16_t tag = AV_RL16(track->codec_priv.data);
  1062. codec_id = codec_get_id(codec_wav_tags, tag);
  1063. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1064. && (track->codec_priv.size >= 86)
  1065. && (track->codec_priv.data != NULL)) {
  1066. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1067. codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
  1068. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1069. switch (track->audio.bitdepth) {
  1070. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1071. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1072. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1073. }
  1074. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1075. switch (track->audio.bitdepth) {
  1076. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1077. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1078. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1079. }
  1080. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1081. codec_id = CODEC_ID_PCM_F64LE;
  1082. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1083. int profile = matroska_aac_profile(track->codec_id);
  1084. int sri = matroska_aac_sri(track->audio.samplerate);
  1085. extradata = av_malloc(5);
  1086. if (extradata == NULL)
  1087. return AVERROR(ENOMEM);
  1088. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1089. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1090. if (strstr(track->codec_id, "SBR")) {
  1091. sri = matroska_aac_sri(track->audio.out_samplerate);
  1092. extradata[2] = 0x56;
  1093. extradata[3] = 0xE5;
  1094. extradata[4] = 0x80 | (sri<<3);
  1095. extradata_size = 5;
  1096. } else
  1097. extradata_size = 2;
  1098. } else if (codec_id == CODEC_ID_TTA) {
  1099. ByteIOContext b;
  1100. extradata_size = 30;
  1101. extradata = av_mallocz(extradata_size);
  1102. if (extradata == NULL)
  1103. return AVERROR(ENOMEM);
  1104. init_put_byte(&b, extradata, extradata_size, 1,
  1105. NULL, NULL, NULL, NULL);
  1106. put_buffer(&b, "TTA1", 4);
  1107. put_le16(&b, 1);
  1108. put_le16(&b, track->audio.channels);
  1109. put_le16(&b, track->audio.bitdepth);
  1110. put_le32(&b, track->audio.out_samplerate);
  1111. put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1112. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1113. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1114. extradata_offset = 26;
  1115. track->codec_priv.size -= extradata_offset;
  1116. } else if (codec_id == CODEC_ID_RA_144) {
  1117. track->audio.out_samplerate = 8000;
  1118. track->audio.channels = 1;
  1119. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1120. codec_id == CODEC_ID_ATRAC3) {
  1121. ByteIOContext b;
  1122. init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
  1123. 0, NULL, NULL, NULL, NULL);
  1124. url_fskip(&b, 24);
  1125. track->audio.coded_framesize = get_be32(&b);
  1126. url_fskip(&b, 12);
  1127. track->audio.sub_packet_h = get_be16(&b);
  1128. track->audio.frame_size = get_be16(&b);
  1129. track->audio.sub_packet_size = get_be16(&b);
  1130. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1131. if (codec_id == CODEC_ID_RA_288) {
  1132. st->codec->block_align = track->audio.coded_framesize;
  1133. track->codec_priv.size = 0;
  1134. } else {
  1135. st->codec->block_align = track->audio.sub_packet_size;
  1136. extradata_offset = 78;
  1137. track->codec_priv.size -= extradata_offset;
  1138. }
  1139. }
  1140. if (codec_id == CODEC_ID_NONE)
  1141. av_log(matroska->ctx, AV_LOG_INFO,
  1142. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1143. if (track->time_scale < 0.01)
  1144. track->time_scale = 1.0;
  1145. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1146. st->codec->codec_id = codec_id;
  1147. st->start_time = 0;
  1148. if (strcmp(track->language, "und"))
  1149. av_strlcpy(st->language, track->language, 4);
  1150. if (track->flag_default)
  1151. st->disposition |= AV_DISPOSITION_DEFAULT;
  1152. if (track->default_duration)
  1153. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1154. track->default_duration, 1000000000, 30000);
  1155. if(extradata){
  1156. st->codec->extradata = extradata;
  1157. st->codec->extradata_size = extradata_size;
  1158. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1159. st->codec->extradata = av_malloc(track->codec_priv.size);
  1160. if(st->codec->extradata == NULL)
  1161. return AVERROR(ENOMEM);
  1162. st->codec->extradata_size = track->codec_priv.size;
  1163. memcpy(st->codec->extradata,
  1164. track->codec_priv.data + extradata_offset,
  1165. track->codec_priv.size);
  1166. }
  1167. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1168. st->codec->codec_type = CODEC_TYPE_VIDEO;
  1169. st->codec->codec_tag = track->video.fourcc;
  1170. st->codec->width = track->video.pixel_width;
  1171. st->codec->height = track->video.pixel_height;
  1172. av_reduce(&st->sample_aspect_ratio.num,
  1173. &st->sample_aspect_ratio.den,
  1174. st->codec->height * track->video.display_width,
  1175. st->codec-> width * track->video.display_height,
  1176. 255);
  1177. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1178. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1179. st->codec->codec_type = CODEC_TYPE_AUDIO;
  1180. st->codec->sample_rate = track->audio.out_samplerate;
  1181. st->codec->channels = track->audio.channels;
  1182. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1183. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  1184. }
  1185. }
  1186. attachements = attachements_list->elem;
  1187. for (j=0; j<attachements_list->nb_elem; j++) {
  1188. if (!(attachements[j].filename && attachements[j].mime &&
  1189. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1190. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1191. } else {
  1192. AVStream *st = av_new_stream(s, 0);
  1193. if (st == NULL)
  1194. break;
  1195. st->filename = av_strdup(attachements[j].filename);
  1196. st->codec->codec_id = CODEC_ID_NONE;
  1197. st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
  1198. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1199. if(st->codec->extradata == NULL)
  1200. break;
  1201. st->codec->extradata_size = attachements[j].bin.size;
  1202. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1203. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1204. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1205. strlen(ff_mkv_mime_tags[i].str))) {
  1206. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1207. break;
  1208. }
  1209. }
  1210. }
  1211. }
  1212. chapters = chapters_list->elem;
  1213. for (i=0; i<chapters_list->nb_elem; i++)
  1214. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
  1215. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1216. chapters[i].start, chapters[i].end,
  1217. chapters[i].title);
  1218. index_list = &matroska->index;
  1219. index = index_list->elem;
  1220. if (index_list->nb_elem
  1221. && index[0].time > 100000000000000/matroska->time_scale) {
  1222. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1223. index_scale = matroska->time_scale;
  1224. }
  1225. for (i=0; i<index_list->nb_elem; i++) {
  1226. EbmlList *pos_list = &index[i].pos;
  1227. MatroskaIndexPos *pos = pos_list->elem;
  1228. for (j=0; j<pos_list->nb_elem; j++) {
  1229. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1230. pos[j].track);
  1231. if (track && track->stream)
  1232. av_add_index_entry(track->stream,
  1233. pos[j].pos + matroska->segment_start,
  1234. index[i].time/index_scale, 0, 0,
  1235. AVINDEX_KEYFRAME);
  1236. }
  1237. }
  1238. return 0;
  1239. }
  1240. /*
  1241. * Put one packet in an application-supplied AVPacket struct.
  1242. * Returns 0 on success or -1 on failure.
  1243. */
  1244. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1245. AVPacket *pkt)
  1246. {
  1247. if (matroska->num_packets > 0) {
  1248. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1249. av_free(matroska->packets[0]);
  1250. if (matroska->num_packets > 1) {
  1251. memmove(&matroska->packets[0], &matroska->packets[1],
  1252. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1253. matroska->packets =
  1254. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1255. sizeof(AVPacket *));
  1256. } else {
  1257. av_freep(&matroska->packets);
  1258. }
  1259. matroska->num_packets--;
  1260. return 0;
  1261. }
  1262. return -1;
  1263. }
  1264. /*
  1265. * Free all packets in our internal queue.
  1266. */
  1267. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1268. {
  1269. if (matroska->packets) {
  1270. int n;
  1271. for (n = 0; n < matroska->num_packets; n++) {
  1272. av_free_packet(matroska->packets[n]);
  1273. av_free(matroska->packets[n]);
  1274. }
  1275. av_freep(&matroska->packets);
  1276. matroska->num_packets = 0;
  1277. }
  1278. }
  1279. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1280. int size, int64_t pos, uint64_t cluster_time,
  1281. uint64_t duration, int is_keyframe,
  1282. int64_t cluster_pos)
  1283. {
  1284. uint64_t timecode = AV_NOPTS_VALUE;
  1285. MatroskaTrack *track;
  1286. int res = 0;
  1287. AVStream *st;
  1288. AVPacket *pkt;
  1289. int16_t block_time;
  1290. uint32_t *lace_size = NULL;
  1291. int n, flags, laces = 0;
  1292. uint64_t num;
  1293. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1294. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1295. return res;
  1296. }
  1297. data += n;
  1298. size -= n;
  1299. track = matroska_find_track_by_num(matroska, num);
  1300. if (size <= 3 || !track || !track->stream) {
  1301. av_log(matroska->ctx, AV_LOG_INFO,
  1302. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1303. return res;
  1304. }
  1305. st = track->stream;
  1306. if (st->discard >= AVDISCARD_ALL)
  1307. return res;
  1308. if (duration == AV_NOPTS_VALUE)
  1309. duration = track->default_duration / matroska->time_scale;
  1310. block_time = AV_RB16(data);
  1311. data += 2;
  1312. flags = *data++;
  1313. size -= 3;
  1314. if (is_keyframe == -1)
  1315. is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
  1316. if (cluster_time != (uint64_t)-1
  1317. && (block_time >= 0 || cluster_time >= -block_time)) {
  1318. timecode = cluster_time + block_time;
  1319. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1320. && timecode < track->end_timecode)
  1321. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1322. if (is_keyframe)
  1323. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1324. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1325. }
  1326. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1327. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1328. return res;
  1329. matroska->skip_to_keyframe = 0;
  1330. }
  1331. switch ((flags & 0x06) >> 1) {
  1332. case 0x0: /* no lacing */
  1333. laces = 1;
  1334. lace_size = av_mallocz(sizeof(int));
  1335. lace_size[0] = size;
  1336. break;
  1337. case 0x1: /* Xiph lacing */
  1338. case 0x2: /* fixed-size lacing */
  1339. case 0x3: /* EBML lacing */
  1340. assert(size>0); // size <=3 is checked before size-=3 above
  1341. laces = (*data) + 1;
  1342. data += 1;
  1343. size -= 1;
  1344. lace_size = av_mallocz(laces * sizeof(int));
  1345. switch ((flags & 0x06) >> 1) {
  1346. case 0x1: /* Xiph lacing */ {
  1347. uint8_t temp;
  1348. uint32_t total = 0;
  1349. for (n = 0; res == 0 && n < laces - 1; n++) {
  1350. while (1) {
  1351. if (size == 0) {
  1352. res = -1;
  1353. break;
  1354. }
  1355. temp = *data;
  1356. lace_size[n] += temp;
  1357. data += 1;
  1358. size -= 1;
  1359. if (temp != 0xff)
  1360. break;
  1361. }
  1362. total += lace_size[n];
  1363. }
  1364. lace_size[n] = size - total;
  1365. break;
  1366. }
  1367. case 0x2: /* fixed-size lacing */
  1368. for (n = 0; n < laces; n++)
  1369. lace_size[n] = size / laces;
  1370. break;
  1371. case 0x3: /* EBML lacing */ {
  1372. uint32_t total;
  1373. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1374. if (n < 0) {
  1375. av_log(matroska->ctx, AV_LOG_INFO,
  1376. "EBML block data error\n");
  1377. break;
  1378. }
  1379. data += n;
  1380. size -= n;
  1381. total = lace_size[0] = num;
  1382. for (n = 1; res == 0 && n < laces - 1; n++) {
  1383. int64_t snum;
  1384. int r;
  1385. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1386. if (r < 0) {
  1387. av_log(matroska->ctx, AV_LOG_INFO,
  1388. "EBML block data error\n");
  1389. break;
  1390. }
  1391. data += r;
  1392. size -= r;
  1393. lace_size[n] = lace_size[n - 1] + snum;
  1394. total += lace_size[n];
  1395. }
  1396. lace_size[n] = size - total;
  1397. break;
  1398. }
  1399. }
  1400. break;
  1401. }
  1402. if (res == 0) {
  1403. for (n = 0; n < laces; n++) {
  1404. if (st->codec->codec_id == CODEC_ID_RA_288 ||
  1405. st->codec->codec_id == CODEC_ID_COOK ||
  1406. st->codec->codec_id == CODEC_ID_ATRAC3) {
  1407. int a = st->codec->block_align;
  1408. int sps = track->audio.sub_packet_size;
  1409. int cfs = track->audio.coded_framesize;
  1410. int h = track->audio.sub_packet_h;
  1411. int y = track->audio.sub_packet_cnt;
  1412. int w = track->audio.frame_size;
  1413. int x;
  1414. if (!track->audio.pkt_cnt) {
  1415. if (st->codec->codec_id == CODEC_ID_RA_288)
  1416. for (x=0; x<h/2; x++)
  1417. memcpy(track->audio.buf+x*2*w+y*cfs,
  1418. data+x*cfs, cfs);
  1419. else
  1420. for (x=0; x<w/sps; x++)
  1421. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1422. if (++track->audio.sub_packet_cnt >= h) {
  1423. track->audio.sub_packet_cnt = 0;
  1424. track->audio.pkt_cnt = h*w / a;
  1425. }
  1426. }
  1427. while (track->audio.pkt_cnt) {
  1428. pkt = av_mallocz(sizeof(AVPacket));
  1429. av_new_packet(pkt, a);
  1430. memcpy(pkt->data, track->audio.buf
  1431. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1432. pkt->pos = pos;
  1433. pkt->stream_index = st->index;
  1434. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1435. }
  1436. } else {
  1437. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1438. int offset = 0, pkt_size = lace_size[n];
  1439. uint8_t *pkt_data = data;
  1440. if (encodings && encodings->scope & 1) {
  1441. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1442. if (offset < 0)
  1443. continue;
  1444. }
  1445. pkt = av_mallocz(sizeof(AVPacket));
  1446. /* XXX: prevent data copy... */
  1447. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1448. av_free(pkt);
  1449. res = AVERROR(ENOMEM);
  1450. n = laces-1;
  1451. break;
  1452. }
  1453. if (offset)
  1454. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1455. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1456. if (pkt_data != data)
  1457. av_free(pkt_data);
  1458. if (n == 0)
  1459. pkt->flags = is_keyframe;
  1460. pkt->stream_index = st->index;
  1461. pkt->pts = timecode;
  1462. pkt->pos = pos;
  1463. if (st->codec->codec_id == CODEC_ID_TEXT)
  1464. pkt->convergence_duration = duration;
  1465. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1466. pkt->duration = duration;
  1467. if (st->codec->codec_id == CODEC_ID_SSA)
  1468. matroska_fix_ass_packet(matroska, pkt, duration);
  1469. if (matroska->prev_pkt &&
  1470. timecode != AV_NOPTS_VALUE &&
  1471. matroska->prev_pkt->pts == timecode &&
  1472. matroska->prev_pkt->stream_index == st->index)
  1473. matroska_merge_packets(matroska->prev_pkt, pkt);
  1474. else {
  1475. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1476. matroska->prev_pkt = pkt;
  1477. }
  1478. }
  1479. if (timecode != AV_NOPTS_VALUE)
  1480. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1481. data += lace_size[n];
  1482. }
  1483. }
  1484. av_free(lace_size);
  1485. return res;
  1486. }
  1487. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1488. {
  1489. MatroskaCluster cluster = { 0 };
  1490. EbmlList *blocks_list;
  1491. MatroskaBlock *blocks;
  1492. int i, res;
  1493. int64_t pos = url_ftell(matroska->ctx->pb);
  1494. matroska->prev_pkt = NULL;
  1495. if (matroska->has_cluster_id){
  1496. /* For the first cluster we parse, its ID was already read as
  1497. part of matroska_read_header(), so don't read it again */
  1498. res = ebml_parse_id(matroska, matroska_clusters,
  1499. MATROSKA_ID_CLUSTER, &cluster);
  1500. pos -= 4; /* sizeof the ID which was already read */
  1501. matroska->has_cluster_id = 0;
  1502. } else
  1503. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1504. blocks_list = &cluster.blocks;
  1505. blocks = blocks_list->elem;
  1506. for (i=0; i<blocks_list->nb_elem; i++)
  1507. if (blocks[i].bin.size > 0)
  1508. res=matroska_parse_block(matroska,
  1509. blocks[i].bin.data, blocks[i].bin.size,
  1510. blocks[i].bin.pos, cluster.timecode,
  1511. blocks[i].duration, !blocks[i].reference,
  1512. pos);
  1513. ebml_free(matroska_cluster, &cluster);
  1514. if (res < 0) matroska->done = 1;
  1515. return res;
  1516. }
  1517. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1518. {
  1519. MatroskaDemuxContext *matroska = s->priv_data;
  1520. while (matroska_deliver_packet(matroska, pkt)) {
  1521. if (matroska->done)
  1522. return AVERROR(EIO);
  1523. matroska_parse_cluster(matroska);
  1524. }
  1525. return 0;
  1526. }
  1527. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1528. int64_t timestamp, int flags)
  1529. {
  1530. MatroskaDemuxContext *matroska = s->priv_data;
  1531. MatroskaTrack *tracks = matroska->tracks.elem;
  1532. AVStream *st = s->streams[stream_index];
  1533. int i, index, index_sub, index_min;
  1534. if (!st->nb_index_entries)
  1535. return 0;
  1536. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1537. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1538. url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1539. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1540. matroska_clear_queue(matroska);
  1541. if (matroska_parse_cluster(matroska) < 0)
  1542. break;
  1543. }
  1544. }
  1545. matroska_clear_queue(matroska);
  1546. if (index < 0)
  1547. return 0;
  1548. index_min = index;
  1549. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1550. tracks[i].end_timecode = 0;
  1551. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1552. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1553. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1554. if (index_sub >= 0
  1555. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1556. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1557. index_min = index_sub;
  1558. }
  1559. }
  1560. url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1561. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1562. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1563. matroska->done = 0;
  1564. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1565. return 0;
  1566. }
  1567. static int matroska_read_close(AVFormatContext *s)
  1568. {
  1569. MatroskaDemuxContext *matroska = s->priv_data;
  1570. MatroskaTrack *tracks = matroska->tracks.elem;
  1571. int n;
  1572. matroska_clear_queue(matroska);
  1573. for (n=0; n < matroska->tracks.nb_elem; n++)
  1574. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1575. av_free(tracks[n].audio.buf);
  1576. ebml_free(matroska_segment, matroska);
  1577. return 0;
  1578. }
  1579. AVInputFormat matroska_demuxer = {
  1580. "matroska",
  1581. NULL_IF_CONFIG_SMALL("Matroska file format"),
  1582. sizeof(MatroskaDemuxContext),
  1583. matroska_probe,
  1584. matroska_read_header,
  1585. matroska_read_packet,
  1586. matroska_read_close,
  1587. matroska_read_seek,
  1588. };