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.

1443 lines
48KB

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