avidec.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  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. #include <strings.h>
  22. #include "libavutil/intreadwrite.h"
  23. #include "libavutil/bswap.h"
  24. #include "libavutil/opt.h"
  25. #include "libavutil/dict.h"
  26. #include "avformat.h"
  27. #include "avi.h"
  28. #include "dv.h"
  29. #include "riff.h"
  30. #undef NDEBUG
  31. #include <assert.h>
  32. typedef struct AVIStream {
  33. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  34. (used to compute the pts) */
  35. int remaining;
  36. int packet_size;
  37. int scale;
  38. int rate;
  39. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  40. int64_t cum_len; /* temporary storage (used during seek) */
  41. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  42. int prefix_count;
  43. uint32_t pal[256];
  44. int has_pal;
  45. int dshow_block_align; ///< block align variable used to emulate bugs in the MS dshow demuxer
  46. AVFormatContext *sub_ctx;
  47. AVPacket sub_pkt;
  48. uint8_t *sub_buffer;
  49. int64_t seek_pos;
  50. } AVIStream;
  51. typedef struct {
  52. const AVClass *class;
  53. int64_t riff_end;
  54. int64_t movi_end;
  55. int64_t fsize;
  56. int64_t movi_list;
  57. int64_t last_pkt_pos;
  58. int index_loaded;
  59. int is_odml;
  60. int non_interleaved;
  61. int stream_index;
  62. DVDemuxContext* dv_demux;
  63. int odml_depth;
  64. int use_odml;
  65. #define MAX_ODML_DEPTH 1000
  66. } AVIContext;
  67. static const AVOption options[] = {
  68. { "use_odml", "use odml index", offsetof(AVIContext, use_odml), FF_OPT_TYPE_INT, 1, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
  69. { NULL },
  70. };
  71. static const AVClass demuxer_class = {
  72. "AVI demuxer",
  73. av_default_item_name,
  74. options,
  75. LIBAVUTIL_VERSION_INT,
  76. };
  77. static const char avi_headers[][8] = {
  78. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  79. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  80. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  81. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  82. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  83. { 0 }
  84. };
  85. static int avi_load_index(AVFormatContext *s);
  86. static int guess_ni_flag(AVFormatContext *s);
  87. #define print_tag(str, tag, size) \
  88. av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
  89. str, tag & 0xff, \
  90. (tag >> 8) & 0xff, \
  91. (tag >> 16) & 0xff, \
  92. (tag >> 24) & 0xff, \
  93. size)
  94. static inline int get_duration(AVIStream *ast, int len){
  95. if(ast->sample_size){
  96. return len;
  97. }else if (ast->dshow_block_align){
  98. return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
  99. }else
  100. return 1;
  101. }
  102. static int get_riff(AVFormatContext *s, AVIOContext *pb)
  103. {
  104. AVIContext *avi = s->priv_data;
  105. char header[8];
  106. int i;
  107. /* check RIFF header */
  108. avio_read(pb, header, 4);
  109. avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
  110. avi->riff_end += avio_tell(pb); /* RIFF chunk end */
  111. avio_read(pb, header+4, 4);
  112. for(i=0; avi_headers[i][0]; i++)
  113. if(!memcmp(header, avi_headers[i], 8))
  114. break;
  115. if(!avi_headers[i][0])
  116. return -1;
  117. if(header[7] == 0x19)
  118. av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  119. return 0;
  120. }
  121. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  122. AVIContext *avi = s->priv_data;
  123. AVIOContext *pb = s->pb;
  124. int longs_pre_entry= avio_rl16(pb);
  125. int index_sub_type = avio_r8(pb);
  126. int index_type = avio_r8(pb);
  127. int entries_in_use = avio_rl32(pb);
  128. int chunk_id = avio_rl32(pb);
  129. int64_t base = avio_rl64(pb);
  130. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  131. AVStream *st;
  132. AVIStream *ast;
  133. int i;
  134. int64_t last_pos= -1;
  135. int64_t filesize= avio_size(s->pb);
  136. av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  137. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  138. if(stream_id >= s->nb_streams || stream_id < 0)
  139. return -1;
  140. st= s->streams[stream_id];
  141. ast = st->priv_data;
  142. if(index_sub_type)
  143. return -1;
  144. avio_rl32(pb);
  145. if(index_type && longs_pre_entry != 2)
  146. return -1;
  147. if(index_type>1)
  148. return -1;
  149. if(filesize > 0 && base >= filesize){
  150. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  151. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  152. base &= 0xFFFFFFFF;
  153. else
  154. return -1;
  155. }
  156. for(i=0; i<entries_in_use; i++){
  157. if(index_type){
  158. int64_t pos= avio_rl32(pb) + base - 8;
  159. int len = avio_rl32(pb);
  160. int key= len >= 0;
  161. len &= 0x7FFFFFFF;
  162. #ifdef DEBUG_SEEK
  163. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  164. #endif
  165. if(url_feof(pb))
  166. return -1;
  167. if(last_pos == pos || pos == base - 8)
  168. avi->non_interleaved= 1;
  169. if(last_pos != pos && (len || !ast->sample_size))
  170. av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
  171. ast->cum_len += get_duration(ast, len);
  172. last_pos= pos;
  173. }else{
  174. int64_t offset, pos;
  175. int duration;
  176. offset = avio_rl64(pb);
  177. avio_rl32(pb); /* size */
  178. duration = avio_rl32(pb);
  179. if(url_feof(pb))
  180. return -1;
  181. pos = avio_tell(pb);
  182. if(avi->odml_depth > MAX_ODML_DEPTH){
  183. av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
  184. return -1;
  185. }
  186. if(avio_seek(pb, offset+8, SEEK_SET) < 0)
  187. return -1;
  188. avi->odml_depth++;
  189. read_braindead_odml_indx(s, frame_num);
  190. avi->odml_depth--;
  191. frame_num += duration;
  192. if(avio_seek(pb, pos, SEEK_SET) < 0) {
  193. av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index");
  194. return -1;
  195. }
  196. }
  197. }
  198. avi->index_loaded=1;
  199. return 0;
  200. }
  201. static void clean_index(AVFormatContext *s){
  202. int i;
  203. int64_t j;
  204. for(i=0; i<s->nb_streams; i++){
  205. AVStream *st = s->streams[i];
  206. AVIStream *ast = st->priv_data;
  207. int n= st->nb_index_entries;
  208. int max= ast->sample_size;
  209. int64_t pos, size, ts;
  210. if(n != 1 || ast->sample_size==0)
  211. continue;
  212. while(max < 1024) max+=max;
  213. pos= st->index_entries[0].pos;
  214. size= st->index_entries[0].size;
  215. ts= st->index_entries[0].timestamp;
  216. for(j=0; j<size; j+=max){
  217. av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  218. }
  219. }
  220. }
  221. static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
  222. {
  223. AVIOContext *pb = s->pb;
  224. char key[5] = {0}, *value;
  225. size += (size & 1);
  226. if (size == UINT_MAX)
  227. return -1;
  228. value = av_malloc(size+1);
  229. if (!value)
  230. return -1;
  231. avio_read(pb, value, size);
  232. value[size]=0;
  233. AV_WL32(key, tag);
  234. return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
  235. AV_DICT_DONT_STRDUP_VAL);
  236. }
  237. static void avi_read_info(AVFormatContext *s, uint64_t end)
  238. {
  239. while (avio_tell(s->pb) < end) {
  240. uint32_t tag = avio_rl32(s->pb);
  241. uint32_t size = avio_rl32(s->pb);
  242. avi_read_tag(s, NULL, tag, size);
  243. }
  244. }
  245. static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  246. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  247. static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
  248. {
  249. char month[4], time[9], buffer[64];
  250. int i, day, year;
  251. /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
  252. if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
  253. month, &day, time, &year) == 4) {
  254. for (i=0; i<12; i++)
  255. if (!strcasecmp(month, months[i])) {
  256. snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
  257. year, i+1, day, time);
  258. av_dict_set(metadata, "creation_time", buffer, 0);
  259. }
  260. } else if (date[4] == '/' && date[7] == '/') {
  261. date[4] = date[7] = '-';
  262. av_dict_set(metadata, "creation_time", date, 0);
  263. }
  264. }
  265. static void avi_read_nikon(AVFormatContext *s, uint64_t end)
  266. {
  267. while (avio_tell(s->pb) < end) {
  268. uint32_t tag = avio_rl32(s->pb);
  269. uint32_t size = avio_rl32(s->pb);
  270. switch (tag) {
  271. case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
  272. uint64_t tag_end = avio_tell(s->pb) + size;
  273. while (avio_tell(s->pb) < tag_end) {
  274. uint16_t tag = avio_rl16(s->pb);
  275. uint16_t size = avio_rl16(s->pb);
  276. const char *name = NULL;
  277. char buffer[64] = {0};
  278. size -= avio_read(s->pb, buffer,
  279. FFMIN(size, sizeof(buffer)-1));
  280. switch (tag) {
  281. case 0x03: name = "maker"; break;
  282. case 0x04: name = "model"; break;
  283. case 0x13: name = "creation_time";
  284. if (buffer[4] == ':' && buffer[7] == ':')
  285. buffer[4] = buffer[7] = '-';
  286. break;
  287. }
  288. if (name)
  289. av_dict_set(&s->metadata, name, buffer, 0);
  290. avio_skip(s->pb, size);
  291. }
  292. break;
  293. }
  294. default:
  295. avio_skip(s->pb, size);
  296. break;
  297. }
  298. }
  299. }
  300. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  301. {
  302. AVIContext *avi = s->priv_data;
  303. AVIOContext *pb = s->pb;
  304. unsigned int tag, tag1, handler;
  305. int codec_type, stream_index, frame_period;
  306. unsigned int size;
  307. int i;
  308. AVStream *st;
  309. AVIStream *ast = NULL;
  310. int avih_width=0, avih_height=0;
  311. int amv_file_format=0;
  312. uint64_t list_end = 0;
  313. int ret;
  314. avi->stream_index= -1;
  315. if (get_riff(s, pb) < 0)
  316. return -1;
  317. av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
  318. avi->fsize = avio_size(pb);
  319. if(avi->fsize<=0)
  320. avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  321. /* first list tag */
  322. stream_index = -1;
  323. codec_type = -1;
  324. frame_period = 0;
  325. for(;;) {
  326. if (url_feof(pb))
  327. goto fail;
  328. tag = avio_rl32(pb);
  329. size = avio_rl32(pb);
  330. print_tag("tag", tag, size);
  331. switch(tag) {
  332. case MKTAG('L', 'I', 'S', 'T'):
  333. list_end = avio_tell(pb) + size;
  334. /* Ignored, except at start of video packets. */
  335. tag1 = avio_rl32(pb);
  336. print_tag("list", tag1, 0);
  337. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  338. avi->movi_list = avio_tell(pb) - 4;
  339. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  340. else avi->movi_end = avio_size(pb);
  341. av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  342. goto end_of_header;
  343. }
  344. else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  345. avi_read_info(s, list_end);
  346. else if (tag1 == MKTAG('n', 'c', 'd', 't'))
  347. avi_read_nikon(s, list_end);
  348. break;
  349. case MKTAG('I', 'D', 'I', 'T'): {
  350. unsigned char date[64] = {0};
  351. size += (size & 1);
  352. size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
  353. avio_skip(pb, size);
  354. avi_metadata_creation_time(&s->metadata, date);
  355. break;
  356. }
  357. case MKTAG('d', 'm', 'l', 'h'):
  358. avi->is_odml = 1;
  359. avio_skip(pb, size + (size & 1));
  360. break;
  361. case MKTAG('a', 'm', 'v', 'h'):
  362. amv_file_format=1;
  363. case MKTAG('a', 'v', 'i', 'h'):
  364. /* AVI header */
  365. /* using frame_period is bad idea */
  366. frame_period = avio_rl32(pb);
  367. avio_rl32(pb); /* max. bytes per second */
  368. avio_rl32(pb);
  369. avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
  370. avio_skip(pb, 2 * 4);
  371. avio_rl32(pb);
  372. avio_rl32(pb);
  373. avih_width=avio_rl32(pb);
  374. avih_height=avio_rl32(pb);
  375. avio_skip(pb, size - 10 * 4);
  376. break;
  377. case MKTAG('s', 't', 'r', 'h'):
  378. /* stream header */
  379. tag1 = avio_rl32(pb);
  380. handler = avio_rl32(pb); /* codec tag */
  381. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  382. avio_skip(pb, size - 8);
  383. break;
  384. }else{
  385. stream_index++;
  386. st = av_new_stream(s, stream_index);
  387. if (!st)
  388. goto fail;
  389. ast = av_mallocz(sizeof(AVIStream));
  390. if (!ast)
  391. goto fail;
  392. st->priv_data = ast;
  393. }
  394. if(amv_file_format)
  395. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  396. print_tag("strh", tag1, -1);
  397. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  398. int64_t dv_dur;
  399. /*
  400. * After some consideration -- I don't think we
  401. * have to support anything but DV in type1 AVIs.
  402. */
  403. if (s->nb_streams != 1)
  404. goto fail;
  405. if (handler != MKTAG('d', 'v', 's', 'd') &&
  406. handler != MKTAG('d', 'v', 'h', 'd') &&
  407. handler != MKTAG('d', 'v', 's', 'l'))
  408. goto fail;
  409. ast = s->streams[0]->priv_data;
  410. av_freep(&s->streams[0]->codec->extradata);
  411. av_freep(&s->streams[0]->codec);
  412. av_freep(&s->streams[0]);
  413. s->nb_streams = 0;
  414. if (CONFIG_DV_DEMUXER) {
  415. avi->dv_demux = dv_init_demux(s);
  416. if (!avi->dv_demux)
  417. goto fail;
  418. }
  419. s->streams[0]->priv_data = ast;
  420. avio_skip(pb, 3 * 4);
  421. ast->scale = avio_rl32(pb);
  422. ast->rate = avio_rl32(pb);
  423. avio_skip(pb, 4); /* start time */
  424. dv_dur = avio_rl32(pb);
  425. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  426. dv_dur *= AV_TIME_BASE;
  427. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  428. }
  429. /*
  430. * else, leave duration alone; timing estimation in utils.c
  431. * will make a guess based on bitrate.
  432. */
  433. stream_index = s->nb_streams - 1;
  434. avio_skip(pb, size - 9*4);
  435. break;
  436. }
  437. assert(stream_index < s->nb_streams);
  438. st->codec->stream_codec_tag= handler;
  439. avio_rl32(pb); /* flags */
  440. avio_rl16(pb); /* priority */
  441. avio_rl16(pb); /* language */
  442. avio_rl32(pb); /* initial frame */
  443. ast->scale = avio_rl32(pb);
  444. ast->rate = avio_rl32(pb);
  445. if(!(ast->scale && ast->rate)){
  446. av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
  447. if(frame_period){
  448. ast->rate = 1000000;
  449. ast->scale = frame_period;
  450. }else{
  451. ast->rate = 25;
  452. ast->scale = 1;
  453. }
  454. }
  455. av_set_pts_info(st, 64, ast->scale, ast->rate);
  456. ast->cum_len=avio_rl32(pb); /* start */
  457. st->nb_frames = avio_rl32(pb);
  458. st->start_time = 0;
  459. avio_rl32(pb); /* buffer size */
  460. avio_rl32(pb); /* quality */
  461. ast->sample_size = avio_rl32(pb); /* sample ssize */
  462. ast->cum_len *= FFMAX(1, ast->sample_size);
  463. // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  464. switch(tag1) {
  465. case MKTAG('v', 'i', 'd', 's'):
  466. codec_type = AVMEDIA_TYPE_VIDEO;
  467. ast->sample_size = 0;
  468. break;
  469. case MKTAG('a', 'u', 'd', 's'):
  470. codec_type = AVMEDIA_TYPE_AUDIO;
  471. break;
  472. case MKTAG('t', 'x', 't', 's'):
  473. codec_type = AVMEDIA_TYPE_SUBTITLE;
  474. break;
  475. case MKTAG('d', 'a', 't', 's'):
  476. codec_type = AVMEDIA_TYPE_DATA;
  477. break;
  478. default:
  479. av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
  480. }
  481. if(ast->sample_size == 0)
  482. st->duration = st->nb_frames;
  483. ast->frame_offset= ast->cum_len;
  484. avio_skip(pb, size - 12 * 4);
  485. break;
  486. case MKTAG('s', 't', 'r', 'f'):
  487. /* stream header */
  488. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  489. avio_skip(pb, size);
  490. } else {
  491. uint64_t cur_pos = avio_tell(pb);
  492. if (cur_pos < list_end)
  493. size = FFMIN(size, list_end - cur_pos);
  494. st = s->streams[stream_index];
  495. switch(codec_type) {
  496. case AVMEDIA_TYPE_VIDEO:
  497. if(amv_file_format){
  498. st->codec->width=avih_width;
  499. st->codec->height=avih_height;
  500. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  501. st->codec->codec_id = CODEC_ID_AMV;
  502. avio_skip(pb, size);
  503. break;
  504. }
  505. tag1 = ff_get_bmp_header(pb, st);
  506. if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
  507. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  508. st->codec->codec_tag = tag1;
  509. st->codec->codec_id = CODEC_ID_XSUB;
  510. break;
  511. }
  512. if(size > 10*4 && size<(1<<30)){
  513. st->codec->extradata_size= size - 10*4;
  514. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  515. if (!st->codec->extradata) {
  516. st->codec->extradata_size= 0;
  517. return AVERROR(ENOMEM);
  518. }
  519. avio_read(pb, st->codec->extradata, st->codec->extradata_size);
  520. }
  521. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  522. avio_r8(pb);
  523. /* Extract palette from extradata if bpp <= 8. */
  524. /* This code assumes that extradata contains only palette. */
  525. /* This is true for all paletted codecs implemented in FFmpeg. */
  526. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  527. int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
  528. const uint8_t *pal_src;
  529. pal_size = FFMIN(pal_size, st->codec->extradata_size);
  530. pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
  531. #if HAVE_BIGENDIAN
  532. for (i = 0; i < pal_size/4; i++)
  533. ast->pal[i] = AV_RL32(pal_src+4*i);
  534. #else
  535. memcpy(ast->pal, pal_src, pal_size);
  536. #endif
  537. ast->has_pal = 1;
  538. }
  539. print_tag("video", tag1, 0);
  540. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  541. st->codec->codec_tag = tag1;
  542. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
  543. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  544. // Support "Resolution 1:1" for Avid AVI Codec
  545. if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
  546. st->codec->extradata_size >= 31 &&
  547. !memcmp(&st->codec->extradata[28], "1:1", 3))
  548. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  549. if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
  550. st->codec->extradata_size+= 9;
  551. st->codec->extradata= av_realloc_f(st->codec->extradata, 1, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  552. if(st->codec->extradata)
  553. memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
  554. }
  555. st->codec->height= FFABS(st->codec->height);
  556. // avio_skip(pb, size - 5 * 4);
  557. break;
  558. case AVMEDIA_TYPE_AUDIO:
  559. ret = ff_get_wav_header(pb, st->codec, size);
  560. if (ret < 0)
  561. return ret;
  562. ast->dshow_block_align= st->codec->block_align;
  563. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  564. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  565. ast->sample_size= st->codec->block_align;
  566. }
  567. if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  568. avio_skip(pb, 1);
  569. /* Force parsing as several audio frames can be in
  570. * one packet and timestamps refer to packet start. */
  571. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  572. /* ADTS header is in extradata, AAC without header must be
  573. * stored as exact frames. Parser not needed and it will
  574. * fail. */
  575. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  576. st->need_parsing = AVSTREAM_PARSE_NONE;
  577. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  578. * audio in the header but have Axan as stream_code_tag. */
  579. if (st->codec->stream_codec_tag == AV_RL32("Axan")){
  580. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  581. st->codec->codec_tag = 0;
  582. }
  583. if (amv_file_format){
  584. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  585. ast->dshow_block_align = 0;
  586. }
  587. break;
  588. case AVMEDIA_TYPE_SUBTITLE:
  589. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  590. st->request_probe= 1;
  591. break;
  592. default:
  593. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  594. st->codec->codec_id= CODEC_ID_NONE;
  595. st->codec->codec_tag= 0;
  596. avio_skip(pb, size);
  597. break;
  598. }
  599. }
  600. break;
  601. case MKTAG('i', 'n', 'd', 'x'):
  602. i= avio_tell(pb);
  603. if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml){
  604. read_braindead_odml_indx(s, 0);
  605. }
  606. avio_seek(pb, i+size, SEEK_SET);
  607. break;
  608. case MKTAG('v', 'p', 'r', 'p'):
  609. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  610. AVRational active, active_aspect;
  611. st = s->streams[stream_index];
  612. avio_rl32(pb);
  613. avio_rl32(pb);
  614. avio_rl32(pb);
  615. avio_rl32(pb);
  616. avio_rl32(pb);
  617. active_aspect.den= avio_rl16(pb);
  618. active_aspect.num= avio_rl16(pb);
  619. active.num = avio_rl32(pb);
  620. active.den = avio_rl32(pb);
  621. avio_rl32(pb); //nbFieldsPerFrame
  622. if(active_aspect.num && active_aspect.den && active.num && active.den){
  623. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  624. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  625. }
  626. size -= 9*4;
  627. }
  628. avio_skip(pb, size);
  629. break;
  630. case MKTAG('s', 't', 'r', 'n'):
  631. if(s->nb_streams){
  632. avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
  633. break;
  634. }
  635. default:
  636. if(size > 1000000){
  637. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  638. "I will ignore it and try to continue anyway.\n");
  639. avi->movi_list = avio_tell(pb) - 4;
  640. avi->movi_end = avio_size(pb);
  641. goto end_of_header;
  642. }
  643. /* skip tag */
  644. size += (size & 1);
  645. avio_skip(pb, size);
  646. break;
  647. }
  648. }
  649. end_of_header:
  650. /* check stream number */
  651. if (stream_index != s->nb_streams - 1) {
  652. fail:
  653. return -1;
  654. }
  655. if(!avi->index_loaded && pb->seekable)
  656. avi_load_index(s);
  657. avi->index_loaded = 1;
  658. avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
  659. for(i=0; i<s->nb_streams; i++){
  660. AVStream *st = s->streams[i];
  661. if(st->nb_index_entries)
  662. break;
  663. }
  664. // DV-in-AVI cannot be non-interleaved, if set this must be
  665. // a mis-detection.
  666. if(avi->dv_demux)
  667. avi->non_interleaved=0;
  668. if(i==s->nb_streams && avi->non_interleaved) {
  669. av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
  670. avi->non_interleaved=0;
  671. }
  672. if(avi->non_interleaved) {
  673. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  674. clean_index(s);
  675. }
  676. ff_metadata_conv_ctx(s, NULL, ff_avi_metadata_conv);
  677. return 0;
  678. }
  679. static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
  680. if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
  681. uint8_t desc[256];
  682. int score = AVPROBE_SCORE_MAX / 2, ret;
  683. AVIStream *ast = st->priv_data;
  684. AVInputFormat *sub_demuxer;
  685. AVRational time_base;
  686. AVIOContext *pb = avio_alloc_context( pkt->data + 7,
  687. pkt->size - 7,
  688. 0, NULL, NULL, NULL, NULL);
  689. AVProbeData pd;
  690. unsigned int desc_len = avio_rl32(pb);
  691. if (desc_len > pb->buf_end - pb->buf_ptr)
  692. goto error;
  693. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  694. avio_skip(pb, desc_len - ret);
  695. if (*desc)
  696. av_dict_set(&st->metadata, "title", desc, 0);
  697. avio_rl16(pb); /* flags? */
  698. avio_rl32(pb); /* data size */
  699. pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
  700. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  701. goto error;
  702. if (!(ast->sub_ctx = avformat_alloc_context()))
  703. goto error;
  704. ast->sub_ctx->pb = pb;
  705. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  706. av_read_packet(ast->sub_ctx, &ast->sub_pkt);
  707. *st->codec = *ast->sub_ctx->streams[0]->codec;
  708. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  709. time_base = ast->sub_ctx->streams[0]->time_base;
  710. av_set_pts_info(st, 64, time_base.num, time_base.den);
  711. }
  712. ast->sub_buffer = pkt->data;
  713. memset(pkt, 0, sizeof(*pkt));
  714. return 1;
  715. error:
  716. av_freep(&pb);
  717. }
  718. return 0;
  719. }
  720. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  721. AVPacket *pkt)
  722. {
  723. AVIStream *ast, *next_ast = next_st->priv_data;
  724. int64_t ts, next_ts, ts_min = INT64_MAX;
  725. AVStream *st, *sub_st = NULL;
  726. int i;
  727. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  728. AV_TIME_BASE_Q);
  729. for (i=0; i<s->nb_streams; i++) {
  730. st = s->streams[i];
  731. ast = st->priv_data;
  732. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  733. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  734. if (ts <= next_ts && ts < ts_min) {
  735. ts_min = ts;
  736. sub_st = st;
  737. }
  738. }
  739. }
  740. if (sub_st) {
  741. ast = sub_st->priv_data;
  742. *pkt = ast->sub_pkt;
  743. pkt->stream_index = sub_st->index;
  744. if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  745. ast->sub_pkt.data = NULL;
  746. }
  747. return sub_st;
  748. }
  749. static int get_stream_idx(int *d){
  750. if( d[0] >= '0' && d[0] <= '9'
  751. && d[1] >= '0' && d[1] <= '9'){
  752. return (d[0] - '0') * 10 + (d[1] - '0');
  753. }else{
  754. return 100; //invalid stream ID
  755. }
  756. }
  757. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  758. {
  759. AVIContext *avi = s->priv_data;
  760. AVIOContext *pb = s->pb;
  761. int n, d[8];
  762. unsigned int size;
  763. int64_t i, sync;
  764. void* dstr;
  765. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  766. int size = dv_get_packet(avi->dv_demux, pkt);
  767. if (size >= 0)
  768. return size;
  769. }
  770. if(avi->non_interleaved){
  771. int best_stream_index = 0;
  772. AVStream *best_st= NULL;
  773. AVIStream *best_ast;
  774. int64_t best_ts= INT64_MAX;
  775. int i;
  776. for(i=0; i<s->nb_streams; i++){
  777. AVStream *st = s->streams[i];
  778. AVIStream *ast = st->priv_data;
  779. int64_t ts= ast->frame_offset;
  780. int64_t last_ts;
  781. if(!st->nb_index_entries)
  782. continue;
  783. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  784. if(!ast->remaining && ts > last_ts)
  785. continue;
  786. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  787. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  788. if(ts < best_ts){
  789. best_ts= ts;
  790. best_st= st;
  791. best_stream_index= i;
  792. }
  793. }
  794. if(!best_st)
  795. return -1;
  796. best_ast = best_st->priv_data;
  797. best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
  798. if(best_ast->remaining)
  799. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  800. else{
  801. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  802. if(i>=0)
  803. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  804. }
  805. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  806. if(i>=0){
  807. int64_t pos= best_st->index_entries[i].pos;
  808. pos += best_ast->packet_size - best_ast->remaining;
  809. avio_seek(s->pb, pos + 8, SEEK_SET);
  810. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  811. assert(best_ast->remaining <= best_ast->packet_size);
  812. avi->stream_index= best_stream_index;
  813. if(!best_ast->remaining)
  814. best_ast->packet_size=
  815. best_ast->remaining= best_st->index_entries[i].size;
  816. }
  817. }
  818. resync:
  819. if(avi->stream_index >= 0){
  820. AVStream *st= s->streams[ avi->stream_index ];
  821. AVIStream *ast= st->priv_data;
  822. int size, err;
  823. if(get_subtitle_pkt(s, st, pkt))
  824. return 0;
  825. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  826. size= INT_MAX;
  827. else if(ast->sample_size < 32)
  828. // arbitrary multiplier to avoid tiny packets for raw PCM data
  829. size= 1024*ast->sample_size;
  830. else
  831. size= ast->sample_size;
  832. if(size > ast->remaining)
  833. size= ast->remaining;
  834. avi->last_pkt_pos= avio_tell(pb);
  835. err= av_get_packet(pb, pkt, size);
  836. if(err<0)
  837. return err;
  838. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  839. uint8_t *pal;
  840. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  841. if(!pal){
  842. av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
  843. }else{
  844. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  845. ast->has_pal = 0;
  846. }
  847. }
  848. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  849. dstr = pkt->destruct;
  850. size = dv_produce_packet(avi->dv_demux, pkt,
  851. pkt->data, pkt->size, pkt->pos);
  852. pkt->destruct = dstr;
  853. pkt->flags |= AV_PKT_FLAG_KEY;
  854. if (size < 0)
  855. av_free_packet(pkt);
  856. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
  857. && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  858. ast->frame_offset++;
  859. avi->stream_index = -1;
  860. ast->remaining = 0;
  861. goto resync;
  862. } else {
  863. /* XXX: How to handle B-frames in AVI? */
  864. pkt->dts = ast->frame_offset;
  865. // pkt->dts += ast->start;
  866. if(ast->sample_size)
  867. pkt->dts /= ast->sample_size;
  868. //av_log(s, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
  869. pkt->stream_index = avi->stream_index;
  870. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  871. AVIndexEntry *e;
  872. int index;
  873. assert(st->index_entries);
  874. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  875. e= &st->index_entries[index];
  876. if(index >= 0 && e->timestamp == ast->frame_offset){
  877. if (index == st->nb_index_entries-1){
  878. int key=1;
  879. int i;
  880. uint32_t state=-1;
  881. for(i=0; i<FFMIN(size,256); i++){
  882. if(st->codec->codec_id == CODEC_ID_MPEG4){
  883. if(state == 0x1B6){
  884. key= !(pkt->data[i]&0xC0);
  885. break;
  886. }
  887. }else
  888. break;
  889. state= (state<<8) + pkt->data[i];
  890. }
  891. if(!key)
  892. e->flags &= ~AVINDEX_KEYFRAME;
  893. }
  894. if (e->flags & AVINDEX_KEYFRAME)
  895. pkt->flags |= AV_PKT_FLAG_KEY;
  896. }
  897. } else {
  898. pkt->flags |= AV_PKT_FLAG_KEY;
  899. }
  900. ast->frame_offset += get_duration(ast, pkt->size);
  901. }
  902. ast->remaining -= err;
  903. if(!ast->remaining){
  904. avi->stream_index= -1;
  905. ast->packet_size= 0;
  906. }
  907. if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
  908. av_free_packet(pkt);
  909. goto resync;
  910. }
  911. ast->seek_pos= 0;
  912. return 0;
  913. }
  914. memset(d, -1, sizeof(int)*8);
  915. for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
  916. int j;
  917. for(j=0; j<7; j++)
  918. d[j]= d[j+1];
  919. d[7]= avio_r8(pb);
  920. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  921. n= get_stream_idx(d+2);
  922. //av_log(s, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  923. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  924. continue;
  925. //parse ix##
  926. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  927. //parse JUNK
  928. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  929. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  930. avio_skip(pb, size);
  931. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  932. goto resync;
  933. }
  934. //parse stray LIST
  935. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  936. avio_skip(pb, 4);
  937. goto resync;
  938. }
  939. n= get_stream_idx(d);
  940. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  941. continue;
  942. //detect ##ix chunk and skip
  943. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  944. avio_skip(pb, size);
  945. goto resync;
  946. }
  947. //parse ##dc/##wb
  948. if(n < s->nb_streams){
  949. AVStream *st;
  950. AVIStream *ast;
  951. st = s->streams[n];
  952. ast = st->priv_data;
  953. if(s->nb_streams>=2){
  954. AVStream *st1 = s->streams[1];
  955. AVIStream *ast1= st1->priv_data;
  956. //workaround for broken small-file-bug402.avi
  957. if( d[2] == 'w' && d[3] == 'b'
  958. && n==0
  959. && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
  960. && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
  961. && ast->prefix == 'd'*256+'c'
  962. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  963. ){
  964. n=1;
  965. st = st1;
  966. ast = ast1;
  967. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  968. }
  969. }
  970. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  971. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  972. || st->discard >= AVDISCARD_ALL){
  973. ast->frame_offset += get_duration(ast, size);
  974. avio_skip(pb, size);
  975. goto resync;
  976. }
  977. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  978. int k = avio_r8(pb);
  979. int last = (k + avio_r8(pb) - 1) & 0xFF;
  980. avio_rl16(pb); //flags
  981. for (; k <= last; k++)
  982. ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
  983. ast->has_pal= 1;
  984. goto resync;
  985. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  986. d[2]*256+d[3] == ast->prefix /*||
  987. (d[2] == 'd' && d[3] == 'c') ||
  988. (d[2] == 'w' && d[3] == 'b')*/) {
  989. //av_log(s, AV_LOG_DEBUG, "OK\n");
  990. if(d[2]*256+d[3] == ast->prefix)
  991. ast->prefix_count++;
  992. else{
  993. ast->prefix= d[2]*256+d[3];
  994. ast->prefix_count= 0;
  995. }
  996. avi->stream_index= n;
  997. ast->packet_size= size + 8;
  998. ast->remaining= size;
  999. if(size || !ast->sample_size){
  1000. uint64_t pos= avio_tell(pb) - 8;
  1001. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  1002. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  1003. }
  1004. }
  1005. goto resync;
  1006. }
  1007. }
  1008. }
  1009. return AVERROR_EOF;
  1010. }
  1011. /* XXX: We make the implicit supposition that the positions are sorted
  1012. for each stream. */
  1013. static int avi_read_idx1(AVFormatContext *s, int size)
  1014. {
  1015. AVIContext *avi = s->priv_data;
  1016. AVIOContext *pb = s->pb;
  1017. int nb_index_entries, i;
  1018. AVStream *st;
  1019. AVIStream *ast;
  1020. unsigned int index, tag, flags, pos, len;
  1021. unsigned last_pos= -1;
  1022. nb_index_entries = size / 16;
  1023. if (nb_index_entries <= 0)
  1024. return -1;
  1025. /* Read the entries and sort them in each stream component. */
  1026. for(i = 0; i < nb_index_entries; i++) {
  1027. tag = avio_rl32(pb);
  1028. flags = avio_rl32(pb);
  1029. pos = avio_rl32(pb);
  1030. len = avio_rl32(pb);
  1031. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1032. i, tag, flags, pos, len);
  1033. if(i==0 && pos > avi->movi_list)
  1034. avi->movi_list= 0; //FIXME better check
  1035. pos += avi->movi_list;
  1036. index = ((tag & 0xff) - '0') * 10;
  1037. index += ((tag >> 8) & 0xff) - '0';
  1038. if (index >= s->nb_streams)
  1039. continue;
  1040. st = s->streams[index];
  1041. ast = st->priv_data;
  1042. #if defined(DEBUG_SEEK)
  1043. av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1044. #endif
  1045. if(url_feof(pb))
  1046. return -1;
  1047. if(last_pos == pos)
  1048. avi->non_interleaved= 1;
  1049. else if(len || !ast->sample_size)
  1050. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1051. ast->cum_len += get_duration(ast, len);
  1052. last_pos= pos;
  1053. }
  1054. return 0;
  1055. }
  1056. static int guess_ni_flag(AVFormatContext *s){
  1057. int i;
  1058. int64_t last_start=0;
  1059. int64_t first_end= INT64_MAX;
  1060. int64_t oldpos= avio_tell(s->pb);
  1061. for(i=0; i<s->nb_streams; i++){
  1062. AVStream *st = s->streams[i];
  1063. int n= st->nb_index_entries;
  1064. unsigned int size;
  1065. if(n <= 0)
  1066. continue;
  1067. if(n >= 2){
  1068. int64_t pos= st->index_entries[0].pos;
  1069. avio_seek(s->pb, pos + 4, SEEK_SET);
  1070. size= avio_rl32(s->pb);
  1071. if(pos + size > st->index_entries[1].pos)
  1072. last_start= INT64_MAX;
  1073. }
  1074. if(st->index_entries[0].pos > last_start)
  1075. last_start= st->index_entries[0].pos;
  1076. if(st->index_entries[n-1].pos < first_end)
  1077. first_end= st->index_entries[n-1].pos;
  1078. }
  1079. avio_seek(s->pb, oldpos, SEEK_SET);
  1080. return last_start > first_end;
  1081. }
  1082. static int avi_load_index(AVFormatContext *s)
  1083. {
  1084. AVIContext *avi = s->priv_data;
  1085. AVIOContext *pb = s->pb;
  1086. uint32_t tag, size;
  1087. int64_t pos= avio_tell(pb);
  1088. int ret = -1;
  1089. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1090. goto the_end; // maybe truncated file
  1091. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1092. for(;;) {
  1093. if (url_feof(pb))
  1094. break;
  1095. tag = avio_rl32(pb);
  1096. size = avio_rl32(pb);
  1097. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1098. tag & 0xff,
  1099. (tag >> 8) & 0xff,
  1100. (tag >> 16) & 0xff,
  1101. (tag >> 24) & 0xff,
  1102. size);
  1103. switch(tag) {
  1104. case MKTAG('i', 'd', 'x', '1'):
  1105. if (avi_read_idx1(s, size) < 0)
  1106. goto skip;
  1107. ret = 0;
  1108. goto the_end;
  1109. break;
  1110. default:
  1111. skip:
  1112. size += (size & 1);
  1113. if (avio_skip(pb, size) < 0)
  1114. goto the_end; // something is wrong here
  1115. break;
  1116. }
  1117. }
  1118. the_end:
  1119. avio_seek(pb, pos, SEEK_SET);
  1120. return ret;
  1121. }
  1122. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1123. {
  1124. AVIStream *ast2 = st2->priv_data;
  1125. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1126. av_free_packet(&ast2->sub_pkt);
  1127. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1128. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1129. av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1130. }
  1131. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1132. {
  1133. AVIContext *avi = s->priv_data;
  1134. AVStream *st;
  1135. int i, index;
  1136. int64_t pos, pos_min;
  1137. AVIStream *ast;
  1138. if (!avi->index_loaded) {
  1139. /* we only load the index on demand */
  1140. avi_load_index(s);
  1141. avi->index_loaded = 1;
  1142. }
  1143. assert(stream_index>= 0);
  1144. st = s->streams[stream_index];
  1145. ast= st->priv_data;
  1146. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  1147. if(index<0)
  1148. return -1;
  1149. /* find the position */
  1150. pos = st->index_entries[index].pos;
  1151. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1152. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  1153. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1154. /* One and only one real stream for DV in AVI, and it has video */
  1155. /* offsets. Calling with other stream indexes should have failed */
  1156. /* the av_index_search_timestamp call above. */
  1157. assert(stream_index == 0);
  1158. if(avio_seek(s->pb, pos, SEEK_SET) < 0)
  1159. return -1;
  1160. /* Feed the DV video stream version of the timestamp to the */
  1161. /* DV demux so it can synthesize correct timestamps. */
  1162. dv_offset_reset(avi->dv_demux, timestamp);
  1163. avi->stream_index= -1;
  1164. return 0;
  1165. }
  1166. pos_min= pos;
  1167. for(i = 0; i < s->nb_streams; i++) {
  1168. AVStream *st2 = s->streams[i];
  1169. AVIStream *ast2 = st2->priv_data;
  1170. ast2->packet_size=
  1171. ast2->remaining= 0;
  1172. if (ast2->sub_ctx) {
  1173. seek_subtitle(st, st2, timestamp);
  1174. continue;
  1175. }
  1176. if (st2->nb_index_entries <= 0)
  1177. continue;
  1178. // assert(st2->codec->block_align);
  1179. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  1180. index = av_index_search_timestamp(
  1181. st2,
  1182. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1183. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1184. if(index<0)
  1185. index=0;
  1186. ast2->seek_pos= st2->index_entries[index].pos;
  1187. pos_min= FFMIN(pos_min,ast2->seek_pos);
  1188. }
  1189. for(i = 0; i < s->nb_streams; i++) {
  1190. AVStream *st2 = s->streams[i];
  1191. AVIStream *ast2 = st2->priv_data;
  1192. if (ast2->sub_ctx || st2->nb_index_entries <= 0)
  1193. continue;
  1194. index = av_index_search_timestamp(
  1195. st2,
  1196. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1197. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1198. if(index<0)
  1199. index=0;
  1200. while(index>0 && st2->index_entries[index-1].pos >= pos_min)
  1201. index--;
  1202. ast2->frame_offset = st2->index_entries[index].timestamp;
  1203. }
  1204. /* do the seek */
  1205. if (avio_seek(s->pb, pos_min, SEEK_SET) < 0)
  1206. return -1;
  1207. avi->stream_index= -1;
  1208. return 0;
  1209. }
  1210. static int avi_read_close(AVFormatContext *s)
  1211. {
  1212. int i;
  1213. AVIContext *avi = s->priv_data;
  1214. for(i=0;i<s->nb_streams;i++) {
  1215. AVStream *st = s->streams[i];
  1216. AVIStream *ast = st->priv_data;
  1217. if (ast) {
  1218. if (ast->sub_ctx) {
  1219. av_freep(&ast->sub_ctx->pb);
  1220. av_close_input_file(ast->sub_ctx);
  1221. }
  1222. av_free(ast->sub_buffer);
  1223. av_free_packet(&ast->sub_pkt);
  1224. }
  1225. }
  1226. av_free(avi->dv_demux);
  1227. return 0;
  1228. }
  1229. static int avi_probe(AVProbeData *p)
  1230. {
  1231. int i;
  1232. /* check file header */
  1233. for(i=0; avi_headers[i][0]; i++)
  1234. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1235. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1236. return AVPROBE_SCORE_MAX;
  1237. return 0;
  1238. }
  1239. AVInputFormat ff_avi_demuxer = {
  1240. "avi",
  1241. NULL_IF_CONFIG_SMALL("AVI format"),
  1242. sizeof(AVIContext),
  1243. avi_probe,
  1244. avi_read_header,
  1245. avi_read_packet,
  1246. avi_read_close,
  1247. avi_read_seek,
  1248. .priv_class = &demuxer_class,
  1249. };