matroskadec.c 75 KB

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