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.

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