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.

1629 lines
56KB

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