You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1462 lines
49KB

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