avidec.c 47 KB

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