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.

1432 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. #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_ERROR, "unknown stream type %X\n", tag1);
  476. goto fail;
  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 (!av_open_input_stream(&ast->sub_ctx, pb, "", sub_demuxer, NULL)) {
  700. av_read_packet(ast->sub_ctx, &ast->sub_pkt);
  701. *st->codec = *ast->sub_ctx->streams[0]->codec;
  702. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  703. time_base = ast->sub_ctx->streams[0]->time_base;
  704. av_set_pts_info(st, 64, time_base.num, time_base.den);
  705. }
  706. ast->sub_buffer = pkt->data;
  707. memset(pkt, 0, sizeof(*pkt));
  708. return 1;
  709. error:
  710. av_freep(&pb);
  711. }
  712. return 0;
  713. }
  714. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  715. AVPacket *pkt)
  716. {
  717. AVIStream *ast, *next_ast = next_st->priv_data;
  718. int64_t ts, next_ts, ts_min = INT64_MAX;
  719. AVStream *st, *sub_st = NULL;
  720. int i;
  721. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  722. AV_TIME_BASE_Q);
  723. for (i=0; i<s->nb_streams; i++) {
  724. st = s->streams[i];
  725. ast = st->priv_data;
  726. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  727. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  728. if (ts <= next_ts && ts < ts_min) {
  729. ts_min = ts;
  730. sub_st = st;
  731. }
  732. }
  733. }
  734. if (sub_st) {
  735. ast = sub_st->priv_data;
  736. *pkt = ast->sub_pkt;
  737. pkt->stream_index = sub_st->index;
  738. if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  739. ast->sub_pkt.data = NULL;
  740. }
  741. return sub_st;
  742. }
  743. static int get_stream_idx(int *d){
  744. if( d[0] >= '0' && d[0] <= '9'
  745. && d[1] >= '0' && d[1] <= '9'){
  746. return (d[0] - '0') * 10 + (d[1] - '0');
  747. }else{
  748. return 100; //invalid stream ID
  749. }
  750. }
  751. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  752. {
  753. AVIContext *avi = s->priv_data;
  754. AVIOContext *pb = s->pb;
  755. int n, d[8];
  756. unsigned int size;
  757. int64_t i, sync;
  758. void* dstr;
  759. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  760. int size = dv_get_packet(avi->dv_demux, pkt);
  761. if (size >= 0)
  762. return size;
  763. }
  764. if(avi->non_interleaved){
  765. int best_stream_index = 0;
  766. AVStream *best_st= NULL;
  767. AVIStream *best_ast;
  768. int64_t best_ts= INT64_MAX;
  769. int i;
  770. for(i=0; i<s->nb_streams; i++){
  771. AVStream *st = s->streams[i];
  772. AVIStream *ast = st->priv_data;
  773. int64_t ts= ast->frame_offset;
  774. int64_t last_ts;
  775. if(!st->nb_index_entries)
  776. continue;
  777. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  778. if(!ast->remaining && ts > last_ts)
  779. continue;
  780. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  781. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  782. if(ts < best_ts){
  783. best_ts= ts;
  784. best_st= st;
  785. best_stream_index= i;
  786. }
  787. }
  788. if(!best_st)
  789. return -1;
  790. best_ast = best_st->priv_data;
  791. best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
  792. if(best_ast->remaining)
  793. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  794. else{
  795. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  796. if(i>=0)
  797. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  798. }
  799. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  800. if(i>=0){
  801. int64_t pos= best_st->index_entries[i].pos;
  802. pos += best_ast->packet_size - best_ast->remaining;
  803. avio_seek(s->pb, pos + 8, SEEK_SET);
  804. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  805. assert(best_ast->remaining <= best_ast->packet_size);
  806. avi->stream_index= best_stream_index;
  807. if(!best_ast->remaining)
  808. best_ast->packet_size=
  809. best_ast->remaining= best_st->index_entries[i].size;
  810. }
  811. }
  812. resync:
  813. if(avi->stream_index >= 0){
  814. AVStream *st= s->streams[ avi->stream_index ];
  815. AVIStream *ast= st->priv_data;
  816. int size, err;
  817. if(get_subtitle_pkt(s, st, pkt))
  818. return 0;
  819. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  820. size= INT_MAX;
  821. else if(ast->sample_size < 32)
  822. // arbitrary multiplier to avoid tiny packets for raw PCM data
  823. size= 1024*ast->sample_size;
  824. else
  825. size= ast->sample_size;
  826. if(size > ast->remaining)
  827. size= ast->remaining;
  828. avi->last_pkt_pos= avio_tell(pb);
  829. err= av_get_packet(pb, pkt, size);
  830. if(err<0)
  831. return err;
  832. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  833. uint8_t *pal;
  834. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  835. if(!pal){
  836. av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
  837. }else{
  838. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  839. ast->has_pal = 0;
  840. }
  841. }
  842. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  843. dstr = pkt->destruct;
  844. size = dv_produce_packet(avi->dv_demux, pkt,
  845. pkt->data, pkt->size, pkt->pos);
  846. pkt->destruct = dstr;
  847. pkt->flags |= AV_PKT_FLAG_KEY;
  848. if (size < 0)
  849. av_free_packet(pkt);
  850. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
  851. && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  852. ast->frame_offset++;
  853. avi->stream_index = -1;
  854. ast->remaining = 0;
  855. goto resync;
  856. } else {
  857. /* XXX: How to handle B-frames in AVI? */
  858. pkt->dts = ast->frame_offset;
  859. // pkt->dts += ast->start;
  860. if(ast->sample_size)
  861. pkt->dts /= ast->sample_size;
  862. //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);
  863. pkt->stream_index = avi->stream_index;
  864. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  865. AVIndexEntry *e;
  866. int index;
  867. assert(st->index_entries);
  868. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  869. e= &st->index_entries[index];
  870. if(index >= 0 && e->timestamp == ast->frame_offset){
  871. if (index == st->nb_index_entries-1){
  872. int key=1;
  873. int i;
  874. uint32_t state=-1;
  875. for(i=0; i<FFMIN(size,256); i++){
  876. if(st->codec->codec_id == CODEC_ID_MPEG4){
  877. if(state == 0x1B6){
  878. key= !(pkt->data[i]&0xC0);
  879. break;
  880. }
  881. }else
  882. break;
  883. state= (state<<8) + pkt->data[i];
  884. }
  885. if(!key)
  886. e->flags &= ~AVINDEX_KEYFRAME;
  887. }
  888. if (e->flags & AVINDEX_KEYFRAME)
  889. pkt->flags |= AV_PKT_FLAG_KEY;
  890. }
  891. } else {
  892. pkt->flags |= AV_PKT_FLAG_KEY;
  893. }
  894. ast->frame_offset += get_duration(ast, pkt->size);
  895. }
  896. ast->remaining -= size;
  897. if(!ast->remaining){
  898. avi->stream_index= -1;
  899. ast->packet_size= 0;
  900. }
  901. if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
  902. av_free_packet(pkt);
  903. goto resync;
  904. }
  905. ast->seek_pos= 0;
  906. return size;
  907. }
  908. memset(d, -1, sizeof(int)*8);
  909. for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
  910. int j;
  911. for(j=0; j<7; j++)
  912. d[j]= d[j+1];
  913. d[7]= avio_r8(pb);
  914. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  915. n= get_stream_idx(d+2);
  916. //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);
  917. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  918. continue;
  919. //parse ix##
  920. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  921. //parse JUNK
  922. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  923. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  924. avio_skip(pb, size);
  925. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  926. goto resync;
  927. }
  928. //parse stray LIST
  929. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  930. avio_skip(pb, 4);
  931. goto resync;
  932. }
  933. n= get_stream_idx(d);
  934. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  935. continue;
  936. //detect ##ix chunk and skip
  937. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  938. avio_skip(pb, size);
  939. goto resync;
  940. }
  941. //parse ##dc/##wb
  942. if(n < s->nb_streams){
  943. AVStream *st;
  944. AVIStream *ast;
  945. st = s->streams[n];
  946. ast = st->priv_data;
  947. if(s->nb_streams>=2){
  948. AVStream *st1 = s->streams[1];
  949. AVIStream *ast1= st1->priv_data;
  950. //workaround for broken small-file-bug402.avi
  951. if( d[2] == 'w' && d[3] == 'b'
  952. && n==0
  953. && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
  954. && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
  955. && ast->prefix == 'd'*256+'c'
  956. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  957. ){
  958. n=1;
  959. st = st1;
  960. ast = ast1;
  961. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  962. }
  963. }
  964. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  965. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  966. || st->discard >= AVDISCARD_ALL){
  967. ast->frame_offset += get_duration(ast, size);
  968. avio_skip(pb, size);
  969. goto resync;
  970. }
  971. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  972. int k = avio_r8(pb);
  973. int last = (k + avio_r8(pb) - 1) & 0xFF;
  974. avio_rl16(pb); //flags
  975. for (; k <= last; k++)
  976. ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
  977. ast->has_pal= 1;
  978. goto resync;
  979. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  980. d[2]*256+d[3] == ast->prefix /*||
  981. (d[2] == 'd' && d[3] == 'c') ||
  982. (d[2] == 'w' && d[3] == 'b')*/) {
  983. //av_log(s, AV_LOG_DEBUG, "OK\n");
  984. if(d[2]*256+d[3] == ast->prefix)
  985. ast->prefix_count++;
  986. else{
  987. ast->prefix= d[2]*256+d[3];
  988. ast->prefix_count= 0;
  989. }
  990. avi->stream_index= n;
  991. ast->packet_size= size + 8;
  992. ast->remaining= size;
  993. if(size || !ast->sample_size){
  994. uint64_t pos= avio_tell(pb) - 8;
  995. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  996. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  997. }
  998. }
  999. goto resync;
  1000. }
  1001. }
  1002. }
  1003. return AVERROR_EOF;
  1004. }
  1005. /* XXX: We make the implicit supposition that the positions are sorted
  1006. for each stream. */
  1007. static int avi_read_idx1(AVFormatContext *s, int size)
  1008. {
  1009. AVIContext *avi = s->priv_data;
  1010. AVIOContext *pb = s->pb;
  1011. int nb_index_entries, i;
  1012. AVStream *st;
  1013. AVIStream *ast;
  1014. unsigned int index, tag, flags, pos, len;
  1015. unsigned last_pos= -1;
  1016. nb_index_entries = size / 16;
  1017. if (nb_index_entries <= 0)
  1018. return -1;
  1019. /* Read the entries and sort them in each stream component. */
  1020. for(i = 0; i < nb_index_entries; i++) {
  1021. tag = avio_rl32(pb);
  1022. flags = avio_rl32(pb);
  1023. pos = avio_rl32(pb);
  1024. len = avio_rl32(pb);
  1025. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1026. i, tag, flags, pos, len);
  1027. if(i==0 && pos > avi->movi_list)
  1028. avi->movi_list= 0; //FIXME better check
  1029. pos += avi->movi_list;
  1030. index = ((tag & 0xff) - '0') * 10;
  1031. index += ((tag >> 8) & 0xff) - '0';
  1032. if (index >= s->nb_streams)
  1033. continue;
  1034. st = s->streams[index];
  1035. ast = st->priv_data;
  1036. #if defined(DEBUG_SEEK)
  1037. av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1038. #endif
  1039. if(url_feof(pb))
  1040. return -1;
  1041. if(last_pos == pos)
  1042. avi->non_interleaved= 1;
  1043. else if(len || !ast->sample_size)
  1044. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1045. ast->cum_len += get_duration(ast, len);
  1046. last_pos= pos;
  1047. }
  1048. return 0;
  1049. }
  1050. static int guess_ni_flag(AVFormatContext *s){
  1051. int i;
  1052. int64_t last_start=0;
  1053. int64_t first_end= INT64_MAX;
  1054. int64_t oldpos= avio_tell(s->pb);
  1055. for(i=0; i<s->nb_streams; i++){
  1056. AVStream *st = s->streams[i];
  1057. int n= st->nb_index_entries;
  1058. unsigned int size;
  1059. if(n <= 0)
  1060. continue;
  1061. if(n >= 2){
  1062. int64_t pos= st->index_entries[0].pos;
  1063. avio_seek(s->pb, pos + 4, SEEK_SET);
  1064. size= avio_rl32(s->pb);
  1065. if(pos + size > st->index_entries[1].pos)
  1066. last_start= INT64_MAX;
  1067. }
  1068. if(st->index_entries[0].pos > last_start)
  1069. last_start= st->index_entries[0].pos;
  1070. if(st->index_entries[n-1].pos < first_end)
  1071. first_end= st->index_entries[n-1].pos;
  1072. }
  1073. avio_seek(s->pb, oldpos, SEEK_SET);
  1074. return last_start > first_end;
  1075. }
  1076. static int avi_load_index(AVFormatContext *s)
  1077. {
  1078. AVIContext *avi = s->priv_data;
  1079. AVIOContext *pb = s->pb;
  1080. uint32_t tag, size;
  1081. int64_t pos= avio_tell(pb);
  1082. int ret = -1;
  1083. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1084. goto the_end; // maybe truncated file
  1085. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1086. for(;;) {
  1087. if (url_feof(pb))
  1088. break;
  1089. tag = avio_rl32(pb);
  1090. size = avio_rl32(pb);
  1091. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1092. tag & 0xff,
  1093. (tag >> 8) & 0xff,
  1094. (tag >> 16) & 0xff,
  1095. (tag >> 24) & 0xff,
  1096. size);
  1097. switch(tag) {
  1098. case MKTAG('i', 'd', 'x', '1'):
  1099. if (avi_read_idx1(s, size) < 0)
  1100. goto skip;
  1101. ret = 0;
  1102. goto the_end;
  1103. break;
  1104. default:
  1105. skip:
  1106. size += (size & 1);
  1107. if (avio_skip(pb, size) < 0)
  1108. goto the_end; // something is wrong here
  1109. break;
  1110. }
  1111. }
  1112. the_end:
  1113. avio_seek(pb, pos, SEEK_SET);
  1114. return ret;
  1115. }
  1116. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1117. {
  1118. AVIStream *ast2 = st2->priv_data;
  1119. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1120. av_free_packet(&ast2->sub_pkt);
  1121. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1122. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1123. av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1124. }
  1125. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1126. {
  1127. AVIContext *avi = s->priv_data;
  1128. AVStream *st;
  1129. int i, index;
  1130. int64_t pos, pos_min;
  1131. AVIStream *ast;
  1132. if (!avi->index_loaded) {
  1133. /* we only load the index on demand */
  1134. avi_load_index(s);
  1135. avi->index_loaded = 1;
  1136. }
  1137. assert(stream_index>= 0);
  1138. st = s->streams[stream_index];
  1139. ast= st->priv_data;
  1140. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  1141. if(index<0)
  1142. return -1;
  1143. /* find the position */
  1144. pos = st->index_entries[index].pos;
  1145. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1146. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  1147. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1148. /* One and only one real stream for DV in AVI, and it has video */
  1149. /* offsets. Calling with other stream indexes should have failed */
  1150. /* the av_index_search_timestamp call above. */
  1151. assert(stream_index == 0);
  1152. /* Feed the DV video stream version of the timestamp to the */
  1153. /* DV demux so it can synthesize correct timestamps. */
  1154. dv_offset_reset(avi->dv_demux, timestamp);
  1155. avio_seek(s->pb, pos, SEEK_SET);
  1156. avi->stream_index= -1;
  1157. return 0;
  1158. }
  1159. pos_min= pos;
  1160. for(i = 0; i < s->nb_streams; i++) {
  1161. AVStream *st2 = s->streams[i];
  1162. AVIStream *ast2 = st2->priv_data;
  1163. ast2->packet_size=
  1164. ast2->remaining= 0;
  1165. if (ast2->sub_ctx) {
  1166. seek_subtitle(st, st2, timestamp);
  1167. continue;
  1168. }
  1169. if (st2->nb_index_entries <= 0)
  1170. continue;
  1171. // assert(st2->codec->block_align);
  1172. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  1173. index = av_index_search_timestamp(
  1174. st2,
  1175. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1176. flags | AVSEEK_FLAG_BACKWARD);
  1177. if(index<0)
  1178. index=0;
  1179. ast2->seek_pos= st2->index_entries[index].pos;
  1180. pos_min= FFMIN(pos_min,ast2->seek_pos);
  1181. }
  1182. for(i = 0; i < s->nb_streams; i++) {
  1183. AVStream *st2 = s->streams[i];
  1184. AVIStream *ast2 = st2->priv_data;
  1185. if (ast2->sub_ctx || st2->nb_index_entries <= 0)
  1186. continue;
  1187. index = av_index_search_timestamp(
  1188. st2,
  1189. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1190. flags | AVSEEK_FLAG_BACKWARD);
  1191. if(index<0)
  1192. index=0;
  1193. while(index>0 && st2->index_entries[index-1].pos >= pos_min)
  1194. index--;
  1195. ast2->frame_offset = st2->index_entries[index].timestamp;
  1196. }
  1197. /* do the seek */
  1198. avio_seek(s->pb, pos_min, SEEK_SET);
  1199. avi->stream_index= -1;
  1200. return 0;
  1201. }
  1202. static int avi_read_close(AVFormatContext *s)
  1203. {
  1204. int i;
  1205. AVIContext *avi = s->priv_data;
  1206. for(i=0;i<s->nb_streams;i++) {
  1207. AVStream *st = s->streams[i];
  1208. AVIStream *ast = st->priv_data;
  1209. if (ast) {
  1210. if (ast->sub_ctx) {
  1211. av_freep(&ast->sub_ctx->pb);
  1212. av_close_input_stream(ast->sub_ctx);
  1213. }
  1214. av_free(ast->sub_buffer);
  1215. av_free_packet(&ast->sub_pkt);
  1216. }
  1217. }
  1218. av_free(avi->dv_demux);
  1219. return 0;
  1220. }
  1221. static int avi_probe(AVProbeData *p)
  1222. {
  1223. int i;
  1224. /* check file header */
  1225. for(i=0; avi_headers[i][0]; i++)
  1226. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1227. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1228. return AVPROBE_SCORE_MAX;
  1229. return 0;
  1230. }
  1231. AVInputFormat ff_avi_demuxer = {
  1232. "avi",
  1233. NULL_IF_CONFIG_SMALL("AVI format"),
  1234. sizeof(AVIContext),
  1235. avi_probe,
  1236. avi_read_header,
  1237. avi_read_packet,
  1238. avi_read_close,
  1239. avi_read_seek,
  1240. .priv_class = &demuxer_class,
  1241. };