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.

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