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.

2018 lines
73KB

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