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.

1495 lines
50KB

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