Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * MOV demuxer
  3.  * Copyright (c) 2001 Fabrice Bellard
  4.  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  5.  *
  6.  * first version by Francois Revol <revol@free.fr>
  7.  * seek function by Gael Chardon <gael.dev@4now.net>
  8.  *
  9.  * This file is part of FFmpeg.
  10.  *
  11.  * FFmpeg is free software; you can redistribute it and/or
  12.  * modify it under the terms of the GNU Lesser General Public
  13.  * License as published by the Free Software Foundation; either
  14.  * version 2.1 of the License, or (at your option) any later version.
  15.  *
  16.  * FFmpeg is distributed in the hope that it will be useful,
  17.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  19.  * Lesser General Public License for more details.
  20.  *
  21.  * You should have received a copy of the GNU Lesser General Public
  22.  * License along with FFmpeg; if not, write to the Free Software
  23.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24.  */
  25.  
  26. #include <inttypes.h>
  27. #include <limits.h>
  28. #include <stdint.h>
  29.  
  30. #include "libavutil/attributes.h"
  31. #include "libavutil/channel_layout.h"
  32. #include "libavutil/internal.h"
  33. #include "libavutil/intreadwrite.h"
  34. #include "libavutil/intfloat.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavutil/time_internal.h"
  37. #include "libavutil/avstring.h"
  38. #include "libavutil/dict.h"
  39. #include "libavutil/display.h"
  40. #include "libavutil/opt.h"
  41. #include "libavutil/aes.h"
  42. #include "libavutil/sha.h"
  43. #include "libavutil/timecode.h"
  44. #include "libavcodec/ac3tab.h"
  45. #include "avformat.h"
  46. #include "internal.h"
  47. #include "avio_internal.h"
  48. #include "riff.h"
  49. #include "isom.h"
  50. #include "libavcodec/get_bits.h"
  51. #include "id3v1.h"
  52. #include "mov_chan.h"
  53. #include "replaygain.h"
  54.  
  55. #if CONFIG_ZLIB
  56. #include <zlib.h>
  57. #endif
  58.  
  59. #include "qtpalette.h"
  60.  
  61. /* those functions parse an atom */
  62. /* links atom IDs to parse functions */
  63. typedef struct MOVParseTableEntry {
  64.     uint32_t type;
  65.     int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  66. } MOVParseTableEntry;
  67.  
  68. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
  69. static int mov_read_mfra(MOVContext *c, AVIOContext *f);
  70.  
  71. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
  72.                                              unsigned len, const char *key)
  73. {
  74.     char buf[16];
  75.  
  76.     short current, total = 0;
  77.     avio_rb16(pb); // unknown
  78.     current = avio_rb16(pb);
  79.     if (len >= 6)
  80.         total = avio_rb16(pb);
  81.     if (!total)
  82.         snprintf(buf, sizeof(buf), "%d", current);
  83.     else
  84.         snprintf(buf, sizeof(buf), "%d/%d", current, total);
  85.     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  86.     av_dict_set(&c->fc->metadata, key, buf, 0);
  87.  
  88.     return 0;
  89. }
  90.  
  91. static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
  92.                                             unsigned len, const char *key)
  93. {
  94.     /* bypass padding bytes */
  95.     avio_r8(pb);
  96.     avio_r8(pb);
  97.     avio_r8(pb);
  98.  
  99.     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  100.     av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  101.  
  102.     return 0;
  103. }
  104.  
  105. static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
  106.                                         unsigned len, const char *key)
  107. {
  108.     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  109.     av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  110.  
  111.     return 0;
  112. }
  113.  
  114. static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
  115.                              unsigned len, const char *key)
  116. {
  117.     short genre;
  118.  
  119.     avio_r8(pb); // unknown
  120.  
  121.     genre = avio_r8(pb);
  122.     if (genre < 1 || genre > ID3v1_GENRE_MAX)
  123.         return 0;
  124.     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  125.     av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
  126.  
  127.     return 0;
  128. }
  129.  
  130. static const uint32_t mac_to_unicode[128] = {
  131.     0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  132.     0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  133.     0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  134.     0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  135.     0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  136.     0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  137.     0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  138.     0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  139.     0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  140.     0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  141.     0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  142.     0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  143.     0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  144.     0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  145.     0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  146.     0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  147. };
  148.  
  149. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  150.                                char *dst, int dstlen)
  151. {
  152.     char *p = dst;
  153.     char *end = dst+dstlen-1;
  154.     int i;
  155.  
  156.     for (i = 0; i < len; i++) {
  157.         uint8_t t, c = avio_r8(pb);
  158.         if (c < 0x80 && p < end)
  159.             *p++ = c;
  160.         else if (p < end)
  161.             PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  162.     }
  163.     *p = 0;
  164.     return p - dst;
  165. }
  166.  
  167. static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
  168. {
  169.     AVPacket pkt;
  170.     AVStream *st;
  171.     MOVStreamContext *sc;
  172.     enum AVCodecID id;
  173.     int ret;
  174.  
  175.     switch (type) {
  176.     case 0xd:  id = AV_CODEC_ID_MJPEG; break;
  177.     case 0xe:  id = AV_CODEC_ID_PNG;   break;
  178.     case 0x1b: id = AV_CODEC_ID_BMP;   break;
  179.     default:
  180.         av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
  181.         avio_skip(pb, len);
  182.         return 0;
  183.     }
  184.  
  185.     st = avformat_new_stream(c->fc, NULL);
  186.     if (!st)
  187.         return AVERROR(ENOMEM);
  188.     sc = av_mallocz(sizeof(*sc));
  189.     if (!sc)
  190.         return AVERROR(ENOMEM);
  191.     st->priv_data = sc;
  192.  
  193.     ret = av_get_packet(pb, &pkt, len);
  194.     if (ret < 0)
  195.         return ret;
  196.  
  197.     st->disposition              |= AV_DISPOSITION_ATTACHED_PIC;
  198.  
  199.     st->attached_pic              = pkt;
  200.     st->attached_pic.stream_index = st->index;
  201.     st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
  202.  
  203.     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  204.     st->codec->codec_id   = id;
  205.  
  206.     return 0;
  207. }
  208.  
  209. static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
  210. {
  211.     char language[4] = { 0 };
  212.     char buf[200], place[100];
  213.     uint16_t langcode = 0;
  214.     double longitude, latitude, altitude;
  215.     const char *key = "location";
  216.  
  217.     if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
  218.         av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
  219.         return AVERROR_INVALIDDATA;
  220.     }
  221.  
  222.     avio_skip(pb, 4); // version+flags
  223.     langcode = avio_rb16(pb);
  224.     ff_mov_lang_to_iso639(langcode, language);
  225.     len -= 6;
  226.  
  227.     len -= avio_get_str(pb, len, place, sizeof(place));
  228.     if (len < 1) {
  229.         av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
  230.         return AVERROR_INVALIDDATA;
  231.     }
  232.     avio_skip(pb, 1); // role
  233.     len -= 1;
  234.  
  235.     if (len < 12) {
  236.         av_log(c->fc, AV_LOG_ERROR, "no space for coordinates left (%d)\n", len);
  237.         return AVERROR_INVALIDDATA;
  238.     }
  239.     longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  240.     latitude  = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  241.     altitude  = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  242.  
  243.     // Try to output in the same format as the ?xyz field
  244.     snprintf(buf, sizeof(buf), "%+08.4f%+09.4f",  latitude, longitude);
  245.     if (altitude)
  246.         av_strlcatf(buf, sizeof(buf), "%+f", altitude);
  247.     av_strlcatf(buf, sizeof(buf), "/%s", place);
  248.  
  249.     if (*language && strcmp(language, "und")) {
  250.         char key2[16];
  251.         snprintf(key2, sizeof(key2), "%s-%s", key, language);
  252.         av_dict_set(&c->fc->metadata, key2, buf, 0);
  253.     }
  254.     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  255.     return av_dict_set(&c->fc->metadata, key, buf, 0);
  256. }
  257.  
  258. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  259. {
  260.     char tmp_key[5];
  261.     char key2[32], language[4] = {0};
  262.     char *str = NULL;
  263.     const char *key = NULL;
  264.     uint16_t langcode = 0;
  265.     uint32_t data_type = 0, str_size, str_size_alloc;
  266.     int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
  267.     int raw = 0;
  268.  
  269.     switch (atom.type) {
  270.     case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
  271.     case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
  272.     case MKTAG( 'X','M','P','_'):
  273.         if (c->export_xmp) { key = "xmp"; raw = 1; } break;
  274.     case MKTAG( 'a','A','R','T'): key = "album_artist";    break;
  275.     case MKTAG( 'a','k','I','D'): key = "account_type";
  276.         parse = mov_metadata_int8_no_padding; break;
  277.     case MKTAG( 'a','p','I','D'): key = "account_id"; break;
  278.     case MKTAG( 'c','a','t','g'): key = "category"; break;
  279.     case MKTAG( 'c','p','i','l'): key = "compilation";
  280.         parse = mov_metadata_int8_no_padding; break;
  281.     case MKTAG( 'c','p','r','t'): key = "copyright"; break;
  282.     case MKTAG( 'd','e','s','c'): key = "description"; break;
  283.     case MKTAG( 'd','i','s','k'): key = "disc";
  284.         parse = mov_metadata_track_or_disc_number; break;
  285.     case MKTAG( 'e','g','i','d'): key = "episode_uid";
  286.         parse = mov_metadata_int8_no_padding; break;
  287.     case MKTAG( 'g','n','r','e'): key = "genre";
  288.         parse = mov_metadata_gnre; break;
  289.     case MKTAG( 'h','d','v','d'): key = "hd_video";
  290.         parse = mov_metadata_int8_no_padding; break;
  291.     case MKTAG( 'k','e','y','w'): key = "keywords";  break;
  292.     case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
  293.     case MKTAG( 'l','o','c','i'):
  294.         return mov_metadata_loci(c, pb, atom.size);
  295.     case MKTAG( 'p','c','s','t'): key = "podcast";
  296.         parse = mov_metadata_int8_no_padding; break;
  297.     case MKTAG( 'p','g','a','p'): key = "gapless_playback";
  298.         parse = mov_metadata_int8_no_padding; break;
  299.     case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
  300.     case MKTAG( 'r','t','n','g'): key = "rating";
  301.         parse = mov_metadata_int8_no_padding; break;
  302.     case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
  303.     case MKTAG( 's','o','a','l'): key = "sort_album";   break;
  304.     case MKTAG( 's','o','a','r'): key = "sort_artist";  break;
  305.     case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
  306.     case MKTAG( 's','o','n','m'): key = "sort_name";    break;
  307.     case MKTAG( 's','o','s','n'): key = "sort_show";    break;
  308.     case MKTAG( 's','t','i','k'): key = "media_type";
  309.         parse = mov_metadata_int8_no_padding; break;
  310.     case MKTAG( 't','r','k','n'): key = "track";
  311.         parse = mov_metadata_track_or_disc_number; break;
  312.     case MKTAG( 't','v','e','n'): key = "episode_id"; break;
  313.     case MKTAG( 't','v','e','s'): key = "episode_sort";
  314.         parse = mov_metadata_int8_bypass_padding; break;
  315.     case MKTAG( 't','v','n','n'): key = "network";   break;
  316.     case MKTAG( 't','v','s','h'): key = "show";      break;
  317.     case MKTAG( 't','v','s','n'): key = "season_number";
  318.         parse = mov_metadata_int8_bypass_padding; break;
  319.     case MKTAG(0xa9,'A','R','T'): key = "artist";    break;
  320.     case MKTAG(0xa9,'P','R','D'): key = "producer";  break;
  321.     case MKTAG(0xa9,'a','l','b'): key = "album";     break;
  322.     case MKTAG(0xa9,'a','u','t'): key = "artist";    break;
  323.     case MKTAG(0xa9,'c','h','p'): key = "chapter";   break;
  324.     case MKTAG(0xa9,'c','m','t'): key = "comment";   break;
  325.     case MKTAG(0xa9,'c','o','m'): key = "composer";  break;
  326.     case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  327.     case MKTAG(0xa9,'d','a','y'): key = "date";      break;
  328.     case MKTAG(0xa9,'d','i','r'): key = "director";  break;
  329.     case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
  330.     case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
  331.     case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
  332.     case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
  333.     case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
  334.     case MKTAG(0xa9,'g','r','p'): key = "grouping";  break;
  335.     case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
  336.     case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
  337.     case MKTAG(0xa9,'l','y','r'): key = "lyrics";    break;
  338.     case MKTAG(0xa9,'m','a','k'): key = "make";      break;
  339.     case MKTAG(0xa9,'m','o','d'): key = "model";     break;
  340.     case MKTAG(0xa9,'n','a','m'): key = "title";     break;
  341.     case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
  342.     case MKTAG(0xa9,'p','r','d'): key = "producer";  break;
  343.     case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
  344.     case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
  345.     case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
  346.     case MKTAG(0xa9,'s','t','3'): key = "subtitle";  break;
  347.     case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
  348.     case MKTAG(0xa9,'t','o','o'): key = "encoder";   break;
  349.     case MKTAG(0xa9,'t','r','k'): key = "track";     break;
  350.     case MKTAG(0xa9,'u','r','l'): key = "URL";       break;
  351.     case MKTAG(0xa9,'w','r','n'): key = "warning";   break;
  352.     case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
  353.     case MKTAG(0xa9,'x','y','z'): key = "location";  break;
  354.     }
  355. retry:
  356.     if (c->itunes_metadata && atom.size > 8) {
  357.         int data_size = avio_rb32(pb);
  358.         int tag = avio_rl32(pb);
  359.         if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
  360.             data_type = avio_rb32(pb); // type
  361.             avio_rb32(pb); // unknown
  362.             str_size = data_size - 16;
  363.             atom.size -= 16;
  364.  
  365.             if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
  366.                 int ret = mov_read_covr(c, pb, data_type, str_size);
  367.                 if (ret < 0) {
  368.                     av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
  369.                 }
  370.                 return ret;
  371.             }
  372.         } else return 0;
  373.     } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
  374.         str_size = avio_rb16(pb); // string length
  375.         if (str_size > atom.size) {
  376.             raw = 1;
  377.             avio_seek(pb, -2, SEEK_CUR);
  378.             av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
  379.             goto retry;
  380.         }
  381.         langcode = avio_rb16(pb);
  382.         ff_mov_lang_to_iso639(langcode, language);
  383.         atom.size -= 4;
  384.     } else
  385.         str_size = atom.size;
  386.  
  387.     if (c->export_all && !key) {
  388.         snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  389.         key = tmp_key;
  390.     }
  391.  
  392.     if (!key)
  393.         return 0;
  394.     if (atom.size < 0 || str_size >= INT_MAX/2)
  395.         return AVERROR_INVALIDDATA;
  396.  
  397.     // worst-case requirement for output string in case of utf8 coded input
  398.     str_size_alloc = (raw ? str_size : str_size * 2) + 1;
  399.     str = av_mallocz(str_size_alloc);
  400.     if (!str)
  401.         return AVERROR(ENOMEM);
  402.  
  403.     if (parse)
  404.         parse(c, pb, str_size, key);
  405.     else {
  406.         if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
  407.             mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
  408.         } else {
  409.             int ret = ffio_read_size(pb, str, str_size);
  410.             if (ret < 0) {
  411.                 av_free(str);
  412.                 return ret;
  413.             }
  414.             str[str_size] = 0;
  415.         }
  416.         c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  417.         av_dict_set(&c->fc->metadata, key, str, 0);
  418.         if (*language && strcmp(language, "und")) {
  419.             snprintf(key2, sizeof(key2), "%s-%s", key, language);
  420.             av_dict_set(&c->fc->metadata, key2, str, 0);
  421.         }
  422.         if (!strcmp(key, "encoder")) {
  423.             int major, minor, micro;
  424.             if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
  425.                 c->handbrake_version = 1000000*major + 1000*minor + micro;
  426.             }
  427.         }
  428.     }
  429.     av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
  430.     av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
  431.             key, str, (char*)&atom.type, str_size_alloc, atom.size);
  432.  
  433.     av_freep(&str);
  434.     return 0;
  435. }
  436.  
  437. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  438. {
  439.     int64_t start;
  440.     int i, nb_chapters, str_len, version;
  441.     char str[256+1];
  442.     int ret;
  443.  
  444.     if ((atom.size -= 5) < 0)
  445.         return 0;
  446.  
  447.     version = avio_r8(pb);
  448.     avio_rb24(pb);
  449.     if (version)
  450.         avio_rb32(pb); // ???
  451.     nb_chapters = avio_r8(pb);
  452.  
  453.     for (i = 0; i < nb_chapters; i++) {
  454.         if (atom.size < 9)
  455.             return 0;
  456.  
  457.         start = avio_rb64(pb);
  458.         str_len = avio_r8(pb);
  459.  
  460.         if ((atom.size -= 9+str_len) < 0)
  461.             return 0;
  462.  
  463.         ret = ffio_read_size(pb, str, str_len);
  464.         if (ret < 0)
  465.             return ret;
  466.         str[str_len] = 0;
  467.         avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  468.     }
  469.     return 0;
  470. }
  471.  
  472. #define MIN_DATA_ENTRY_BOX_SIZE 12
  473. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  474. {
  475.     AVStream *st;
  476.     MOVStreamContext *sc;
  477.     int entries, i, j;
  478.  
  479.     if (c->fc->nb_streams < 1)
  480.         return 0;
  481.     st = c->fc->streams[c->fc->nb_streams-1];
  482.     sc = st->priv_data;
  483.  
  484.     avio_rb32(pb); // version + flags
  485.     entries = avio_rb32(pb);
  486.     if (entries >  (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
  487.         entries >= UINT_MAX / sizeof(*sc->drefs))
  488.         return AVERROR_INVALIDDATA;
  489.     av_free(sc->drefs);
  490.     sc->drefs_count = 0;
  491.     sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  492.     if (!sc->drefs)
  493.         return AVERROR(ENOMEM);
  494.     sc->drefs_count = entries;
  495.  
  496.     for (i = 0; i < sc->drefs_count; i++) {
  497.         MOVDref *dref = &sc->drefs[i];
  498.         uint32_t size = avio_rb32(pb);
  499.         int64_t next = avio_tell(pb) + size - 4;
  500.  
  501.         if (size < 12)
  502.             return AVERROR_INVALIDDATA;
  503.  
  504.         dref->type = avio_rl32(pb);
  505.         avio_rb32(pb); // version + flags
  506.         av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
  507.  
  508.         if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  509.             /* macintosh alias record */
  510.             uint16_t volume_len, len;
  511.             int16_t type;
  512.             int ret;
  513.  
  514.             avio_skip(pb, 10);
  515.  
  516.             volume_len = avio_r8(pb);
  517.             volume_len = FFMIN(volume_len, 27);
  518.             ret = ffio_read_size(pb, dref->volume, 27);
  519.             if (ret < 0)
  520.                 return ret;
  521.             dref->volume[volume_len] = 0;
  522.             av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  523.  
  524.             avio_skip(pb, 12);
  525.  
  526.             len = avio_r8(pb);
  527.             len = FFMIN(len, 63);
  528.             ret = ffio_read_size(pb, dref->filename, 63);
  529.             if (ret < 0)
  530.                 return ret;
  531.             dref->filename[len] = 0;
  532.             av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  533.  
  534.             avio_skip(pb, 16);
  535.  
  536.             /* read next level up_from_alias/down_to_target */
  537.             dref->nlvl_from = avio_rb16(pb);
  538.             dref->nlvl_to   = avio_rb16(pb);
  539.             av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  540.                    dref->nlvl_from, dref->nlvl_to);
  541.  
  542.             avio_skip(pb, 16);
  543.  
  544.             for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  545.                 if(avio_feof(pb))
  546.                     return AVERROR_EOF;
  547.                 type = avio_rb16(pb);
  548.                 len = avio_rb16(pb);
  549.                 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  550.                 if (len&1)
  551.                     len += 1;
  552.                 if (type == 2 || type == 18) { // absolute path
  553.                     av_free(dref->path);
  554.                     dref->path = av_mallocz(len+1);
  555.                     if (!dref->path)
  556.                         return AVERROR(ENOMEM);
  557.  
  558.                     ret = ffio_read_size(pb, dref->path, len);
  559.                     if (ret < 0) {
  560.                         av_freep(&dref->path);
  561.                         return ret;
  562.                     }
  563.                     if (type == 18) // no additional processing needed
  564.                         continue;
  565.                     if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  566.                         len -= volume_len;
  567.                         memmove(dref->path, dref->path+volume_len, len);
  568.                         dref->path[len] = 0;
  569.                     }
  570.                     for (j = 0; j < len; j++)
  571.                         if (dref->path[j] == ':')
  572.                             dref->path[j] = '/';
  573.                     av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  574.                 } else if (type == 0) { // directory name
  575.                     av_free(dref->dir);
  576.                     dref->dir = av_malloc(len+1);
  577.                     if (!dref->dir)
  578.                         return AVERROR(ENOMEM);
  579.  
  580.                     ret = ffio_read_size(pb, dref->dir, len);
  581.                     if (ret < 0) {
  582.                         av_freep(&dref->dir);
  583.                         return ret;
  584.                     }
  585.                     dref->dir[len] = 0;
  586.                     for (j = 0; j < len; j++)
  587.                         if (dref->dir[j] == ':')
  588.                             dref->dir[j] = '/';
  589.                     av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  590.                 } else
  591.                     avio_skip(pb, len);
  592.             }
  593.         }
  594.         avio_seek(pb, next, SEEK_SET);
  595.     }
  596.     return 0;
  597. }
  598.  
  599. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  600. {
  601.     AVStream *st;
  602.     uint32_t type;
  603.     uint32_t av_unused ctype;
  604.     int64_t title_size;
  605.     char *title_str;
  606.     int ret;
  607.  
  608.     if (c->fc->nb_streams < 1) // meta before first trak
  609.         return 0;
  610.  
  611.     st = c->fc->streams[c->fc->nb_streams-1];
  612.  
  613.     avio_r8(pb); /* version */
  614.     avio_rb24(pb); /* flags */
  615.  
  616.     /* component type */
  617.     ctype = avio_rl32(pb);
  618.     type = avio_rl32(pb); /* component subtype */
  619.  
  620.     av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  621.     av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
  622.  
  623.     if     (type == MKTAG('v','i','d','e'))
  624.         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  625.     else if (type == MKTAG('s','o','u','n'))
  626.         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  627.     else if (type == MKTAG('m','1','a',' '))
  628.         st->codec->codec_id = AV_CODEC_ID_MP2;
  629.     else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
  630.         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  631.  
  632.     avio_rb32(pb); /* component  manufacture */
  633.     avio_rb32(pb); /* component flags */
  634.     avio_rb32(pb); /* component flags mask */
  635.  
  636.     title_size = atom.size - 24;
  637.     if (title_size > 0) {
  638.         title_str = av_malloc(title_size + 1); /* Add null terminator */
  639.         if (!title_str)
  640.             return AVERROR(ENOMEM);
  641.  
  642.         ret = ffio_read_size(pb, title_str, title_size);
  643.         if (ret < 0) {
  644.             av_freep(&title_str);
  645.             return ret;
  646.         }
  647.         title_str[title_size] = 0;
  648.         if (title_str[0]) {
  649.             int off = (!c->isom && title_str[0] == title_size - 1);
  650.             av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
  651.         }
  652.         av_freep(&title_str);
  653.     }
  654.  
  655.     return 0;
  656. }
  657.  
  658. int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
  659. {
  660.     AVStream *st;
  661.     int tag;
  662.  
  663.     if (fc->nb_streams < 1)
  664.         return 0;
  665.     st = fc->streams[fc->nb_streams-1];
  666.  
  667.     avio_rb32(pb); /* version + flags */
  668.     ff_mp4_read_descr(fc, pb, &tag);
  669.     if (tag == MP4ESDescrTag) {
  670.         ff_mp4_parse_es_descr(pb, NULL);
  671.     } else
  672.         avio_rb16(pb); /* ID */
  673.  
  674.     ff_mp4_read_descr(fc, pb, &tag);
  675.     if (tag == MP4DecConfigDescrTag)
  676.         ff_mp4_read_dec_config_descr(fc, st, pb);
  677.     return 0;
  678. }
  679.  
  680. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  681. {
  682.     return ff_mov_read_esds(c->fc, pb);
  683. }
  684.  
  685. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  686. {
  687.     AVStream *st;
  688.     enum AVAudioServiceType *ast;
  689.     int ac3info, acmod, lfeon, bsmod;
  690.  
  691.     if (c->fc->nb_streams < 1)
  692.         return 0;
  693.     st = c->fc->streams[c->fc->nb_streams-1];
  694.  
  695.     ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  696.                                                             sizeof(*ast));
  697.     if (!ast)
  698.         return AVERROR(ENOMEM);
  699.  
  700.     ac3info = avio_rb24(pb);
  701.     bsmod = (ac3info >> 14) & 0x7;
  702.     acmod = (ac3info >> 11) & 0x7;
  703.     lfeon = (ac3info >> 10) & 0x1;
  704.     st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  705.     st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  706.     if (lfeon)
  707.         st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  708.     *ast = bsmod;
  709.     if (st->codec->channels > 1 && bsmod == 0x7)
  710.         *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  711.  
  712.     st->codec->audio_service_type = *ast;
  713.  
  714.     return 0;
  715. }
  716.  
  717. static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  718. {
  719.     AVStream *st;
  720.     enum AVAudioServiceType *ast;
  721.     int eac3info, acmod, lfeon, bsmod;
  722.  
  723.     if (c->fc->nb_streams < 1)
  724.         return 0;
  725.     st = c->fc->streams[c->fc->nb_streams-1];
  726.  
  727.     ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  728.                                                             sizeof(*ast));
  729.     if (!ast)
  730.         return AVERROR(ENOMEM);
  731.  
  732.     /* No need to parse fields for additional independent substreams and its
  733.      * associated dependent substreams since libavcodec's E-AC-3 decoder
  734.      * does not support them yet. */
  735.     avio_rb16(pb); /* data_rate and num_ind_sub */
  736.     eac3info = avio_rb24(pb);
  737.     bsmod = (eac3info >> 12) & 0x1f;
  738.     acmod = (eac3info >>  9) & 0x7;
  739.     lfeon = (eac3info >>  8) & 0x1;
  740.     st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  741.     if (lfeon)
  742.         st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  743.     st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
  744.     *ast = bsmod;
  745.     if (st->codec->channels > 1 && bsmod == 0x7)
  746.         *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  747.  
  748.     st->codec->audio_service_type = *ast;
  749.  
  750.     return 0;
  751. }
  752.  
  753. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  754. {
  755.     AVStream *st;
  756.  
  757.     if (c->fc->nb_streams < 1)
  758.         return 0;
  759.     st = c->fc->streams[c->fc->nb_streams-1];
  760.  
  761.     if (atom.size < 16)
  762.         return 0;
  763.  
  764.     /* skip version and flags */
  765.     avio_skip(pb, 4);
  766.  
  767.     ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
  768.  
  769.     return 0;
  770. }
  771.  
  772. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  773. {
  774.     AVStream *st;
  775.     int ret;
  776.  
  777.     if (c->fc->nb_streams < 1)
  778.         return 0;
  779.     st = c->fc->streams[c->fc->nb_streams-1];
  780.  
  781.     if ((ret = ff_get_wav_header(c->fc, pb, st->codec, atom.size, 0)) < 0)
  782.         av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
  783.  
  784.     return ret;
  785. }
  786.  
  787. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  788. {
  789.     const int num = avio_rb32(pb);
  790.     const int den = avio_rb32(pb);
  791.     AVStream *st;
  792.  
  793.     if (c->fc->nb_streams < 1)
  794.         return 0;
  795.     st = c->fc->streams[c->fc->nb_streams-1];
  796.  
  797.     if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  798.         (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  799.         av_log(c->fc, AV_LOG_WARNING,
  800.                "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  801.                st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  802.                num, den);
  803.     } else if (den != 0) {
  804.         av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
  805.                   num, den, 32767);
  806.     }
  807.     return 0;
  808. }
  809.  
  810. /* this atom contains actual media data */
  811. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  812. {
  813.     if (atom.size == 0) /* wrong one (MP4) */
  814.         return 0;
  815.     c->found_mdat=1;
  816.     return 0; /* now go for moov */
  817. }
  818.  
  819. #define DRM_BLOB_SIZE 56
  820.  
  821. static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  822. {
  823.     uint8_t intermediate_key[20];
  824.     uint8_t intermediate_iv[20];
  825.     uint8_t input[64];
  826.     uint8_t output[64];
  827.     uint8_t file_checksum[20];
  828.     uint8_t calculated_checksum[20];
  829.     struct AVSHA *sha;
  830.     int i;
  831.     int ret = 0;
  832.     uint8_t *activation_bytes = c->activation_bytes;
  833.     uint8_t *fixed_key = c->audible_fixed_key;
  834.  
  835.     c->aax_mode = 1;
  836.  
  837.     sha = av_sha_alloc();
  838.     if (!sha)
  839.         return AVERROR(ENOMEM);
  840.     c->aes_decrypt = av_aes_alloc();
  841.     if (!c->aes_decrypt) {
  842.         ret = AVERROR(ENOMEM);
  843.         goto fail;
  844.     }
  845.  
  846.     /* drm blob processing */
  847.     avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
  848.     avio_read(pb, input, DRM_BLOB_SIZE);
  849.     avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
  850.     avio_read(pb, file_checksum, 20);
  851.  
  852.     av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
  853.     for (i = 0; i < 20; i++)
  854.         av_log(sha, AV_LOG_INFO, "%02x", file_checksum[i]);
  855.     av_log(c->fc, AV_LOG_INFO, "\n");
  856.  
  857.     /* verify activation data */
  858.     if (!activation_bytes) {
  859.         av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
  860.         ret = 0;  /* allow ffprobe to continue working on .aax files */
  861.         goto fail;
  862.     }
  863.     if (c->activation_bytes_size != 4) {
  864.         av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
  865.         ret = AVERROR(EINVAL);
  866.         goto fail;
  867.     }
  868.  
  869.     /* verify fixed key */
  870.     if (c->audible_fixed_key_size != 16) {
  871.         av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
  872.         ret = AVERROR(EINVAL);
  873.         goto fail;
  874.     }
  875.  
  876.     /* AAX (and AAX+) key derivation */
  877.     av_sha_init(sha, 160);
  878.     av_sha_update(sha, fixed_key, 16);
  879.     av_sha_update(sha, activation_bytes, 4);
  880.     av_sha_final(sha, intermediate_key);
  881.     av_sha_init(sha, 160);
  882.     av_sha_update(sha, fixed_key, 16);
  883.     av_sha_update(sha, intermediate_key, 20);
  884.     av_sha_update(sha, activation_bytes, 4);
  885.     av_sha_final(sha, intermediate_iv);
  886.     av_sha_init(sha, 160);
  887.     av_sha_update(sha, intermediate_key, 16);
  888.     av_sha_update(sha, intermediate_iv, 16);
  889.     av_sha_final(sha, calculated_checksum);
  890.     if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
  891.         av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
  892.         ret = AVERROR_INVALIDDATA;
  893.         goto fail;
  894.     }
  895.     av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
  896.     av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
  897.     for (i = 0; i < 4; i++) {
  898.         // file data (in output) is stored in big-endian mode
  899.         if (activation_bytes[i] != output[3 - i]) { // critical error
  900.             av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
  901.             ret = AVERROR_INVALIDDATA;
  902.             goto fail;
  903.         }
  904.     }
  905.     memcpy(c->file_key, output + 8, 16);
  906.     memcpy(input, output + 26, 16);
  907.     av_sha_init(sha, 160);
  908.     av_sha_update(sha, input, 16);
  909.     av_sha_update(sha, c->file_key, 16);
  910.     av_sha_update(sha, fixed_key, 16);
  911.     av_sha_final(sha, c->file_iv);
  912.  
  913. fail:
  914.     av_free(sha);
  915.  
  916.     return ret;
  917. }
  918.  
  919. // Audible AAX (and AAX+) bytestream decryption
  920. static int aax_filter(uint8_t *input, int size, MOVContext *c)
  921. {
  922.     int blocks = 0;
  923.     unsigned char iv[16];
  924.  
  925.     memcpy(iv, c->file_iv, 16); // iv is overwritten
  926.     blocks = size >> 4; // trailing bytes are not encrypted!
  927.     av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
  928.     av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
  929.  
  930.     return 0;
  931. }
  932.  
  933. /* read major brand, minor version and compatible brands and store them as metadata */
  934. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  935. {
  936.     uint32_t minor_ver;
  937.     int comp_brand_size;
  938.     char* comp_brands_str;
  939.     uint8_t type[5] = {0};
  940.     int ret = ffio_read_size(pb, type, 4);
  941.     if (ret < 0)
  942.         return ret;
  943.  
  944.     if (strcmp(type, "qt  "))
  945.         c->isom = 1;
  946.     av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  947.     av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  948.     minor_ver = avio_rb32(pb); /* minor version */
  949.     av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
  950.  
  951.     comp_brand_size = atom.size - 8;
  952.     if (comp_brand_size < 0)
  953.         return AVERROR_INVALIDDATA;
  954.     comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  955.     if (!comp_brands_str)
  956.         return AVERROR(ENOMEM);
  957.  
  958.     ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
  959.     if (ret < 0) {
  960.         av_freep(&comp_brands_str);
  961.         return ret;
  962.     }
  963.     comp_brands_str[comp_brand_size] = 0;
  964.     av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  965.     av_freep(&comp_brands_str);
  966.  
  967.     return 0;
  968. }
  969.  
  970. /* this atom should contain all header atoms */
  971. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  972. {
  973.     int ret;
  974.  
  975.     if (c->found_moov) {
  976.         av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
  977.         avio_skip(pb, atom.size);
  978.         return 0;
  979.     }
  980.  
  981.     if ((ret = mov_read_default(c, pb, atom)) < 0)
  982.         return ret;
  983.     /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  984.     /* so we don't parse the whole file if over a network */
  985.     c->found_moov=1;
  986.     return 0; /* now go for mdat */
  987. }
  988.  
  989. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  990. {
  991.     if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
  992.         c->has_looked_for_mfra = 1;
  993.         if (pb->seekable) {
  994.             int ret;
  995.             av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
  996.                     "for a mfra\n");
  997.             if ((ret = mov_read_mfra(c, pb)) < 0) {
  998.                 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
  999.                         "read the mfra (may be a live ismv)\n");
  1000.             }
  1001.         } else {
  1002.             av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
  1003.                     "seekable, can not look for mfra\n");
  1004.         }
  1005.     }
  1006.     c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
  1007.     av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  1008.     return mov_read_default(c, pb, atom);
  1009. }
  1010.  
  1011. static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
  1012. {
  1013.     char buffer[32];
  1014.     if (time) {
  1015.         struct tm *ptm, tmbuf;
  1016.         time_t timet;
  1017.         if(time >= 2082844800)
  1018.             time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
  1019.         timet = time;
  1020.         ptm = gmtime_r(&timet, &tmbuf);
  1021.         if (!ptm) return;
  1022.         if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
  1023.             av_dict_set(metadata, "creation_time", buffer, 0);
  1024.     }
  1025. }
  1026.  
  1027. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1028. {
  1029.     AVStream *st;
  1030.     MOVStreamContext *sc;
  1031.     int version;
  1032.     char language[4] = {0};
  1033.     unsigned lang;
  1034.     int64_t creation_time;
  1035.  
  1036.     if (c->fc->nb_streams < 1)
  1037.         return 0;
  1038.     st = c->fc->streams[c->fc->nb_streams-1];
  1039.     sc = st->priv_data;
  1040.  
  1041.     if (sc->time_scale) {
  1042.         av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
  1043.         return AVERROR_INVALIDDATA;
  1044.     }
  1045.  
  1046.     version = avio_r8(pb);
  1047.     if (version > 1) {
  1048.         avpriv_request_sample(c->fc, "Version %d", version);
  1049.         return AVERROR_PATCHWELCOME;
  1050.     }
  1051.     avio_rb24(pb); /* flags */
  1052.     if (version == 1) {
  1053.         creation_time = avio_rb64(pb);
  1054.         avio_rb64(pb);
  1055.     } else {
  1056.         creation_time = avio_rb32(pb);
  1057.         avio_rb32(pb); /* modification time */
  1058.     }
  1059.     mov_metadata_creation_time(&st->metadata, creation_time);
  1060.  
  1061.     sc->time_scale = avio_rb32(pb);
  1062.     st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1063.  
  1064.     lang = avio_rb16(pb); /* language */
  1065.     if (ff_mov_lang_to_iso639(lang, language))
  1066.         av_dict_set(&st->metadata, "language", language, 0);
  1067.     avio_rb16(pb); /* quality */
  1068.  
  1069.     return 0;
  1070. }
  1071.  
  1072. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1073. {
  1074.     int64_t creation_time;
  1075.     int version = avio_r8(pb); /* version */
  1076.     avio_rb24(pb); /* flags */
  1077.  
  1078.     if (version == 1) {
  1079.         creation_time = avio_rb64(pb);
  1080.         avio_rb64(pb);
  1081.     } else {
  1082.         creation_time = avio_rb32(pb);
  1083.         avio_rb32(pb); /* modification time */
  1084.     }
  1085.     mov_metadata_creation_time(&c->fc->metadata, creation_time);
  1086.     c->time_scale = avio_rb32(pb); /* time scale */
  1087.  
  1088.     av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
  1089.  
  1090.     c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1091.     // set the AVCodecContext duration because the duration of individual tracks
  1092.     // may be inaccurate
  1093.     if (c->time_scale > 0 && !c->trex_data)
  1094.         c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
  1095.     avio_rb32(pb); /* preferred scale */
  1096.  
  1097.     avio_rb16(pb); /* preferred volume */
  1098.  
  1099.     avio_skip(pb, 10); /* reserved */
  1100.  
  1101.     avio_skip(pb, 36); /* display matrix */
  1102.  
  1103.     avio_rb32(pb); /* preview time */
  1104.     avio_rb32(pb); /* preview duration */
  1105.     avio_rb32(pb); /* poster time */
  1106.     avio_rb32(pb); /* selection time */
  1107.     avio_rb32(pb); /* selection duration */
  1108.     avio_rb32(pb); /* current time */
  1109.     avio_rb32(pb); /* next track ID */
  1110.  
  1111.     return 0;
  1112. }
  1113.  
  1114. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1115. {
  1116.     AVStream *st;
  1117.     int little_endian;
  1118.  
  1119.     if (c->fc->nb_streams < 1)
  1120.         return 0;
  1121.     st = c->fc->streams[c->fc->nb_streams-1];
  1122.  
  1123.     little_endian = avio_rb16(pb) & 0xFF;
  1124.     av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
  1125.     if (little_endian == 1) {
  1126.         switch (st->codec->codec_id) {
  1127.         case AV_CODEC_ID_PCM_S24BE:
  1128.             st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
  1129.             break;
  1130.         case AV_CODEC_ID_PCM_S32BE:
  1131.             st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
  1132.             break;
  1133.         case AV_CODEC_ID_PCM_F32BE:
  1134.             st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
  1135.             break;
  1136.         case AV_CODEC_ID_PCM_F64BE:
  1137.             st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
  1138.             break;
  1139.         default:
  1140.             break;
  1141.         }
  1142.     }
  1143.     return 0;
  1144. }
  1145.  
  1146. static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1147. {
  1148.     AVStream *st;
  1149.     char color_parameter_type[5] = { 0 };
  1150.     uint16_t color_primaries, color_trc, color_matrix;
  1151.     int ret;
  1152.  
  1153.     if (c->fc->nb_streams < 1)
  1154.         return 0;
  1155.     st = c->fc->streams[c->fc->nb_streams - 1];
  1156.  
  1157.     ret = ffio_read_size(pb, color_parameter_type, 4);
  1158.     if (ret < 0)
  1159.         return ret;
  1160.     if (strncmp(color_parameter_type, "nclx", 4) &&
  1161.         strncmp(color_parameter_type, "nclc", 4)) {
  1162.         av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
  1163.                color_parameter_type);
  1164.         return 0;
  1165.     }
  1166.  
  1167.     color_primaries = avio_rb16(pb);
  1168.     color_trc = avio_rb16(pb);
  1169.     color_matrix = avio_rb16(pb);
  1170.  
  1171.     av_log(c->fc, AV_LOG_TRACE,
  1172.            "%s: pri %d trc %d matrix %d",
  1173.            color_parameter_type, color_primaries, color_trc, color_matrix);
  1174.  
  1175.     if (!strncmp(color_parameter_type, "nclx", 4)) {
  1176.         uint8_t color_range = avio_r8(pb) >> 7;
  1177.         av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
  1178.         if (color_range)
  1179.             st->codec->color_range = AVCOL_RANGE_JPEG;
  1180.         else
  1181.             st->codec->color_range = AVCOL_RANGE_MPEG;
  1182.         /* 14496-12 references JPEG XR specs (rather than the more complete
  1183.          * 23001-8) so some adjusting is required */
  1184.         if (color_primaries >= AVCOL_PRI_FILM)
  1185.             color_primaries = AVCOL_PRI_UNSPECIFIED;
  1186.         if ((color_trc >= AVCOL_TRC_LINEAR &&
  1187.              color_trc <= AVCOL_TRC_LOG_SQRT) ||
  1188.             color_trc >= AVCOL_TRC_BT2020_10)
  1189.             color_trc = AVCOL_TRC_UNSPECIFIED;
  1190.         if (color_matrix >= AVCOL_SPC_BT2020_NCL)
  1191.             color_matrix = AVCOL_SPC_UNSPECIFIED;
  1192.         st->codec->color_primaries = color_primaries;
  1193.         st->codec->color_trc = color_trc;
  1194.         st->codec->colorspace = color_matrix;
  1195.     } else if (!strncmp(color_parameter_type, "nclc", 4)) {
  1196.         /* color primaries, Table 4-4 */
  1197.         switch (color_primaries) {
  1198.         case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
  1199.         case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
  1200.         case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
  1201.         }
  1202.         /* color transfer, Table 4-5 */
  1203.         switch (color_trc) {
  1204.         case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
  1205.         case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
  1206.         }
  1207.         /* color matrix, Table 4-6 */
  1208.         switch (color_matrix) {
  1209.         case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
  1210.         case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
  1211.         case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
  1212.         }
  1213.     }
  1214.     av_log(c->fc, AV_LOG_TRACE, "\n");
  1215.  
  1216.     return 0;
  1217. }
  1218.  
  1219. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1220. {
  1221.     AVStream *st;
  1222.     unsigned mov_field_order;
  1223.     enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  1224.  
  1225.     if (c->fc->nb_streams < 1) // will happen with jp2 files
  1226.         return 0;
  1227.     st = c->fc->streams[c->fc->nb_streams-1];
  1228.     if (atom.size < 2)
  1229.         return AVERROR_INVALIDDATA;
  1230.     mov_field_order = avio_rb16(pb);
  1231.     if ((mov_field_order & 0xFF00) == 0x0100)
  1232.         decoded_field_order = AV_FIELD_PROGRESSIVE;
  1233.     else if ((mov_field_order & 0xFF00) == 0x0200) {
  1234.         switch (mov_field_order & 0xFF) {
  1235.         case 0x01: decoded_field_order = AV_FIELD_TT;
  1236.                    break;
  1237.         case 0x06: decoded_field_order = AV_FIELD_BB;
  1238.                    break;
  1239.         case 0x09: decoded_field_order = AV_FIELD_TB;
  1240.                    break;
  1241.         case 0x0E: decoded_field_order = AV_FIELD_BT;
  1242.                    break;
  1243.         }
  1244.     }
  1245.     if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  1246.         av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  1247.     }
  1248.     st->codec->field_order = decoded_field_order;
  1249.  
  1250.     return 0;
  1251. }
  1252.  
  1253. static int mov_realloc_extradata(AVCodecContext *codec, MOVAtom atom)
  1254. {
  1255.     int err = 0;
  1256.     uint64_t size = (uint64_t)codec->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
  1257.     if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  1258.         return AVERROR_INVALIDDATA;
  1259.     if ((err = av_reallocp(&codec->extradata, size)) < 0) {
  1260.         codec->extradata_size = 0;
  1261.         return err;
  1262.     }
  1263.     codec->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
  1264.     return 0;
  1265. }
  1266.  
  1267. /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
  1268. static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1269.                                         AVCodecContext *codec, uint8_t *buf)
  1270. {
  1271.     int64_t result = atom.size;
  1272.     int err;
  1273.  
  1274.     AV_WB32(buf    , atom.size + 8);
  1275.     AV_WL32(buf + 4, atom.type);
  1276.     err = ffio_read_size(pb, buf + 8, atom.size);
  1277.     if (err < 0) {
  1278.         codec->extradata_size -= atom.size;
  1279.         return err;
  1280.     } else if (err < atom.size) {
  1281.         av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
  1282.         codec->extradata_size -= atom.size - err;
  1283.         result = err;
  1284.     }
  1285.     memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  1286.     return result;
  1287. }
  1288.  
  1289. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  1290. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1291.                               enum AVCodecID codec_id)
  1292. {
  1293.     AVStream *st;
  1294.     uint64_t original_size;
  1295.     int err;
  1296.  
  1297.     if (c->fc->nb_streams < 1) // will happen with jp2 files
  1298.         return 0;
  1299.     st = c->fc->streams[c->fc->nb_streams-1];
  1300.  
  1301.     if (st->codec->codec_id != codec_id)
  1302.         return 0; /* unexpected codec_id - don't mess with extradata */
  1303.  
  1304.     original_size = st->codec->extradata_size;
  1305.     err = mov_realloc_extradata(st->codec, atom);
  1306.     if (err)
  1307.         return err;
  1308.  
  1309.     err =  mov_read_atom_into_extradata(c, pb, atom, st->codec,  st->codec->extradata + original_size);
  1310.     if (err < 0)
  1311.         return err;
  1312.     return 0; // Note: this is the original behavior to ignore truncation.
  1313. }
  1314.  
  1315. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  1316. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1317. {
  1318.     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  1319. }
  1320.  
  1321. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1322. {
  1323.     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  1324. }
  1325.  
  1326. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1327. {
  1328.     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  1329. }
  1330.  
  1331. static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1332. {
  1333.     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
  1334. }
  1335.  
  1336. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1337. {
  1338.     int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  1339.     if(ret == 0)
  1340.         ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
  1341.     return ret;
  1342. }
  1343.  
  1344. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1345. {
  1346.     int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  1347.  
  1348.     if (!ret && c->fc->nb_streams >= 1) {
  1349.         AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
  1350.         if (avctx->extradata_size >= 40) {
  1351.             avctx->height = AV_RB16(&avctx->extradata[36]);
  1352.             avctx->width  = AV_RB16(&avctx->extradata[38]);
  1353.         }
  1354.     }
  1355.     return ret;
  1356. }
  1357.  
  1358. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1359. {
  1360.     if (c->fc->nb_streams >= 1) {
  1361.         AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
  1362.         if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  1363.             codec->codec_id == AV_CODEC_ID_H264 &&
  1364.             atom.size > 11) {
  1365.             avio_skip(pb, 10);
  1366.             /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  1367.             if (avio_rb16(pb) == 0xd4d)
  1368.                 codec->width = 1440;
  1369.             return 0;
  1370.         }
  1371.     }
  1372.  
  1373.     return mov_read_avid(c, pb, atom);
  1374. }
  1375.  
  1376. static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1377. {
  1378.     int ret = 0;
  1379.     int length = 0;
  1380.     uint64_t original_size;
  1381.     if (c->fc->nb_streams >= 1) {
  1382.         AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
  1383.         if (codec->codec_id == AV_CODEC_ID_H264)
  1384.             return 0;
  1385.         if (atom.size == 16) {
  1386.             original_size = codec->extradata_size;
  1387.             ret = mov_realloc_extradata(codec, atom);
  1388.             if (!ret) {
  1389.                 length =  mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
  1390.                 if (length == atom.size) {
  1391.                     const uint8_t range_value = codec->extradata[original_size + 19];
  1392.                     switch (range_value) {
  1393.                     case 1:
  1394.                         codec->color_range = AVCOL_RANGE_MPEG;
  1395.                         break;
  1396.                     case 2:
  1397.                         codec->color_range = AVCOL_RANGE_JPEG;
  1398.                         break;
  1399.                     default:
  1400.                         av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
  1401.                         break;
  1402.                     }
  1403.                     ff_dlog(c, "color_range: %d\n", codec->color_range);
  1404.                 } else {
  1405.                   /* For some reason the whole atom was not added to the extradata */
  1406.                   av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
  1407.                 }
  1408.             } else {
  1409.                 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
  1410.             }
  1411.         } else {
  1412.             av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
  1413.         }
  1414.     }
  1415.  
  1416.     return ret;
  1417. }
  1418.  
  1419. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1420. {
  1421.     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  1422. }
  1423.  
  1424. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1425. {
  1426.     AVStream *st;
  1427.     int ret;
  1428.  
  1429.     if (c->fc->nb_streams < 1)
  1430.         return 0;
  1431.     st = c->fc->streams[c->fc->nb_streams-1];
  1432.  
  1433.     if ((uint64_t)atom.size > (1<<30))
  1434.         return AVERROR_INVALIDDATA;
  1435.  
  1436.     if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
  1437.         st->codec->codec_id == AV_CODEC_ID_QDMC ||
  1438.         st->codec->codec_id == AV_CODEC_ID_SPEEX) {
  1439.         // pass all frma atom to codec, needed at least for QDMC and QDM2
  1440.         av_freep(&st->codec->extradata);
  1441.         ret = ff_get_extradata(st->codec, pb, atom.size);
  1442.         if (ret < 0)
  1443.             return ret;
  1444.     } else if (atom.size > 8) { /* to read frma, esds atoms */
  1445.         if (st->codec->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
  1446.             uint64_t buffer;
  1447.             ret = ffio_ensure_seekback(pb, 8);
  1448.             if (ret < 0)
  1449.                 return ret;
  1450.             buffer = avio_rb64(pb);
  1451.             atom.size -= 8;
  1452.             if (  (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
  1453.                 && buffer >> 32 <= atom.size
  1454.                 && buffer >> 32 >= 8) {
  1455.                 avio_skip(pb, -8);
  1456.                 atom.size += 8;
  1457.             } else if (!st->codec->extradata_size) {
  1458. #define ALAC_EXTRADATA_SIZE 36
  1459.                 st->codec->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
  1460.                 if (!st->codec->extradata)
  1461.                     return AVERROR(ENOMEM);
  1462.                 st->codec->extradata_size = ALAC_EXTRADATA_SIZE;
  1463.                 AV_WB32(st->codec->extradata    , ALAC_EXTRADATA_SIZE);
  1464.                 AV_WB32(st->codec->extradata + 4, MKTAG('a','l','a','c'));
  1465.                 AV_WB64(st->codec->extradata + 12, buffer);
  1466.                 avio_read(pb, st->codec->extradata + 20, 16);
  1467.                 avio_skip(pb, atom.size - 24);
  1468.                 return 0;
  1469.             }
  1470.         }
  1471.         if ((ret = mov_read_default(c, pb, atom)) < 0)
  1472.             return ret;
  1473.     } else
  1474.         avio_skip(pb, atom.size);
  1475.     return 0;
  1476. }
  1477.  
  1478. /**
  1479.  * This function reads atom content and puts data in extradata without tag
  1480.  * nor size unlike mov_read_extradata.
  1481.  */
  1482. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1483. {
  1484.     AVStream *st;
  1485.     int ret;
  1486.  
  1487.     if (c->fc->nb_streams < 1)
  1488.         return 0;
  1489.     st = c->fc->streams[c->fc->nb_streams-1];
  1490.  
  1491.     if ((uint64_t)atom.size > (1<<30))
  1492.         return AVERROR_INVALIDDATA;
  1493.  
  1494.     if (atom.size >= 10) {
  1495.         // Broken files created by legacy versions of libavformat will
  1496.         // wrap a whole fiel atom inside of a glbl atom.
  1497.         unsigned size = avio_rb32(pb);
  1498.         unsigned type = avio_rl32(pb);
  1499.         avio_seek(pb, -8, SEEK_CUR);
  1500.         if (type == MKTAG('f','i','e','l') && size == atom.size)
  1501.             return mov_read_default(c, pb, atom);
  1502.     }
  1503.     if (st->codec->extradata_size > 1 && st->codec->extradata) {
  1504.         av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
  1505.         return 0;
  1506.     }
  1507.     av_freep(&st->codec->extradata);
  1508.     ret = ff_get_extradata(st->codec, pb, atom.size);
  1509.     if (ret < 0)
  1510.         return ret;
  1511.  
  1512.     return 0;
  1513. }
  1514.  
  1515. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1516. {
  1517.     AVStream *st;
  1518.     uint8_t profile_level;
  1519.     int ret;
  1520.  
  1521.     if (c->fc->nb_streams < 1)
  1522.         return 0;
  1523.     st = c->fc->streams[c->fc->nb_streams-1];
  1524.  
  1525.     if (atom.size >= (1<<28) || atom.size < 7)
  1526.         return AVERROR_INVALIDDATA;
  1527.  
  1528.     profile_level = avio_r8(pb);
  1529.     if ((profile_level & 0xf0) != 0xc0)
  1530.         return 0;
  1531.  
  1532.     avio_seek(pb, 6, SEEK_CUR);
  1533.     av_freep(&st->codec->extradata);
  1534.     ret = ff_get_extradata(st->codec, pb, atom.size - 7);
  1535.     if (ret < 0)
  1536.         return ret;
  1537.  
  1538.     return 0;
  1539. }
  1540.  
  1541. /**
  1542.  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  1543.  * but can have extradata appended at the end after the 40 bytes belonging
  1544.  * to the struct.
  1545.  */
  1546. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1547. {
  1548.     AVStream *st;
  1549.     int ret;
  1550.  
  1551.     if (c->fc->nb_streams < 1)
  1552.         return 0;
  1553.     if (atom.size <= 40)
  1554.         return 0;
  1555.     st = c->fc->streams[c->fc->nb_streams-1];
  1556.  
  1557.     if ((uint64_t)atom.size > (1<<30))
  1558.         return AVERROR_INVALIDDATA;
  1559.  
  1560.     avio_skip(pb, 40);
  1561.     av_freep(&st->codec->extradata);
  1562.     ret = ff_get_extradata(st->codec, pb, atom.size - 40);
  1563.     if (ret < 0)
  1564.         return ret;
  1565.  
  1566.     return 0;
  1567. }
  1568.  
  1569. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1570. {
  1571.     AVStream *st;
  1572.     MOVStreamContext *sc;
  1573.     unsigned int i, entries;
  1574.  
  1575.     if (c->fc->nb_streams < 1)
  1576.         return 0;
  1577.     st = c->fc->streams[c->fc->nb_streams-1];
  1578.     sc = st->priv_data;
  1579.  
  1580.     avio_r8(pb); /* version */
  1581.     avio_rb24(pb); /* flags */
  1582.  
  1583.     entries = avio_rb32(pb);
  1584.  
  1585.     if (!entries)
  1586.         return 0;
  1587.  
  1588.     if (sc->chunk_offsets)
  1589.         av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
  1590.     av_free(sc->chunk_offsets);
  1591.     sc->chunk_count = 0;
  1592.     sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
  1593.     if (!sc->chunk_offsets)
  1594.         return AVERROR(ENOMEM);
  1595.     sc->chunk_count = entries;
  1596.  
  1597.     if      (atom.type == MKTAG('s','t','c','o'))
  1598.         for (i = 0; i < entries && !pb->eof_reached; i++)
  1599.             sc->chunk_offsets[i] = avio_rb32(pb);
  1600.     else if (atom.type == MKTAG('c','o','6','4'))
  1601.         for (i = 0; i < entries && !pb->eof_reached; i++)
  1602.             sc->chunk_offsets[i] = avio_rb64(pb);
  1603.     else
  1604.         return AVERROR_INVALIDDATA;
  1605.  
  1606.     sc->chunk_count = i;
  1607.  
  1608.     if (pb->eof_reached)
  1609.         return AVERROR_EOF;
  1610.  
  1611.     return 0;
  1612. }
  1613.  
  1614. /**
  1615.  * Compute codec id for 'lpcm' tag.
  1616.  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1617.  */
  1618. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1619. {
  1620.     /* lpcm flags:
  1621.      * 0x1 = float
  1622.      * 0x2 = big-endian
  1623.      * 0x4 = signed
  1624.      */
  1625.     return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1626. }
  1627.  
  1628. static int mov_codec_id(AVStream *st, uint32_t format)
  1629. {
  1630.     int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1631.  
  1632.     if (id <= 0 &&
  1633.         ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1634.          (format & 0xFFFF) == 'T' + ('S' << 8)))
  1635.         id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1636.  
  1637.     if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1638.         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1639.     } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
  1640.                /* skip old asf mpeg4 tag */
  1641.                format && format != MKTAG('m','p','4','s')) {
  1642.         id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1643.         if (id <= 0)
  1644.             id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1645.         if (id > 0)
  1646.             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1647.         else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
  1648.                     (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1649.                     st->codec->codec_id == AV_CODEC_ID_NONE)) {
  1650.             id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1651.             if (id > 0)
  1652.                 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1653.         }
  1654.     }
  1655.  
  1656.     st->codec->codec_tag = format;
  1657.  
  1658.     return id;
  1659. }
  1660.  
  1661. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1662.                                  AVStream *st, MOVStreamContext *sc)
  1663. {
  1664.     uint8_t codec_name[32];
  1665.     unsigned int color_depth, len, j;
  1666.     int color_greyscale;
  1667.     int color_table_id;
  1668.  
  1669.     avio_rb16(pb); /* version */
  1670.     avio_rb16(pb); /* revision level */
  1671.     avio_rb32(pb); /* vendor */
  1672.     avio_rb32(pb); /* temporal quality */
  1673.     avio_rb32(pb); /* spatial quality */
  1674.  
  1675.     st->codec->width  = avio_rb16(pb); /* width */
  1676.     st->codec->height = avio_rb16(pb); /* height */
  1677.  
  1678.     avio_rb32(pb); /* horiz resolution */
  1679.     avio_rb32(pb); /* vert resolution */
  1680.     avio_rb32(pb); /* data size, always 0 */
  1681.     avio_rb16(pb); /* frames per samples */
  1682.  
  1683.     len = avio_r8(pb); /* codec name, pascal string */
  1684.     if (len > 31)
  1685.         len = 31;
  1686.     mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1687.     if (len < 31)
  1688.         avio_skip(pb, 31 - len);
  1689.  
  1690.     if (codec_name[0])
  1691.         av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1692.  
  1693.     /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1694.     if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1695.         st->codec->codec_tag = MKTAG('I', '4', '2', '0');
  1696.         st->codec->width &= ~1;
  1697.         st->codec->height &= ~1;
  1698.     }
  1699.     /* Flash Media Server uses tag H263 with Sorenson Spark */
  1700.     if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
  1701.         !memcmp(codec_name, "Sorenson H263", 13))
  1702.         st->codec->codec_id = AV_CODEC_ID_FLV1;
  1703.  
  1704.     st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1705.     color_table_id = avio_rb16(pb); /* colortable id */
  1706.     av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
  1707.             st->codec->bits_per_coded_sample, color_table_id);
  1708.     /* figure out the palette situation */
  1709.     color_depth     = st->codec->bits_per_coded_sample & 0x1F;
  1710.     color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  1711.     /* Do not create a greyscale palette for cinepak */
  1712.     if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
  1713.         return;
  1714.  
  1715.     /* if the depth is 2, 4, or 8 bpp, file is palettized */
  1716.     if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
  1717.         /* for palette traversal */
  1718.         unsigned int color_start, color_count, color_end;
  1719.         unsigned int a, r, g, b;
  1720.  
  1721.         if (color_greyscale) {
  1722.             int color_index, color_dec;
  1723.             /* compute the greyscale palette */
  1724.             st->codec->bits_per_coded_sample = color_depth;
  1725.             color_count = 1 << color_depth;
  1726.             color_index = 255;
  1727.             color_dec   = 256 / (color_count - 1);
  1728.             for (j = 0; j < color_count; j++) {
  1729.                 r = g = b = color_index;
  1730.                 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1731.                 color_index -= color_dec;
  1732.                 if (color_index < 0)
  1733.                     color_index = 0;
  1734.             }
  1735.         } else if (color_table_id) {
  1736.             const uint8_t *color_table;
  1737.             /* if flag bit 3 is set, use the default palette */
  1738.             color_count = 1 << color_depth;
  1739.             if (color_depth == 2)
  1740.                 color_table = ff_qt_default_palette_4;
  1741.             else if (color_depth == 4)
  1742.                 color_table = ff_qt_default_palette_16;
  1743.             else
  1744.                 color_table = ff_qt_default_palette_256;
  1745.  
  1746.             for (j = 0; j < color_count; j++) {
  1747.                 r = color_table[j * 3 + 0];
  1748.                 g = color_table[j * 3 + 1];
  1749.                 b = color_table[j * 3 + 2];
  1750.                 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1751.             }
  1752.         } else {
  1753.             /* load the palette from the file */
  1754.             color_start = avio_rb32(pb);
  1755.             color_count = avio_rb16(pb);
  1756.             color_end   = avio_rb16(pb);
  1757.             if ((color_start <= 255) && (color_end <= 255)) {
  1758.                 for (j = color_start; j <= color_end; j++) {
  1759.                     /* each A, R, G, or B component is 16 bits;
  1760.                         * only use the top 8 bits */
  1761.                     a = avio_r8(pb);
  1762.                     avio_r8(pb);
  1763.                     r = avio_r8(pb);
  1764.                     avio_r8(pb);
  1765.                     g = avio_r8(pb);
  1766.                     avio_r8(pb);
  1767.                     b = avio_r8(pb);
  1768.                     avio_r8(pb);
  1769.                     sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
  1770.                 }
  1771.             }
  1772.         }
  1773.         sc->has_palette = 1;
  1774.     }
  1775. }
  1776.  
  1777. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1778.                                  AVStream *st, MOVStreamContext *sc)
  1779. {
  1780.     int bits_per_sample, flags;
  1781.     uint16_t version = avio_rb16(pb);
  1782.     AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1783.  
  1784.     avio_rb16(pb); /* revision level */
  1785.     avio_rb32(pb); /* vendor */
  1786.  
  1787.     st->codec->channels              = avio_rb16(pb); /* channel count */
  1788.     st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1789.     av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
  1790.  
  1791.     sc->audio_cid = avio_rb16(pb);
  1792.     avio_rb16(pb); /* packet size = 0 */
  1793.  
  1794.     st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  1795.  
  1796.     // Read QT version 1 fields. In version 0 these do not exist.
  1797.     av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
  1798.     if (!c->isom ||
  1799.         (compatible_brands && strstr(compatible_brands->value, "qt  "))) {
  1800.  
  1801.         if (version == 1) {
  1802.             sc->samples_per_frame = avio_rb32(pb);
  1803.             avio_rb32(pb); /* bytes per packet */
  1804.             sc->bytes_per_frame = avio_rb32(pb);
  1805.             avio_rb32(pb); /* bytes per sample */
  1806.         } else if (version == 2) {
  1807.             avio_rb32(pb); /* sizeof struct only */
  1808.             st->codec->sample_rate = av_int2double(avio_rb64(pb));
  1809.             st->codec->channels    = avio_rb32(pb);
  1810.             avio_rb32(pb); /* always 0x7F000000 */
  1811.             st->codec->bits_per_coded_sample = avio_rb32(pb);
  1812.  
  1813.             flags = avio_rb32(pb); /* lpcm format specific flag */
  1814.             sc->bytes_per_frame   = avio_rb32(pb);
  1815.             sc->samples_per_frame = avio_rb32(pb);
  1816.             if (st->codec->codec_tag == MKTAG('l','p','c','m'))
  1817.                 st->codec->codec_id =
  1818.                     ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
  1819.                                              flags);
  1820.         }
  1821.         if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
  1822.             /* can't correctly handle variable sized packet as audio unit */
  1823.             switch (st->codec->codec_id) {
  1824.             case AV_CODEC_ID_MP2:
  1825.             case AV_CODEC_ID_MP3:
  1826.                 st->need_parsing = AVSTREAM_PARSE_FULL;
  1827.                 break;
  1828.             }
  1829.         }
  1830.     }
  1831.  
  1832.     switch (st->codec->codec_id) {
  1833.     case AV_CODEC_ID_PCM_S8:
  1834.     case AV_CODEC_ID_PCM_U8:
  1835.         if (st->codec->bits_per_coded_sample == 16)
  1836.             st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
  1837.         break;
  1838.     case AV_CODEC_ID_PCM_S16LE:
  1839.     case AV_CODEC_ID_PCM_S16BE:
  1840.         if (st->codec->bits_per_coded_sample == 8)
  1841.             st->codec->codec_id = AV_CODEC_ID_PCM_S8;
  1842.         else if (st->codec->bits_per_coded_sample == 24)
  1843.             st->codec->codec_id =
  1844.                 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1845.                 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1846.         else if (st->codec->bits_per_coded_sample == 32)
  1847.              st->codec->codec_id =
  1848.                 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1849.                 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1850.         break;
  1851.     /* set values for old format before stsd version 1 appeared */
  1852.     case AV_CODEC_ID_MACE3:
  1853.         sc->samples_per_frame = 6;
  1854.         sc->bytes_per_frame   = 2 * st->codec->channels;
  1855.         break;
  1856.     case AV_CODEC_ID_MACE6:
  1857.         sc->samples_per_frame = 6;
  1858.         sc->bytes_per_frame   = 1 * st->codec->channels;
  1859.         break;
  1860.     case AV_CODEC_ID_ADPCM_IMA_QT:
  1861.         sc->samples_per_frame = 64;
  1862.         sc->bytes_per_frame   = 34 * st->codec->channels;
  1863.         break;
  1864.     case AV_CODEC_ID_GSM:
  1865.         sc->samples_per_frame = 160;
  1866.         sc->bytes_per_frame   = 33;
  1867.         break;
  1868.     default:
  1869.         break;
  1870.     }
  1871.  
  1872.     bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1873.     if (bits_per_sample) {
  1874.         st->codec->bits_per_coded_sample = bits_per_sample;
  1875.         sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1876.     }
  1877. }
  1878.  
  1879. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1880.                                     AVStream *st, MOVStreamContext *sc,
  1881.                                     int64_t size)
  1882. {
  1883.     // ttxt stsd contains display flags, justification, background
  1884.     // color, fonts, and default styles, so fake an atom to read it
  1885.     MOVAtom fake_atom = { .size = size };
  1886.     // mp4s contains a regular esds atom
  1887.     if (st->codec->codec_tag != AV_RL32("mp4s"))
  1888.         mov_read_glbl(c, pb, fake_atom);
  1889.     st->codec->width  = sc->width;
  1890.     st->codec->height = sc->height;
  1891. }
  1892.  
  1893. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1894. {
  1895.     uint8_t r, g, b;
  1896.     int y, cb, cr;
  1897.  
  1898.     y  = (ycbcr >> 16) & 0xFF;
  1899.     cr = (ycbcr >> 8)  & 0xFF;
  1900.     cb =  ycbcr        & 0xFF;
  1901.  
  1902.     b = av_clip_uint8((1164 * (y - 16)                     + 2018 * (cb - 128)) / 1000);
  1903.     g = av_clip_uint8((1164 * (y - 16) -  813 * (cr - 128) -  391 * (cb - 128)) / 1000);
  1904.     r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128)                    ) / 1000);
  1905.  
  1906.     return (r << 16) | (g << 8) | b;
  1907. }
  1908.  
  1909. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1910. {
  1911.     char buf[256] = {0};
  1912.     uint8_t *src = st->codec->extradata;
  1913.     int i;
  1914.  
  1915.     if (st->codec->extradata_size != 64)
  1916.         return 0;
  1917.  
  1918.     if (st->codec->width > 0 &&  st->codec->height > 0)
  1919.         snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1920.                  st->codec->width, st->codec->height);
  1921.     av_strlcat(buf, "palette: ", sizeof(buf));
  1922.  
  1923.     for (i = 0; i < 16; i++) {
  1924.         uint32_t yuv = AV_RB32(src + i * 4);
  1925.         uint32_t rgba = yuv_to_rgba(yuv);
  1926.  
  1927.         av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1928.     }
  1929.  
  1930.     if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1931.         return 0;
  1932.  
  1933.     av_freep(&st->codec->extradata);
  1934.     st->codec->extradata_size = 0;
  1935.     st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
  1936.     if (!st->codec->extradata)
  1937.         return AVERROR(ENOMEM);
  1938.     st->codec->extradata_size = strlen(buf);
  1939.     memcpy(st->codec->extradata, buf, st->codec->extradata_size);
  1940.  
  1941.     return 0;
  1942. }
  1943.  
  1944. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1945.                                 AVStream *st, MOVStreamContext *sc,
  1946.                                 int64_t size)
  1947. {
  1948.     int ret;
  1949.  
  1950.     if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  1951.         if ((int)size != size)
  1952.             return AVERROR(ENOMEM);
  1953.  
  1954.         ret = ff_get_extradata(st->codec, pb, size);
  1955.         if (ret < 0)
  1956.             return ret;
  1957.         if (size > 16) {
  1958.             MOVStreamContext *tmcd_ctx = st->priv_data;
  1959.             int val;
  1960.             val = AV_RB32(st->codec->extradata + 4);
  1961.             tmcd_ctx->tmcd_flags = val;
  1962.             if (val & 1)
  1963.                 st->codec->flags2 |= AV_CODEC_FLAG2_DROP_FRAME_TIMECODE;
  1964.             st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
  1965.             st->codec->time_base.num = 1;
  1966.             /* adjust for per frame dur in counter mode */
  1967.             if (tmcd_ctx->tmcd_flags & 0x0008) {
  1968.                 int timescale = AV_RB32(st->codec->extradata + 8);
  1969.                 int framedur = AV_RB32(st->codec->extradata + 12);
  1970.                 st->codec->time_base.den *= timescale;
  1971.                 st->codec->time_base.num *= framedur;
  1972.             }
  1973.             if (size > 30) {
  1974.                 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
  1975.                 uint32_t format = AV_RB32(st->codec->extradata + 22);
  1976.                 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
  1977.                     uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
  1978.                     if (str_size > 0 && size >= (int)str_size + 26) {
  1979.                         char *reel_name = av_malloc(str_size + 1);
  1980.                         if (!reel_name)
  1981.                             return AVERROR(ENOMEM);
  1982.                         memcpy(reel_name, st->codec->extradata + 30, str_size);
  1983.                         reel_name[str_size] = 0; /* Add null terminator */
  1984.                         /* don't add reel_name if emtpy string */
  1985.                         if (*reel_name == 0) {
  1986.                             av_free(reel_name);
  1987.                         } else {
  1988.                             av_dict_set(&st->metadata, "reel_name", reel_name,  AV_DICT_DONT_STRDUP_VAL);
  1989.                         }
  1990.                     }
  1991.                 }
  1992.             }
  1993.         }
  1994.     } else {
  1995.         /* other codec type, just skip (rtp, mp4s ...) */
  1996.         avio_skip(pb, size);
  1997.     }
  1998.     return 0;
  1999. }
  2000.  
  2001. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  2002.                                    AVStream *st, MOVStreamContext *sc)
  2003. {
  2004.     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  2005.         !st->codec->sample_rate && sc->time_scale > 1)
  2006.         st->codec->sample_rate = sc->time_scale;
  2007.  
  2008.     /* special codec parameters handling */
  2009.     switch (st->codec->codec_id) {
  2010. #if CONFIG_DV_DEMUXER
  2011.     case AV_CODEC_ID_DVAUDIO:
  2012.         c->dv_fctx = avformat_alloc_context();
  2013.         if (!c->dv_fctx) {
  2014.             av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
  2015.             return AVERROR(ENOMEM);
  2016.         }
  2017.         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  2018.         if (!c->dv_demux) {
  2019.             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  2020.             return AVERROR(ENOMEM);
  2021.         }
  2022.         sc->dv_audio_container = 1;
  2023.         st->codec->codec_id    = AV_CODEC_ID_PCM_S16LE;
  2024.         break;
  2025. #endif
  2026.     /* no ifdef since parameters are always those */
  2027.     case AV_CODEC_ID_QCELP:
  2028.         st->codec->channels = 1;
  2029.         // force sample rate for qcelp when not stored in mov
  2030.         if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  2031.             st->codec->sample_rate = 8000;
  2032.         // FIXME: Why is the following needed for some files?
  2033.         sc->samples_per_frame = 160;
  2034.         if (!sc->bytes_per_frame)
  2035.             sc->bytes_per_frame = 35;
  2036.         break;
  2037.     case AV_CODEC_ID_AMR_NB:
  2038.         st->codec->channels    = 1;
  2039.         /* force sample rate for amr, stsd in 3gp does not store sample rate */
  2040.         st->codec->sample_rate = 8000;
  2041.         break;
  2042.     case AV_CODEC_ID_AMR_WB:
  2043.         st->codec->channels    = 1;
  2044.         st->codec->sample_rate = 16000;
  2045.         break;
  2046.     case AV_CODEC_ID_MP2:
  2047.     case AV_CODEC_ID_MP3:
  2048.         /* force type after stsd for m1a hdlr */
  2049.         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  2050.         break;
  2051.     case AV_CODEC_ID_GSM:
  2052.     case AV_CODEC_ID_ADPCM_MS:
  2053.     case AV_CODEC_ID_ADPCM_IMA_WAV:
  2054.     case AV_CODEC_ID_ILBC:
  2055.     case AV_CODEC_ID_MACE3:
  2056.     case AV_CODEC_ID_MACE6:
  2057.     case AV_CODEC_ID_QDM2:
  2058.         st->codec->block_align = sc->bytes_per_frame;
  2059.         break;
  2060.     case AV_CODEC_ID_ALAC:
  2061.         if (st->codec->extradata_size == 36) {
  2062.             st->codec->channels    = AV_RB8 (st->codec->extradata + 21);
  2063.             st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
  2064.         }
  2065.         break;
  2066.     case AV_CODEC_ID_AC3:
  2067.     case AV_CODEC_ID_EAC3:
  2068.     case AV_CODEC_ID_MPEG1VIDEO:
  2069.     case AV_CODEC_ID_VC1:
  2070.         st->need_parsing = AVSTREAM_PARSE_FULL;
  2071.         break;
  2072.     default:
  2073.         break;
  2074.     }
  2075.     return 0;
  2076. }
  2077.  
  2078. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  2079.                                   int codec_tag, int format,
  2080.                                   int64_t size)
  2081. {
  2082.     int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  2083.  
  2084.     if (codec_tag &&
  2085.          (codec_tag != format &&
  2086.           (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  2087.                                  : codec_tag != MKTAG('j','p','e','g')))) {
  2088.         /* Multiple fourcc, we skip JPEG. This is not correct, we should
  2089.          * export it as a separate AVStream but this needs a few changes
  2090.          * in the MOV demuxer, patch welcome. */
  2091.  
  2092.         av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  2093.         avio_skip(pb, size);
  2094.         return 1;
  2095.     }
  2096.     if ( codec_tag == AV_RL32("avc1") ||
  2097.          codec_tag == AV_RL32("hvc1") ||
  2098.          codec_tag == AV_RL32("hev1")
  2099.     )
  2100.         av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
  2101.  
  2102.     return 0;
  2103. }
  2104.  
  2105. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  2106. {
  2107.     AVStream *st;
  2108.     MOVStreamContext *sc;
  2109.     int pseudo_stream_id;
  2110.  
  2111.     if (c->fc->nb_streams < 1)
  2112.         return 0;
  2113.     st = c->fc->streams[c->fc->nb_streams-1];
  2114.     sc = st->priv_data;
  2115.  
  2116.     for (pseudo_stream_id = 0;
  2117.          pseudo_stream_id < entries && !pb->eof_reached;
  2118.          pseudo_stream_id++) {
  2119.         //Parsing Sample description table
  2120.         enum AVCodecID id;
  2121.         int ret, dref_id = 1;
  2122.         MOVAtom a = { AV_RL32("stsd") };
  2123.         int64_t start_pos = avio_tell(pb);
  2124.         int64_t size = avio_rb32(pb); /* size */
  2125.         uint32_t format = avio_rl32(pb); /* data format */
  2126.  
  2127.         if (size >= 16) {
  2128.             avio_rb32(pb); /* reserved */
  2129.             avio_rb16(pb); /* reserved */
  2130.             dref_id = avio_rb16(pb);
  2131.         }else if (size <= 7){
  2132.             av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
  2133.             return AVERROR_INVALIDDATA;
  2134.         }
  2135.  
  2136.         if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
  2137.                                    size - (avio_tell(pb) - start_pos)))
  2138.             continue;
  2139.  
  2140.         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  2141.         sc->dref_id= dref_id;
  2142.  
  2143.         id = mov_codec_id(st, format);
  2144.  
  2145.         av_log(c->fc, AV_LOG_TRACE,
  2146.                "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
  2147.                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  2148.                 (format >> 24) & 0xff, format, st->codec->codec_type);
  2149.  
  2150.         if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  2151.             st->codec->codec_id = id;
  2152.             mov_parse_stsd_video(c, pb, st, sc);
  2153.         } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  2154.             st->codec->codec_id = id;
  2155.             mov_parse_stsd_audio(c, pb, st, sc);
  2156.         } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  2157.             st->codec->codec_id = id;
  2158.             mov_parse_stsd_subtitle(c, pb, st, sc,
  2159.                                     size - (avio_tell(pb) - start_pos));
  2160.         } else {
  2161.             ret = mov_parse_stsd_data(c, pb, st, sc,
  2162.                                       size - (avio_tell(pb) - start_pos));
  2163.             if (ret < 0)
  2164.                 return ret;
  2165.         }
  2166.         /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  2167.         a.size = size - (avio_tell(pb) - start_pos);
  2168.         if (a.size > 8) {
  2169.             if ((ret = mov_read_default(c, pb, a)) < 0)
  2170.                 return ret;
  2171.         } else if (a.size > 0)
  2172.             avio_skip(pb, a.size);
  2173.     }
  2174.  
  2175.     if (pb->eof_reached)
  2176.         return AVERROR_EOF;
  2177.  
  2178.     return mov_finalize_stsd_codec(c, pb, st, sc);
  2179. }
  2180.  
  2181. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2182. {
  2183.     int entries;
  2184.  
  2185.     avio_r8(pb); /* version */
  2186.     avio_rb24(pb); /* flags */
  2187.     entries = avio_rb32(pb);
  2188.  
  2189.     return ff_mov_read_stsd_entries(c, pb, entries);
  2190. }
  2191.  
  2192. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2193. {
  2194.     AVStream *st;
  2195.     MOVStreamContext *sc;
  2196.     unsigned int i, entries;
  2197.  
  2198.     if (c->fc->nb_streams < 1)
  2199.         return 0;
  2200.     st = c->fc->streams[c->fc->nb_streams-1];
  2201.     sc = st->priv_data;
  2202.  
  2203.     avio_r8(pb); /* version */
  2204.     avio_rb24(pb); /* flags */
  2205.  
  2206.     entries = avio_rb32(pb);
  2207.  
  2208.     av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  2209.  
  2210.     if (!entries)
  2211.         return 0;
  2212.     if (sc->stsc_data)
  2213.         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
  2214.     av_free(sc->stsc_data);
  2215.     sc->stsc_count = 0;
  2216.     sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
  2217.     if (!sc->stsc_data)
  2218.         return AVERROR(ENOMEM);
  2219.  
  2220.     for (i = 0; i < entries && !pb->eof_reached; i++) {
  2221.         sc->stsc_data[i].first = avio_rb32(pb);
  2222.         sc->stsc_data[i].count = avio_rb32(pb);
  2223.         sc->stsc_data[i].id = avio_rb32(pb);
  2224.     }
  2225.  
  2226.     sc->stsc_count = i;
  2227.  
  2228.     if (pb->eof_reached)
  2229.         return AVERROR_EOF;
  2230.  
  2231.     return 0;
  2232. }
  2233.  
  2234. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2235. {
  2236.     AVStream *st;
  2237.     MOVStreamContext *sc;
  2238.     unsigned i, entries;
  2239.  
  2240.     if (c->fc->nb_streams < 1)
  2241.         return 0;
  2242.     st = c->fc->streams[c->fc->nb_streams-1];
  2243.     sc = st->priv_data;
  2244.  
  2245.     avio_rb32(pb); // version + flags
  2246.  
  2247.     entries = avio_rb32(pb);
  2248.     if (sc->stps_data)
  2249.         av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
  2250.     av_free(sc->stps_data);
  2251.     sc->stps_count = 0;
  2252.     sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
  2253.     if (!sc->stps_data)
  2254.         return AVERROR(ENOMEM);
  2255.  
  2256.     for (i = 0; i < entries && !pb->eof_reached; i++) {
  2257.         sc->stps_data[i] = avio_rb32(pb);
  2258.         //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
  2259.     }
  2260.  
  2261.     sc->stps_count = i;
  2262.  
  2263.     if (pb->eof_reached)
  2264.         return AVERROR_EOF;
  2265.  
  2266.     return 0;
  2267. }
  2268.  
  2269. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2270. {
  2271.     AVStream *st;
  2272.     MOVStreamContext *sc;
  2273.     unsigned int i, entries;
  2274.  
  2275.     if (c->fc->nb_streams < 1)
  2276.         return 0;
  2277.     st = c->fc->streams[c->fc->nb_streams-1];
  2278.     sc = st->priv_data;
  2279.  
  2280.     avio_r8(pb); /* version */
  2281.     avio_rb24(pb); /* flags */
  2282.  
  2283.     entries = avio_rb32(pb);
  2284.  
  2285.     av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
  2286.  
  2287.     if (!entries)
  2288.     {
  2289.         sc->keyframe_absent = 1;
  2290.         if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  2291.             st->need_parsing = AVSTREAM_PARSE_HEADERS;
  2292.         return 0;
  2293.     }
  2294.     if (sc->keyframes)
  2295.         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
  2296.     if (entries >= UINT_MAX / sizeof(int))
  2297.         return AVERROR_INVALIDDATA;
  2298.     av_freep(&sc->keyframes);
  2299.     sc->keyframe_count = 0;
  2300.     sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
  2301.     if (!sc->keyframes)
  2302.         return AVERROR(ENOMEM);
  2303.  
  2304.     for (i = 0; i < entries && !pb->eof_reached; i++) {
  2305.         sc->keyframes[i] = avio_rb32(pb);
  2306.         //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
  2307.     }
  2308.  
  2309.     sc->keyframe_count = i;
  2310.  
  2311.     if (pb->eof_reached)
  2312.         return AVERROR_EOF;
  2313.  
  2314.     return 0;
  2315. }
  2316.  
  2317. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2318. {
  2319.     AVStream *st;
  2320.     MOVStreamContext *sc;
  2321.     unsigned int i, entries, sample_size, field_size, num_bytes;
  2322.     GetBitContext gb;
  2323.     unsigned char* buf;
  2324.     int ret;
  2325.  
  2326.     if (c->fc->nb_streams < 1)
  2327.         return 0;
  2328.     st = c->fc->streams[c->fc->nb_streams-1];
  2329.     sc = st->priv_data;
  2330.  
  2331.     avio_r8(pb); /* version */
  2332.     avio_rb24(pb); /* flags */
  2333.  
  2334.     if (atom.type == MKTAG('s','t','s','z')) {
  2335.         sample_size = avio_rb32(pb);
  2336.         if (!sc->sample_size) /* do not overwrite value computed in stsd */
  2337.             sc->sample_size = sample_size;
  2338.         sc->stsz_sample_size = sample_size;
  2339.         field_size = 32;
  2340.     } else {
  2341.         sample_size = 0;
  2342.         avio_rb24(pb); /* reserved */
  2343.         field_size = avio_r8(pb);
  2344.     }
  2345.     entries = avio_rb32(pb);
  2346.  
  2347.     av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  2348.  
  2349.     sc->sample_count = entries;
  2350.     if (sample_size)
  2351.         return 0;
  2352.  
  2353.     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  2354.         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  2355.         return AVERROR_INVALIDDATA;
  2356.     }
  2357.  
  2358.     if (!entries)
  2359.         return 0;
  2360.     if (entries >= (UINT_MAX - 4) / field_size)
  2361.         return AVERROR_INVALIDDATA;
  2362.     if (sc->sample_sizes)
  2363.         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
  2364.     av_free(sc->sample_sizes);
  2365.     sc->sample_count = 0;
  2366.     sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
  2367.     if (!sc->sample_sizes)
  2368.         return AVERROR(ENOMEM);
  2369.  
  2370.     num_bytes = (entries*field_size+4)>>3;
  2371.  
  2372.     buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  2373.     if (!buf) {
  2374.         av_freep(&sc->sample_sizes);
  2375.         return AVERROR(ENOMEM);
  2376.     }
  2377.  
  2378.     ret = ffio_read_size(pb, buf, num_bytes);
  2379.     if (ret < 0) {
  2380.         av_freep(&sc->sample_sizes);
  2381.         av_free(buf);
  2382.         return ret;
  2383.     }
  2384.  
  2385.     init_get_bits(&gb, buf, 8*num_bytes);
  2386.  
  2387.     for (i = 0; i < entries && !pb->eof_reached; i++) {
  2388.         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  2389.         sc->data_size += sc->sample_sizes[i];
  2390.     }
  2391.  
  2392.     sc->sample_count = i;
  2393.  
  2394.     av_free(buf);
  2395.  
  2396.     if (pb->eof_reached)
  2397.         return AVERROR_EOF;
  2398.  
  2399.     return 0;
  2400. }
  2401.  
  2402. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2403. {
  2404.     AVStream *st;
  2405.     MOVStreamContext *sc;
  2406.     unsigned int i, entries;
  2407.     int64_t duration=0;
  2408.     int64_t total_sample_count=0;
  2409.  
  2410.     if (c->fc->nb_streams < 1)
  2411.         return 0;
  2412.     st = c->fc->streams[c->fc->nb_streams-1];
  2413.     sc = st->priv_data;
  2414.  
  2415.     avio_r8(pb); /* version */
  2416.     avio_rb24(pb); /* flags */
  2417.     entries = avio_rb32(pb);
  2418.  
  2419.     av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
  2420.             c->fc->nb_streams-1, entries);
  2421.  
  2422.     if (sc->stts_data)
  2423.         av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
  2424.     av_free(sc->stts_data);
  2425.     sc->stts_count = 0;
  2426.     sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
  2427.     if (!sc->stts_data)
  2428.         return AVERROR(ENOMEM);
  2429.  
  2430.     for (i = 0; i < entries && !pb->eof_reached; i++) {
  2431.         int sample_duration;
  2432.         int sample_count;
  2433.  
  2434.         sample_count=avio_rb32(pb);
  2435.         sample_duration = avio_rb32(pb);
  2436.  
  2437.         if (sample_count < 0) {
  2438.             av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  2439.             return AVERROR_INVALIDDATA;
  2440.         }
  2441.         sc->stts_data[i].count= sample_count;
  2442.         sc->stts_data[i].duration= sample_duration;
  2443.  
  2444.         av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  2445.                 sample_count, sample_duration);
  2446.  
  2447.         if (   i+1 == entries
  2448.             && i
  2449.             && sample_count == 1
  2450.             && total_sample_count > 100
  2451.             && sample_duration/10 > duration / total_sample_count)
  2452.             sample_duration = duration / total_sample_count;
  2453.         duration+=(int64_t)sample_duration*sample_count;
  2454.         total_sample_count+=sample_count;
  2455.     }
  2456.  
  2457.     sc->stts_count = i;
  2458.  
  2459.     sc->duration_for_fps  += duration;
  2460.     sc->nb_frames_for_fps += total_sample_count;
  2461.  
  2462.     if (pb->eof_reached)
  2463.         return AVERROR_EOF;
  2464.  
  2465.     st->nb_frames= total_sample_count;
  2466.     if (duration)
  2467.         st->duration= duration;
  2468.     sc->track_end = duration;
  2469.     return 0;
  2470. }
  2471.  
  2472. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  2473. {
  2474.     if (duration < 0) {
  2475.         sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  2476.     }
  2477. }
  2478.  
  2479. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2480. {
  2481.     AVStream *st;
  2482.     MOVStreamContext *sc;
  2483.     unsigned int i, entries;
  2484.  
  2485.     if (c->fc->nb_streams < 1)
  2486.         return 0;
  2487.     st = c->fc->streams[c->fc->nb_streams-1];
  2488.     sc = st->priv_data;
  2489.  
  2490.     avio_r8(pb); /* version */
  2491.     avio_rb24(pb); /* flags */
  2492.     entries = avio_rb32(pb);
  2493.  
  2494.     av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  2495.  
  2496.     if (!entries)
  2497.         return 0;
  2498.     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  2499.         return AVERROR_INVALIDDATA;
  2500.     av_freep(&sc->ctts_data);
  2501.     sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
  2502.     if (!sc->ctts_data)
  2503.         return AVERROR(ENOMEM);
  2504.  
  2505.     for (i = 0; i < entries && !pb->eof_reached; i++) {
  2506.         int count    =avio_rb32(pb);
  2507.         int duration =avio_rb32(pb);
  2508.  
  2509.         sc->ctts_data[i].count   = count;
  2510.         sc->ctts_data[i].duration= duration;
  2511.  
  2512.         av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
  2513.                 count, duration);
  2514.  
  2515.         if (FFNABS(duration) < -(1<<28) && i+2<entries) {
  2516.             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  2517.             av_freep(&sc->ctts_data);
  2518.             sc->ctts_count = 0;
  2519.             return 0;
  2520.         }
  2521.  
  2522.         if (i+2<entries)
  2523.             mov_update_dts_shift(sc, duration);
  2524.     }
  2525.  
  2526.     sc->ctts_count = i;
  2527.  
  2528.     if (pb->eof_reached)
  2529.         return AVERROR_EOF;
  2530.  
  2531.     av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  2532.  
  2533.     return 0;
  2534. }
  2535.  
  2536. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2537. {
  2538.     AVStream *st;
  2539.     MOVStreamContext *sc;
  2540.     unsigned int i, entries;
  2541.     uint8_t version;
  2542.     uint32_t grouping_type;
  2543.  
  2544.     if (c->fc->nb_streams < 1)
  2545.         return 0;
  2546.     st = c->fc->streams[c->fc->nb_streams-1];
  2547.     sc = st->priv_data;
  2548.  
  2549.     version = avio_r8(pb); /* version */
  2550.     avio_rb24(pb); /* flags */
  2551.     grouping_type = avio_rl32(pb);
  2552.     if (grouping_type != MKTAG( 'r','a','p',' '))
  2553.         return 0; /* only support 'rap ' grouping */
  2554.     if (version == 1)
  2555.         avio_rb32(pb); /* grouping_type_parameter */
  2556.  
  2557.     entries = avio_rb32(pb);
  2558.     if (!entries)
  2559.         return 0;
  2560.     if (sc->rap_group)
  2561.         av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
  2562.     av_free(sc->rap_group);
  2563.     sc->rap_group_count = 0;
  2564.     sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
  2565.     if (!sc->rap_group)
  2566.         return AVERROR(ENOMEM);
  2567.  
  2568.     for (i = 0; i < entries && !pb->eof_reached; i++) {
  2569.         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  2570.         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  2571.     }
  2572.  
  2573.     sc->rap_group_count = i;
  2574.  
  2575.     return pb->eof_reached ? AVERROR_EOF : 0;
  2576. }
  2577.  
  2578. static void mov_build_index(MOVContext *mov, AVStream *st)
  2579. {
  2580.     MOVStreamContext *sc = st->priv_data;
  2581.     int64_t current_offset;
  2582.     int64_t current_dts = 0;
  2583.     unsigned int stts_index = 0;
  2584.     unsigned int stsc_index = 0;
  2585.     unsigned int stss_index = 0;
  2586.     unsigned int stps_index = 0;
  2587.     unsigned int i, j;
  2588.     uint64_t stream_size = 0;
  2589.  
  2590.     if (sc->elst_count) {
  2591.         int i, edit_start_index = 0, unsupported = 0;
  2592.         int64_t empty_duration = 0; // empty duration of the first edit list entry
  2593.         int64_t start_time = 0; // start time of the media
  2594.  
  2595.         for (i = 0; i < sc->elst_count; i++) {
  2596.             const MOVElst *e = &sc->elst_data[i];
  2597.             if (i == 0 && e->time == -1) {
  2598.                 /* if empty, the first entry is the start time of the stream
  2599.                  * relative to the presentation itself */
  2600.                 empty_duration = e->duration;
  2601.                 edit_start_index = 1;
  2602.             } else if (i == edit_start_index && e->time >= 0) {
  2603.                 start_time = e->time;
  2604.             } else
  2605.                 unsupported = 1;
  2606.         }
  2607.         if (unsupported)
  2608.             av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2609.                    "a/v desync might occur, patch welcome\n");
  2610.  
  2611.         /* adjust first dts according to edit list */
  2612.         if ((empty_duration || start_time) && mov->time_scale > 0) {
  2613.             if (empty_duration)
  2614.                 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
  2615.             sc->time_offset = start_time - empty_duration;
  2616.             current_dts = -sc->time_offset;
  2617.             if (sc->ctts_count>0 && sc->stts_count>0 &&
  2618.                 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  2619.                 /* more than 16 frames delay, dts are likely wrong
  2620.                    this happens with files created by iMovie */
  2621.                 sc->wrong_dts = 1;
  2622.                 st->codec->has_b_frames = 1;
  2623.             }
  2624.         }
  2625.     }
  2626.  
  2627.     /* only use old uncompressed audio chunk demuxing when stts specifies it */
  2628.     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  2629.           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  2630.         unsigned int current_sample = 0;
  2631.         unsigned int stts_sample = 0;
  2632.         unsigned int sample_size;
  2633.         unsigned int distance = 0;
  2634.         unsigned int rap_group_index = 0;
  2635.         unsigned int rap_group_sample = 0;
  2636.         int64_t last_dts = 0;
  2637.         int64_t dts_correction = 0;
  2638.         int rap_group_present = sc->rap_group_count && sc->rap_group;
  2639.         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  2640.  
  2641.         current_dts -= sc->dts_shift;
  2642.         last_dts     = current_dts;
  2643.  
  2644.         if (!sc->sample_count || st->nb_index_entries)
  2645.             return;
  2646.         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2647.             return;
  2648.         if (av_reallocp_array(&st->index_entries,
  2649.                               st->nb_index_entries + sc->sample_count,
  2650.                               sizeof(*st->index_entries)) < 0) {
  2651.             st->nb_index_entries = 0;
  2652.             return;
  2653.         }
  2654.         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  2655.  
  2656.         for (i = 0; i < sc->chunk_count; i++) {
  2657.             int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  2658.             current_offset = sc->chunk_offsets[i];
  2659.             while (stsc_index + 1 < sc->stsc_count &&
  2660.                 i + 1 == sc->stsc_data[stsc_index + 1].first)
  2661.                 stsc_index++;
  2662.  
  2663.             if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  2664.                 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  2665.                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  2666.                 sc->stsz_sample_size = sc->sample_size;
  2667.             }
  2668.             if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  2669.                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  2670.                 sc->stsz_sample_size = sc->sample_size;
  2671.             }
  2672.  
  2673.             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  2674.                 int keyframe = 0;
  2675.                 if (current_sample >= sc->sample_count) {
  2676.                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  2677.                     return;
  2678.                 }
  2679.  
  2680.                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  2681.                     keyframe = 1;
  2682.                     if (stss_index + 1 < sc->keyframe_count)
  2683.                         stss_index++;
  2684.                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  2685.                     keyframe = 1;
  2686.                     if (stps_index + 1 < sc->stps_count)
  2687.                         stps_index++;
  2688.                 }
  2689.                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
  2690.                     if (sc->rap_group[rap_group_index].index > 0)
  2691.                         keyframe = 1;
  2692.                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  2693.                         rap_group_sample = 0;
  2694.                         rap_group_index++;
  2695.                     }
  2696.                 }
  2697.                 if (sc->keyframe_absent
  2698.                     && !sc->stps_count
  2699.                     && !rap_group_present
  2700.                     && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  2701.                      keyframe = 1;
  2702.                 if (keyframe)
  2703.                     distance = 0;
  2704.                 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  2705.                 if (sc->pseudo_stream_id == -1 ||
  2706.                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  2707.                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  2708.                     e->pos = current_offset;
  2709.                     e->timestamp = current_dts;
  2710.                     e->size = sample_size;
  2711.                     e->min_distance = distance;
  2712.                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  2713.                     av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2714.                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  2715.                             current_offset, current_dts, sample_size, distance, keyframe);
  2716.                     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  2717.                         ff_rfps_add_frame(mov->fc, st, current_dts);
  2718.                 }
  2719.  
  2720.                 current_offset += sample_size;
  2721.                 stream_size += sample_size;
  2722.  
  2723.                 /* A negative sample duration is invalid based on the spec,
  2724.                  * but some samples need it to correct the DTS. */
  2725.                 if (sc->stts_data[stts_index].duration < 0) {
  2726.                     av_log(mov->fc, AV_LOG_WARNING,
  2727.                            "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  2728.                            sc->stts_data[stts_index].duration, stts_index,
  2729.                            st->index);
  2730.                     dts_correction += sc->stts_data[stts_index].duration - 1;
  2731.                     sc->stts_data[stts_index].duration = 1;
  2732.                 }
  2733.                 current_dts += sc->stts_data[stts_index].duration;
  2734.                 if (!dts_correction || current_dts + dts_correction > last_dts) {
  2735.                     current_dts += dts_correction;
  2736.                     dts_correction = 0;
  2737.                 } else {
  2738.                     /* Avoid creating non-monotonous DTS */
  2739.                     dts_correction += current_dts - last_dts - 1;
  2740.                     current_dts = last_dts + 1;
  2741.                 }
  2742.                 last_dts = current_dts;
  2743.                 distance++;
  2744.                 stts_sample++;
  2745.                 current_sample++;
  2746.                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  2747.                     stts_sample = 0;
  2748.                     stts_index++;
  2749.                 }
  2750.             }
  2751.         }
  2752.         if (st->duration > 0)
  2753.             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  2754.     } else {
  2755.         unsigned chunk_samples, total = 0;
  2756.  
  2757.         // compute total chunk count
  2758.         for (i = 0; i < sc->stsc_count; i++) {
  2759.             unsigned count, chunk_count;
  2760.  
  2761.             chunk_samples = sc->stsc_data[i].count;
  2762.             if (i != sc->stsc_count - 1 &&
  2763.                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2764.                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2765.                 return;
  2766.             }
  2767.  
  2768.             if (sc->samples_per_frame >= 160) { // gsm
  2769.                 count = chunk_samples / sc->samples_per_frame;
  2770.             } else if (sc->samples_per_frame > 1) {
  2771.                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2772.                 count = (chunk_samples+samples-1) / samples;
  2773.             } else {
  2774.                 count = (chunk_samples+1023) / 1024;
  2775.             }
  2776.  
  2777.             if (i < sc->stsc_count - 1)
  2778.                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2779.             else
  2780.                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2781.             total += chunk_count * count;
  2782.         }
  2783.  
  2784.         av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
  2785.         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2786.             return;
  2787.         if (av_reallocp_array(&st->index_entries,
  2788.                               st->nb_index_entries + total,
  2789.                               sizeof(*st->index_entries)) < 0) {
  2790.             st->nb_index_entries = 0;
  2791.             return;
  2792.         }
  2793.         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2794.  
  2795.         // populate index
  2796.         for (i = 0; i < sc->chunk_count; i++) {
  2797.             current_offset = sc->chunk_offsets[i];
  2798.             if (stsc_index + 1 < sc->stsc_count &&
  2799.                 i + 1 == sc->stsc_data[stsc_index + 1].first)
  2800.                 stsc_index++;
  2801.             chunk_samples = sc->stsc_data[stsc_index].count;
  2802.  
  2803.             while (chunk_samples > 0) {
  2804.                 AVIndexEntry *e;
  2805.                 unsigned size, samples;
  2806.  
  2807.                 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  2808.                     avpriv_request_sample(mov->fc,
  2809.                            "Zero bytes per frame, but %d samples per frame",
  2810.                            sc->samples_per_frame);
  2811.                     return;
  2812.                 }
  2813.  
  2814.                 if (sc->samples_per_frame >= 160) { // gsm
  2815.                     samples = sc->samples_per_frame;
  2816.                     size = sc->bytes_per_frame;
  2817.                 } else {
  2818.                     if (sc->samples_per_frame > 1) {
  2819.                         samples = FFMIN((1024 / sc->samples_per_frame)*
  2820.                                         sc->samples_per_frame, chunk_samples);
  2821.                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2822.                     } else {
  2823.                         samples = FFMIN(1024, chunk_samples);
  2824.                         size = samples * sc->sample_size;
  2825.                     }
  2826.                 }
  2827.  
  2828.                 if (st->nb_index_entries >= total) {
  2829.                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  2830.                     return;
  2831.                 }
  2832.                 e = &st->index_entries[st->nb_index_entries++];
  2833.                 e->pos = current_offset;
  2834.                 e->timestamp = current_dts;
  2835.                 e->size = size;
  2836.                 e->min_distance = 0;
  2837.                 e->flags = AVINDEX_KEYFRAME;
  2838.                 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  2839.                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  2840.                         size, samples);
  2841.  
  2842.                 current_offset += size;
  2843.                 current_dts += samples;
  2844.                 chunk_samples -= samples;
  2845.             }
  2846.         }
  2847.     }
  2848. }
  2849.  
  2850. static int test_same_origin(const char *src, const char *ref) {
  2851.     char src_proto[64];
  2852.     char ref_proto[64];
  2853.     char src_auth[256];
  2854.     char ref_auth[256];
  2855.     char src_host[256];
  2856.     char ref_host[256];
  2857.     int src_port=-1;
  2858.     int ref_port=-1;
  2859.  
  2860.     av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
  2861.     av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
  2862.  
  2863.     if (strlen(src) == 0) {
  2864.         return -1;
  2865.     } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
  2866.         strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
  2867.         strlen(src_host) + 1 >= sizeof(src_host) ||
  2868.         strlen(ref_host) + 1 >= sizeof(ref_host)) {
  2869.         return 0;
  2870.     } else if (strcmp(src_proto, ref_proto) ||
  2871.                strcmp(src_auth, ref_auth) ||
  2872.                strcmp(src_host, ref_host) ||
  2873.                src_port != ref_port) {
  2874.         return 0;
  2875.     } else
  2876.         return 1;
  2877. }
  2878.  
  2879. static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref,
  2880.                          AVIOInterruptCB *int_cb)
  2881. {
  2882.     AVOpenCallback open_func = c->fc->open_cb;
  2883.  
  2884.     if (!open_func)
  2885.         open_func = ffio_open2_wrapper;
  2886.  
  2887.     /* try relative path, we do not try the absolute because it can leak information about our
  2888.        system to an attacker */
  2889.     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  2890.         char filename[1025];
  2891.         const char *src_path;
  2892.         int i, l;
  2893.  
  2894.         /* find a source dir */
  2895.         src_path = strrchr(src, '/');
  2896.         if (src_path)
  2897.             src_path++;
  2898.         else
  2899.             src_path = src;
  2900.  
  2901.         /* find a next level down to target */
  2902.         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  2903.             if (ref->path[l] == '/') {
  2904.                 if (i == ref->nlvl_to - 1)
  2905.                     break;
  2906.                 else
  2907.                     i++;
  2908.             }
  2909.  
  2910.         /* compose filename if next level down to target was found */
  2911.         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
  2912.             memcpy(filename, src, src_path - src);
  2913.             filename[src_path - src] = 0;
  2914.  
  2915.             for (i = 1; i < ref->nlvl_from; i++)
  2916.                 av_strlcat(filename, "../", sizeof(filename));
  2917.  
  2918.             av_strlcat(filename, ref->path + l + 1, sizeof(filename));
  2919.             if (!c->use_absolute_path && !c->fc->open_cb) {
  2920.                 int same_origin = test_same_origin(src, filename);
  2921.  
  2922.                 if (!same_origin) {
  2923.                     av_log(c->fc, AV_LOG_ERROR,
  2924.                         "Reference with mismatching origin, %s not tried for security reasons, "
  2925.                         "set demuxer option use_absolute_path to allow it anyway\n",
  2926.                         ref->path);
  2927.                     return AVERROR(ENOENT);
  2928.                 }
  2929.  
  2930.                 if(strstr(ref->path + l + 1, "..") ||
  2931.                    strstr(ref->path + l + 1, ":") ||
  2932.                    (ref->nlvl_from > 1 && same_origin < 0) ||
  2933.                    (filename[0] == '/' && src_path == src))
  2934.                     return AVERROR(ENOENT);
  2935.             }
  2936.  
  2937.             if (strlen(filename) + 1 == sizeof(filename))
  2938.                 return AVERROR(ENOENT);
  2939.             if (!open_func(c->fc, pb, filename, AVIO_FLAG_READ, int_cb, NULL))
  2940.                 return 0;
  2941.         }
  2942.     } else if (c->use_absolute_path) {
  2943.         av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
  2944.                "this is a possible security issue\n");
  2945.         if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
  2946.             return 0;
  2947.     } else if (c->fc->open_cb) {
  2948.         if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
  2949.             return 0;
  2950.     } else {
  2951.         av_log(c->fc, AV_LOG_ERROR,
  2952.                "Absolute path %s not tried for security reasons, "
  2953.                "set demuxer option use_absolute_path to allow absolute paths\n",
  2954.                ref->path);
  2955.     }
  2956.  
  2957.     return AVERROR(ENOENT);
  2958. }
  2959.  
  2960. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  2961. {
  2962.     if (sc->time_scale <= 0) {
  2963.         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  2964.         sc->time_scale = c->time_scale;
  2965.         if (sc->time_scale <= 0)
  2966.             sc->time_scale = 1;
  2967.     }
  2968. }
  2969.  
  2970. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2971. {
  2972.     AVStream *st;
  2973.     MOVStreamContext *sc;
  2974.     int ret;
  2975.  
  2976.     st = avformat_new_stream(c->fc, NULL);
  2977.     if (!st) return AVERROR(ENOMEM);
  2978.     st->id = c->fc->nb_streams;
  2979.     sc = av_mallocz(sizeof(MOVStreamContext));
  2980.     if (!sc) return AVERROR(ENOMEM);
  2981.  
  2982.     st->priv_data = sc;
  2983.     st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2984.     sc->ffindex = st->index;
  2985.  
  2986.     if ((ret = mov_read_default(c, pb, atom)) < 0)
  2987.         return ret;
  2988.  
  2989.     /* sanity checks */
  2990.     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2991.                             (!sc->sample_size && !sc->sample_count))) {
  2992.         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2993.                st->index);
  2994.         return 0;
  2995.     }
  2996.  
  2997.     fix_timescale(c, sc);
  2998.  
  2999.     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  3000.  
  3001.     mov_build_index(c, st);
  3002.  
  3003.     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  3004.         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  3005.         if (mov_open_dref(c, &sc->pb, c->fc->filename, dref,
  3006.                           &c->fc->interrupt_callback) < 0)
  3007.             av_log(c->fc, AV_LOG_ERROR,
  3008.                    "stream %d, error opening alias: path='%s', dir='%s', "
  3009.                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  3010.                    st->index, dref->path, dref->dir, dref->filename,
  3011.                    dref->volume, dref->nlvl_from, dref->nlvl_to);
  3012.     } else {
  3013.         sc->pb = c->fc->pb;
  3014.         sc->pb_is_copied = 1;
  3015.     }
  3016.  
  3017.     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  3018.         if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
  3019.             sc->height && sc->width &&
  3020.             (st->codec->width != sc->width || st->codec->height != sc->height)) {
  3021.             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  3022.                                              ((double)st->codec->width * sc->height), INT_MAX);
  3023.         }
  3024.  
  3025. #if FF_API_R_FRAME_RATE
  3026.         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  3027.             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  3028.                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  3029. #endif
  3030.     }
  3031.  
  3032.     // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  3033.     if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
  3034.         TAG_IS_AVCI(st->codec->codec_tag)) {
  3035.         ret = ff_generate_avci_extradata(st);
  3036.         if (ret < 0)
  3037.             return ret;
  3038.     }
  3039.  
  3040.     switch (st->codec->codec_id) {
  3041. #if CONFIG_H261_DECODER
  3042.     case AV_CODEC_ID_H261:
  3043. #endif
  3044. #if CONFIG_H263_DECODER
  3045.     case AV_CODEC_ID_H263:
  3046. #endif
  3047. #if CONFIG_MPEG4_DECODER
  3048.     case AV_CODEC_ID_MPEG4:
  3049. #endif
  3050.         st->codec->width = 0; /* let decoder init width/height */
  3051.         st->codec->height= 0;
  3052.         break;
  3053.     }
  3054.  
  3055.     /* Do not need those anymore. */
  3056.     av_freep(&sc->chunk_offsets);
  3057.     av_freep(&sc->stsc_data);
  3058.     av_freep(&sc->sample_sizes);
  3059.     av_freep(&sc->keyframes);
  3060.     av_freep(&sc->stts_data);
  3061.     av_freep(&sc->stps_data);
  3062.     av_freep(&sc->elst_data);
  3063.     av_freep(&sc->rap_group);
  3064.  
  3065.     return 0;
  3066. }
  3067.  
  3068. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3069. {
  3070.     int ret;
  3071.     c->itunes_metadata = 1;
  3072.     ret = mov_read_default(c, pb, atom);
  3073.     c->itunes_metadata = 0;
  3074.     return ret;
  3075. }
  3076.  
  3077. static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
  3078. {
  3079.     int64_t end = avio_tell(pb) + size;
  3080.     uint8_t *key = NULL, *val = NULL;
  3081.     int i;
  3082.     AVStream *st;
  3083.     MOVStreamContext *sc;
  3084.  
  3085.     if (c->fc->nb_streams < 1)
  3086.         return 0;
  3087.     st = c->fc->streams[c->fc->nb_streams-1];
  3088.     sc = st->priv_data;
  3089.  
  3090.     for (i = 0; i < 2; i++) {
  3091.         uint8_t **p;
  3092.         uint32_t len, tag;
  3093.         int ret;
  3094.  
  3095.         if (end - avio_tell(pb) <= 12)
  3096.             break;
  3097.  
  3098.         len = avio_rb32(pb);
  3099.         tag = avio_rl32(pb);
  3100.         avio_skip(pb, 4); // flags
  3101.  
  3102.         if (len < 12 || len - 12 > end - avio_tell(pb))
  3103.             break;
  3104.         len -= 12;
  3105.  
  3106.         if (tag == MKTAG('n', 'a', 'm', 'e'))
  3107.             p = &key;
  3108.         else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  3109.             avio_skip(pb, 4);
  3110.             len -= 4;
  3111.             p = &val;
  3112.         } else
  3113.             break;
  3114.  
  3115.         *p = av_malloc(len + 1);
  3116.         if (!*p)
  3117.             break;
  3118.         ret = ffio_read_size(pb, *p, len);
  3119.         if (ret < 0) {
  3120.             av_freep(p);
  3121.             return ret;
  3122.         }
  3123.         (*p)[len] = 0;
  3124.     }
  3125.  
  3126.     if (key && val) {
  3127.         if (strcmp(key, "iTunSMPB") == 0) {
  3128.             int priming, remainder, samples;
  3129.             if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  3130.                 if(priming>0 && priming<16384)
  3131.                     sc->start_pad = priming;
  3132.             }
  3133.         }
  3134.         if (strcmp(key, "cdec") != 0) {
  3135.             av_dict_set(&c->fc->metadata, key, val,
  3136.                         AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  3137.             key = val = NULL;
  3138.         }
  3139.     }
  3140.  
  3141.     avio_seek(pb, end, SEEK_SET);
  3142.     av_freep(&key);
  3143.     av_freep(&val);
  3144.     return 0;
  3145. }
  3146.  
  3147. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3148. {
  3149.     int64_t end = avio_tell(pb) + atom.size;
  3150.     uint32_t tag, len;
  3151.  
  3152.     if (atom.size < 8)
  3153.         goto fail;
  3154.  
  3155.     len = avio_rb32(pb);
  3156.     tag = avio_rl32(pb);
  3157.  
  3158.     if (len > atom.size)
  3159.         goto fail;
  3160.  
  3161.     if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
  3162.         uint8_t domain[128];
  3163.         int domain_len;
  3164.  
  3165.         avio_skip(pb, 4); // flags
  3166.         len -= 12;
  3167.  
  3168.         domain_len = avio_get_str(pb, len, domain, sizeof(domain));
  3169.         avio_skip(pb, len - domain_len);
  3170.         return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
  3171.     }
  3172.  
  3173. fail:
  3174.     av_log(c->fc, AV_LOG_VERBOSE,
  3175.            "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  3176.     return 0;
  3177. }
  3178.  
  3179. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3180. {
  3181.     while (atom.size > 8) {
  3182.         uint32_t tag = avio_rl32(pb);
  3183.         atom.size -= 4;
  3184.         if (tag == MKTAG('h','d','l','r')) {
  3185.             avio_seek(pb, -8, SEEK_CUR);
  3186.             atom.size += 8;
  3187.             return mov_read_default(c, pb, atom);
  3188.         }
  3189.     }
  3190.     return 0;
  3191. }
  3192.  
  3193. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3194. {
  3195.     int i;
  3196.     int width;
  3197.     int height;
  3198.     int display_matrix[3][3];
  3199.     AVStream *st;
  3200.     MOVStreamContext *sc;
  3201.     int version;
  3202.     int flags;
  3203.  
  3204.     if (c->fc->nb_streams < 1)
  3205.         return 0;
  3206.     st = c->fc->streams[c->fc->nb_streams-1];
  3207.     sc = st->priv_data;
  3208.  
  3209.     version = avio_r8(pb);
  3210.     flags = avio_rb24(pb);
  3211.     st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  3212.  
  3213.     if (version == 1) {
  3214.         avio_rb64(pb);
  3215.         avio_rb64(pb);
  3216.     } else {
  3217.         avio_rb32(pb); /* creation time */
  3218.         avio_rb32(pb); /* modification time */
  3219.     }
  3220.     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  3221.     avio_rb32(pb); /* reserved */
  3222.  
  3223.     /* highlevel (considering edits) duration in movie timebase */
  3224.     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  3225.     avio_rb32(pb); /* reserved */
  3226.     avio_rb32(pb); /* reserved */
  3227.  
  3228.     avio_rb16(pb); /* layer */
  3229.     avio_rb16(pb); /* alternate group */
  3230.     avio_rb16(pb); /* volume */
  3231.     avio_rb16(pb); /* reserved */
  3232.  
  3233.     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  3234.     // they're kept in fixed point format through all calculations
  3235.     // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  3236.     // side data, but the scale factor is not needed to calculate aspect ratio
  3237.     for (i = 0; i < 3; i++) {
  3238.         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
  3239.         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
  3240.         display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point
  3241.     }
  3242.  
  3243.     width = avio_rb32(pb);       // 16.16 fixed point track width
  3244.     height = avio_rb32(pb);      // 16.16 fixed point track height
  3245.     sc->width = width >> 16;
  3246.     sc->height = height >> 16;
  3247.  
  3248.     // save the matrix and add rotate metadata when it is not the default
  3249.     // identity
  3250.     if (display_matrix[0][0] != (1 << 16) ||
  3251.         display_matrix[1][1] != (1 << 16) ||
  3252.         display_matrix[2][2] != (1 << 30) ||
  3253.         display_matrix[0][1] || display_matrix[0][2] ||
  3254.         display_matrix[1][0] || display_matrix[1][2] ||
  3255.         display_matrix[2][0] || display_matrix[2][1]) {
  3256.         int i, j;
  3257.         double rotate;
  3258.  
  3259.         av_freep(&sc->display_matrix);
  3260.         sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  3261.         if (!sc->display_matrix)
  3262.             return AVERROR(ENOMEM);
  3263.  
  3264.         for (i = 0; i < 3; i++)
  3265.             for (j = 0; j < 3; j++)
  3266.                 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
  3267.  
  3268.         rotate = av_display_rotation_get(sc->display_matrix);
  3269.         if (!isnan(rotate)) {
  3270.             char rotate_buf[64];
  3271.             rotate = -rotate;
  3272.             if (rotate < 0) // for backward compatibility
  3273.                 rotate += 360;
  3274.             snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  3275.             av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  3276.         }
  3277.     }
  3278.  
  3279.     // transform the display width/height according to the matrix
  3280.     // to keep the same scale, use [width height 1<<16]
  3281.     if (width && height && sc->display_matrix) {
  3282.         double disp_transform[2];
  3283.  
  3284. #define SQR(a) ((a)*(double)(a))
  3285.         for (i = 0; i < 2; i++)
  3286.             disp_transform[i] = sqrt(SQR(display_matrix[i][0]) + SQR(display_matrix[i][1]));
  3287.  
  3288.         if (disp_transform[0] > 0       && disp_transform[1] > 0 &&
  3289.             disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
  3290.             fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
  3291.             st->sample_aspect_ratio = av_d2q(
  3292.                 disp_transform[0] / disp_transform[1],
  3293.                 INT_MAX);
  3294.     }
  3295.     return 0;
  3296. }
  3297.  
  3298. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3299. {
  3300.     MOVFragment *frag = &c->fragment;
  3301.     MOVTrackExt *trex = NULL;
  3302.     MOVFragmentIndex* index = NULL;
  3303.     int flags, track_id, i, found = 0;
  3304.  
  3305.     avio_r8(pb); /* version */
  3306.     flags = avio_rb24(pb);
  3307.  
  3308.     track_id = avio_rb32(pb);
  3309.     if (!track_id)
  3310.         return AVERROR_INVALIDDATA;
  3311.     frag->track_id = track_id;
  3312.     for (i = 0; i < c->trex_count; i++)
  3313.         if (c->trex_data[i].track_id == frag->track_id) {
  3314.             trex = &c->trex_data[i];
  3315.             break;
  3316.         }
  3317.     if (!trex) {
  3318.         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  3319.         return AVERROR_INVALIDDATA;
  3320.     }
  3321.  
  3322.     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  3323.                              avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  3324.                              frag->moof_offset : frag->implicit_offset;
  3325.     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  3326.  
  3327.     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  3328.                      avio_rb32(pb) : trex->duration;
  3329.     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
  3330.                      avio_rb32(pb) : trex->size;
  3331.     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
  3332.                      avio_rb32(pb) : trex->flags;
  3333.     frag->time     = AV_NOPTS_VALUE;
  3334.     for (i = 0; i < c->fragment_index_count; i++) {
  3335.         int j;
  3336.         MOVFragmentIndex* candidate = c->fragment_index_data[i];
  3337.         if (candidate->track_id == frag->track_id) {
  3338.             av_log(c->fc, AV_LOG_DEBUG,
  3339.                    "found fragment index for track %u\n", frag->track_id);
  3340.             index = candidate;
  3341.             for (j = index->current_item; j < index->item_count; j++) {
  3342.                 if (frag->implicit_offset == index->items[j].moof_offset) {
  3343.                     av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  3344.                             "for track %u and moof_offset %"PRId64"\n",
  3345.                             frag->track_id, index->items[j].moof_offset);
  3346.                     frag->time = index->items[j].time;
  3347.                     index->current_item = j + 1;
  3348.                     found = 1;
  3349.                     break;
  3350.                 }
  3351.             }
  3352.             if (found)
  3353.                 break;
  3354.         }
  3355.     }
  3356.     if (index && !found) {
  3357.         av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
  3358.                "it doesn't have an (in-order) entry for moof_offset "
  3359.                "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  3360.     }
  3361.     av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  3362.     return 0;
  3363. }
  3364.  
  3365. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3366. {
  3367.     c->chapter_track = avio_rb32(pb);
  3368.     return 0;
  3369. }
  3370.  
  3371. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3372. {
  3373.     MOVTrackExt *trex;
  3374.     int err;
  3375.  
  3376.     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  3377.         return AVERROR_INVALIDDATA;
  3378.     if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  3379.                                  sizeof(*c->trex_data))) < 0) {
  3380.         c->trex_count = 0;
  3381.         return err;
  3382.     }
  3383.  
  3384.     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  3385.  
  3386.     trex = &c->trex_data[c->trex_count++];
  3387.     avio_r8(pb); /* version */
  3388.     avio_rb24(pb); /* flags */
  3389.     trex->track_id = avio_rb32(pb);
  3390.     trex->stsd_id  = avio_rb32(pb);
  3391.     trex->duration = avio_rb32(pb);
  3392.     trex->size     = avio_rb32(pb);
  3393.     trex->flags    = avio_rb32(pb);
  3394.     return 0;
  3395. }
  3396.  
  3397. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3398. {
  3399.     MOVFragment *frag = &c->fragment;
  3400.     AVStream *st = NULL;
  3401.     MOVStreamContext *sc;
  3402.     int version, i;
  3403.  
  3404.     for (i = 0; i < c->fc->nb_streams; i++) {
  3405.         if (c->fc->streams[i]->id == frag->track_id) {
  3406.             st = c->fc->streams[i];
  3407.             break;
  3408.         }
  3409.     }
  3410.     if (!st) {
  3411.         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3412.         return AVERROR_INVALIDDATA;
  3413.     }
  3414.     sc = st->priv_data;
  3415.     if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  3416.         return 0;
  3417.     version = avio_r8(pb);
  3418.     avio_rb24(pb); /* flags */
  3419.     if (version) {
  3420.         sc->track_end = avio_rb64(pb);
  3421.     } else {
  3422.         sc->track_end = avio_rb32(pb);
  3423.     }
  3424.     return 0;
  3425. }
  3426.  
  3427. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3428. {
  3429.     MOVFragment *frag = &c->fragment;
  3430.     AVStream *st = NULL;
  3431.     MOVStreamContext *sc;
  3432.     MOVStts *ctts_data;
  3433.     uint64_t offset;
  3434.     int64_t dts;
  3435.     int data_offset = 0;
  3436.     unsigned entries, first_sample_flags = frag->flags;
  3437.     int flags, distance, i, found_keyframe = 0, err;
  3438.  
  3439.     for (i = 0; i < c->fc->nb_streams; i++) {
  3440.         if (c->fc->streams[i]->id == frag->track_id) {
  3441.             st = c->fc->streams[i];
  3442.             break;
  3443.         }
  3444.     }
  3445.     if (!st) {
  3446.         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3447.         return AVERROR_INVALIDDATA;
  3448.     }
  3449.     sc = st->priv_data;
  3450.     if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  3451.         return 0;
  3452.     avio_r8(pb); /* version */
  3453.     flags = avio_rb24(pb);
  3454.     entries = avio_rb32(pb);
  3455.     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
  3456.  
  3457.     /* Always assume the presence of composition time offsets.
  3458.      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  3459.      *  1) in the initial movie, there are no samples.
  3460.      *  2) in the first movie fragment, there is only one sample without composition time offset.
  3461.      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
  3462.     if (!sc->ctts_count && sc->sample_count)
  3463.     {
  3464.         /* Complement ctts table if moov atom doesn't have ctts atom. */
  3465.         ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  3466.         if (!ctts_data)
  3467.             return AVERROR(ENOMEM);
  3468.         sc->ctts_data = ctts_data;
  3469.         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  3470.         sc->ctts_data[sc->ctts_count].duration = 0;
  3471.         sc->ctts_count++;
  3472.     }
  3473.     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  3474.         return AVERROR_INVALIDDATA;
  3475.     if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  3476.                                  sizeof(*sc->ctts_data))) < 0) {
  3477.         sc->ctts_count = 0;
  3478.         return err;
  3479.     }
  3480.     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
  3481.     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  3482.     dts    = sc->track_end - sc->time_offset;
  3483.     offset = frag->base_data_offset + data_offset;
  3484.     distance = 0;
  3485.     av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  3486.     for (i = 0; i < entries && !pb->eof_reached; i++) {
  3487.         unsigned sample_size = frag->size;
  3488.         int sample_flags = i ? frag->flags : first_sample_flags;
  3489.         unsigned sample_duration = frag->duration;
  3490.         int keyframe = 0;
  3491.  
  3492.         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  3493.         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
  3494.         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
  3495.         sc->ctts_data[sc->ctts_count].count = 1;
  3496.         sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  3497.                                                   avio_rb32(pb) : 0;
  3498.         mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  3499.         if (frag->time != AV_NOPTS_VALUE) {
  3500.             if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  3501.                 int64_t pts = frag->time;
  3502.                 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3503.                         " sc->dts_shift %d ctts.duration %d"
  3504.                         " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  3505.                         sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
  3506.                         sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  3507.                 dts = pts - sc->dts_shift;
  3508.                 if (flags & MOV_TRUN_SAMPLE_CTS) {
  3509.                     dts -= sc->ctts_data[sc->ctts_count].duration;
  3510.                 } else {
  3511.                     dts -= sc->time_offset;
  3512.                 }
  3513.                 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  3514.             } else {
  3515.                 dts = frag->time;
  3516.                 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3517.                         ", using it for dts\n", dts);
  3518.             }
  3519.             frag->time = AV_NOPTS_VALUE;
  3520.         }
  3521.         sc->ctts_count++;
  3522.         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  3523.             keyframe = 1;
  3524.         else if (!found_keyframe)
  3525.             keyframe = found_keyframe =
  3526.                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  3527.                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  3528.         if (keyframe)
  3529.             distance = 0;
  3530.         err = av_add_index_entry(st, offset, dts, sample_size, distance,
  3531.                                  keyframe ? AVINDEX_KEYFRAME : 0);
  3532.         if (err < 0) {
  3533.             av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
  3534.         }
  3535.         av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  3536.                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  3537.                 offset, dts, sample_size, distance, keyframe);
  3538.         distance++;
  3539.         dts += sample_duration;
  3540.         offset += sample_size;
  3541.         sc->data_size += sample_size;
  3542.         sc->duration_for_fps += sample_duration;
  3543.         sc->nb_frames_for_fps ++;
  3544.     }
  3545.  
  3546.     if (pb->eof_reached)
  3547.         return AVERROR_EOF;
  3548.  
  3549.     frag->implicit_offset = offset;
  3550.  
  3551.     sc->track_end = dts + sc->time_offset;
  3552.     if (st->duration < sc->track_end)
  3553.         st->duration = sc->track_end;
  3554.  
  3555.     return 0;
  3556. }
  3557.  
  3558. static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3559. {
  3560.     int64_t offset = avio_tell(pb) + atom.size, pts;
  3561.     uint8_t version;
  3562.     unsigned i, track_id;
  3563.     AVStream *st = NULL;
  3564.     MOVStreamContext *sc;
  3565.     MOVFragmentIndex *index = NULL;
  3566.     MOVFragmentIndex **tmp;
  3567.     AVRational timescale;
  3568.  
  3569.     version = avio_r8(pb);
  3570.     if (version > 1) {
  3571.         avpriv_request_sample(c->fc, "sidx version %u", version);
  3572.         return AVERROR_PATCHWELCOME;
  3573.     }
  3574.  
  3575.     avio_rb24(pb); // flags
  3576.  
  3577.     track_id = avio_rb32(pb); // Reference ID
  3578.     for (i = 0; i < c->fc->nb_streams; i++) {
  3579.         if (c->fc->streams[i]->id == track_id) {
  3580.             st = c->fc->streams[i];
  3581.             break;
  3582.         }
  3583.     }
  3584.     if (!st) {
  3585.         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", track_id);
  3586.         return AVERROR_INVALIDDATA;
  3587.     }
  3588.  
  3589.     sc = st->priv_data;
  3590.  
  3591.     timescale = av_make_q(1, avio_rb32(pb));
  3592.  
  3593.     if (version == 0) {
  3594.         pts = avio_rb32(pb);
  3595.         offset += avio_rb32(pb);
  3596.     } else {
  3597.         pts = avio_rb64(pb);
  3598.         offset += avio_rb64(pb);
  3599.     }
  3600.  
  3601.     avio_rb16(pb); // reserved
  3602.  
  3603.     index = av_mallocz(sizeof(MOVFragmentIndex));
  3604.     if (!index)
  3605.         return AVERROR(ENOMEM);
  3606.  
  3607.     index->track_id = track_id;
  3608.  
  3609.     index->item_count = avio_rb16(pb);
  3610.     index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
  3611.  
  3612.     if (!index->items) {
  3613.         av_freep(&index);
  3614.         return AVERROR(ENOMEM);
  3615.     }
  3616.  
  3617.     for (i = 0; i < index->item_count; i++) {
  3618.         uint32_t size = avio_rb32(pb);
  3619.         uint32_t duration = avio_rb32(pb);
  3620.         if (size & 0x80000000) {
  3621.             avpriv_request_sample(c->fc, "sidx reference_type 1");
  3622.             av_freep(&index->items);
  3623.             av_freep(&index);
  3624.             return AVERROR_PATCHWELCOME;
  3625.         }
  3626.         avio_rb32(pb); // sap_flags
  3627.         index->items[i].moof_offset = offset;
  3628.         index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
  3629.         offset += size;
  3630.         pts += duration;
  3631.     }
  3632.  
  3633.     st->duration = sc->track_end = pts;
  3634.  
  3635.     tmp = av_realloc_array(c->fragment_index_data,
  3636.                            c->fragment_index_count + 1,
  3637.                            sizeof(MOVFragmentIndex*));
  3638.     if (!tmp) {
  3639.         av_freep(&index->items);
  3640.         av_freep(&index);
  3641.         return AVERROR(ENOMEM);
  3642.     }
  3643.  
  3644.     c->fragment_index_data = tmp;
  3645.     c->fragment_index_data[c->fragment_index_count++] = index;
  3646.  
  3647.     if (offset == avio_size(pb))
  3648.         c->fragment_index_complete = 1;
  3649.  
  3650.     return 0;
  3651. }
  3652.  
  3653. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  3654. /* like the files created with Adobe Premiere 5.0, for samples see */
  3655. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  3656. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3657. {
  3658.     int err;
  3659.  
  3660.     if (atom.size < 8)
  3661.         return 0; /* continue */
  3662.     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  3663.         avio_skip(pb, atom.size - 4);
  3664.         return 0;
  3665.     }
  3666.     atom.type = avio_rl32(pb);
  3667.     atom.size -= 8;
  3668.     if (atom.type != MKTAG('m','d','a','t')) {
  3669.         avio_skip(pb, atom.size);
  3670.         return 0;
  3671.     }
  3672.     err = mov_read_mdat(c, pb, atom);
  3673.     return err;
  3674. }
  3675.  
  3676. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3677. {
  3678. #if CONFIG_ZLIB
  3679.     AVIOContext ctx;
  3680.     uint8_t *cmov_data;
  3681.     uint8_t *moov_data; /* uncompressed data */
  3682.     long cmov_len, moov_len;
  3683.     int ret = -1;
  3684.  
  3685.     avio_rb32(pb); /* dcom atom */
  3686.     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  3687.         return AVERROR_INVALIDDATA;
  3688.     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  3689.         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  3690.         return AVERROR_INVALIDDATA;
  3691.     }
  3692.     avio_rb32(pb); /* cmvd atom */
  3693.     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  3694.         return AVERROR_INVALIDDATA;
  3695.     moov_len = avio_rb32(pb); /* uncompressed size */
  3696.     cmov_len = atom.size - 6 * 4;
  3697.  
  3698.     cmov_data = av_malloc(cmov_len);
  3699.     if (!cmov_data)
  3700.         return AVERROR(ENOMEM);
  3701.     moov_data = av_malloc(moov_len);
  3702.     if (!moov_data) {
  3703.         av_free(cmov_data);
  3704.         return AVERROR(ENOMEM);
  3705.     }
  3706.     ret = ffio_read_size(pb, cmov_data, cmov_len);
  3707.     if (ret < 0)
  3708.         goto free_and_return;
  3709.  
  3710.     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  3711.         goto free_and_return;
  3712.     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  3713.         goto free_and_return;
  3714.     ctx.seekable = AVIO_SEEKABLE_NORMAL;
  3715.     atom.type = MKTAG('m','o','o','v');
  3716.     atom.size = moov_len;
  3717.     ret = mov_read_default(c, &ctx, atom);
  3718. free_and_return:
  3719.     av_free(moov_data);
  3720.     av_free(cmov_data);
  3721.     return ret;
  3722. #else
  3723.     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  3724.     return AVERROR(ENOSYS);
  3725. #endif
  3726. }
  3727.  
  3728. /* edit list atom */
  3729. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3730. {
  3731.     MOVStreamContext *sc;
  3732.     int i, edit_count, version;
  3733.  
  3734.     if (c->fc->nb_streams < 1 || c->ignore_editlist)
  3735.         return 0;
  3736.     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  3737.  
  3738.     version = avio_r8(pb); /* version */
  3739.     avio_rb24(pb); /* flags */
  3740.     edit_count = avio_rb32(pb); /* entries */
  3741.  
  3742.     if (!edit_count)
  3743.         return 0;
  3744.     if (sc->elst_data)
  3745.         av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
  3746.     av_free(sc->elst_data);
  3747.     sc->elst_count = 0;
  3748.     sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
  3749.     if (!sc->elst_data)
  3750.         return AVERROR(ENOMEM);
  3751.  
  3752.     av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  3753.     for (i = 0; i < edit_count && !pb->eof_reached; i++) {
  3754.         MOVElst *e = &sc->elst_data[i];
  3755.  
  3756.         if (version == 1) {
  3757.             e->duration = avio_rb64(pb);
  3758.             e->time     = avio_rb64(pb);
  3759.         } else {
  3760.             e->duration = avio_rb32(pb); /* segment duration */
  3761.             e->time     = (int32_t)avio_rb32(pb); /* media time */
  3762.         }
  3763.         e->rate = avio_rb32(pb) / 65536.0;
  3764.         av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  3765.                 e->duration, e->time, e->rate);
  3766.     }
  3767.     sc->elst_count = i;
  3768.  
  3769.     return 0;
  3770. }
  3771.  
  3772. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3773. {
  3774.     MOVStreamContext *sc;
  3775.  
  3776.     if (c->fc->nb_streams < 1)
  3777.         return AVERROR_INVALIDDATA;
  3778.     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  3779.     sc->timecode_track = avio_rb32(pb);
  3780.     return 0;
  3781. }
  3782.  
  3783. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3784. {
  3785.     int ret;
  3786.     uint8_t uuid[16];
  3787.     static const uint8_t uuid_isml_manifest[] = {
  3788.         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3789.         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3790.     };
  3791.  
  3792.     if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
  3793.         return AVERROR_INVALIDDATA;
  3794.  
  3795.     ret = avio_read(pb, uuid, sizeof(uuid));
  3796.     if (ret < 0) {
  3797.         return ret;
  3798.     } else if (ret != sizeof(uuid)) {
  3799.         return AVERROR_INVALIDDATA;
  3800.     }
  3801.     if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  3802.         uint8_t *buffer, *ptr;
  3803.         char *endptr;
  3804.         size_t len = atom.size - sizeof(uuid);
  3805.  
  3806.         if (len < 4) {
  3807.             return AVERROR_INVALIDDATA;
  3808.         }
  3809.         ret = avio_skip(pb, 4); // zeroes
  3810.         len -= 4;
  3811.  
  3812.         buffer = av_mallocz(len + 1);
  3813.         if (!buffer) {
  3814.             return AVERROR(ENOMEM);
  3815.         }
  3816.         ret = avio_read(pb, buffer, len);
  3817.         if (ret < 0) {
  3818.             av_free(buffer);
  3819.             return ret;
  3820.         } else if (ret != len) {
  3821.             av_free(buffer);
  3822.             return AVERROR_INVALIDDATA;
  3823.         }
  3824.  
  3825.         ptr = buffer;
  3826.         while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  3827.             ptr += sizeof("systemBitrate=\"") - 1;
  3828.             c->bitrates_count++;
  3829.             c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  3830.             if (!c->bitrates) {
  3831.                 c->bitrates_count = 0;
  3832.                 av_free(buffer);
  3833.                 return AVERROR(ENOMEM);
  3834.             }
  3835.             errno = 0;
  3836.             ret = strtol(ptr, &endptr, 10);
  3837.             if (ret < 0 || errno || *endptr != '"') {
  3838.                 c->bitrates[c->bitrates_count - 1] = 0;
  3839.             } else {
  3840.                 c->bitrates[c->bitrates_count - 1] = ret;
  3841.             }
  3842.         }
  3843.  
  3844.         av_free(buffer);
  3845.     }
  3846.     return 0;
  3847. }
  3848.  
  3849. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3850. {
  3851.     int ret;
  3852.     uint8_t content[16];
  3853.  
  3854.     if (atom.size < 8)
  3855.         return 0;
  3856.  
  3857.     ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  3858.     if (ret < 0)
  3859.         return ret;
  3860.  
  3861.     if (   !c->found_moov
  3862.         && !c->found_mdat
  3863.         && !memcmp(content, "Anevia\x1A\x1A", 8)
  3864.         && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  3865.         c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  3866.     }
  3867.  
  3868.     return 0;
  3869. }
  3870.  
  3871. static const MOVParseTableEntry mov_default_parse_table[] = {
  3872. { MKTAG('A','C','L','R'), mov_read_aclr },
  3873. { MKTAG('A','P','R','G'), mov_read_avid },
  3874. { MKTAG('A','A','L','P'), mov_read_avid },
  3875. { MKTAG('A','R','E','S'), mov_read_ares },
  3876. { MKTAG('a','v','s','s'), mov_read_avss },
  3877. { MKTAG('c','h','p','l'), mov_read_chpl },
  3878. { MKTAG('c','o','6','4'), mov_read_stco },
  3879. { MKTAG('c','o','l','r'), mov_read_colr },
  3880. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  3881. { MKTAG('d','i','n','f'), mov_read_default },
  3882. { MKTAG('D','p','x','E'), mov_read_dpxe },
  3883. { MKTAG('d','r','e','f'), mov_read_dref },
  3884. { MKTAG('e','d','t','s'), mov_read_default },
  3885. { MKTAG('e','l','s','t'), mov_read_elst },
  3886. { MKTAG('e','n','d','a'), mov_read_enda },
  3887. { MKTAG('f','i','e','l'), mov_read_fiel },
  3888. { MKTAG('a','d','r','m'), mov_read_adrm },
  3889. { MKTAG('f','t','y','p'), mov_read_ftyp },
  3890. { MKTAG('g','l','b','l'), mov_read_glbl },
  3891. { MKTAG('h','d','l','r'), mov_read_hdlr },
  3892. { MKTAG('i','l','s','t'), mov_read_ilst },
  3893. { MKTAG('j','p','2','h'), mov_read_jp2h },
  3894. { MKTAG('m','d','a','t'), mov_read_mdat },
  3895. { MKTAG('m','d','h','d'), mov_read_mdhd },
  3896. { MKTAG('m','d','i','a'), mov_read_default },
  3897. { MKTAG('m','e','t','a'), mov_read_meta },
  3898. { MKTAG('m','i','n','f'), mov_read_default },
  3899. { MKTAG('m','o','o','f'), mov_read_moof },
  3900. { MKTAG('m','o','o','v'), mov_read_moov },
  3901. { MKTAG('m','v','e','x'), mov_read_default },
  3902. { MKTAG('m','v','h','d'), mov_read_mvhd },
  3903. { MKTAG('S','M','I',' '), mov_read_svq3 },
  3904. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  3905. { MKTAG('a','v','c','C'), mov_read_glbl },
  3906. { MKTAG('p','a','s','p'), mov_read_pasp },
  3907. { MKTAG('s','i','d','x'), mov_read_sidx },
  3908. { MKTAG('s','t','b','l'), mov_read_default },
  3909. { MKTAG('s','t','c','o'), mov_read_stco },
  3910. { MKTAG('s','t','p','s'), mov_read_stps },
  3911. { MKTAG('s','t','r','f'), mov_read_strf },
  3912. { MKTAG('s','t','s','c'), mov_read_stsc },
  3913. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  3914. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  3915. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  3916. { MKTAG('s','t','t','s'), mov_read_stts },
  3917. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  3918. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  3919. { MKTAG('t','f','d','t'), mov_read_tfdt },
  3920. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  3921. { MKTAG('t','r','a','k'), mov_read_trak },
  3922. { MKTAG('t','r','a','f'), mov_read_default },
  3923. { MKTAG('t','r','e','f'), mov_read_default },
  3924. { MKTAG('t','m','c','d'), mov_read_tmcd },
  3925. { MKTAG('c','h','a','p'), mov_read_chap },
  3926. { MKTAG('t','r','e','x'), mov_read_trex },
  3927. { MKTAG('t','r','u','n'), mov_read_trun },
  3928. { MKTAG('u','d','t','a'), mov_read_default },
  3929. { MKTAG('w','a','v','e'), mov_read_wave },
  3930. { MKTAG('e','s','d','s'), mov_read_esds },
  3931. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  3932. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  3933. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  3934. { MKTAG('w','f','e','x'), mov_read_wfex },
  3935. { MKTAG('c','m','o','v'), mov_read_cmov },
  3936. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  3937. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  3938. { MKTAG('s','b','g','p'), mov_read_sbgp },
  3939. { MKTAG('h','v','c','C'), mov_read_glbl },
  3940. { MKTAG('u','u','i','d'), mov_read_uuid },
  3941. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  3942. { MKTAG('f','r','e','e'), mov_read_free },
  3943. { MKTAG('-','-','-','-'), mov_read_custom },
  3944. { 0, NULL }
  3945. };
  3946.  
  3947. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3948. {
  3949.     int64_t total_size = 0;
  3950.     MOVAtom a;
  3951.     int i;
  3952.  
  3953.     if (c->atom_depth > 10) {
  3954.         av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
  3955.         return AVERROR_INVALIDDATA;
  3956.     }
  3957.     c->atom_depth ++;
  3958.  
  3959.     if (atom.size < 0)
  3960.         atom.size = INT64_MAX;
  3961.     while (total_size + 8 <= atom.size && !avio_feof(pb)) {
  3962.         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  3963.         a.size = atom.size;
  3964.         a.type=0;
  3965.         if (atom.size >= 8) {
  3966.             a.size = avio_rb32(pb);
  3967.             a.type = avio_rl32(pb);
  3968.             if (a.type == MKTAG('f','r','e','e') &&
  3969.                 a.size >= 8 &&
  3970.                 c->moov_retry) {
  3971.                 uint8_t buf[8];
  3972.                 uint32_t *type = (uint32_t *)buf + 1;
  3973.                 if (avio_read(pb, buf, 8) != 8)
  3974.                     return AVERROR_INVALIDDATA;
  3975.                 avio_seek(pb, -8, SEEK_CUR);
  3976.                 if (*type == MKTAG('m','v','h','d') ||
  3977.                     *type == MKTAG('c','m','o','v')) {
  3978.                     av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  3979.                     a.type = MKTAG('m','o','o','v');
  3980.                 }
  3981.             }
  3982.             if (atom.type != MKTAG('r','o','o','t') &&
  3983.                 atom.type != MKTAG('m','o','o','v'))
  3984.             {
  3985.                 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  3986.                 {
  3987.                     av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  3988.                     avio_skip(pb, -8);
  3989.                     c->atom_depth --;
  3990.                     return 0;
  3991.                 }
  3992.             }
  3993.             total_size += 8;
  3994.             if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
  3995.                 a.size = avio_rb64(pb) - 8;
  3996.                 total_size += 8;
  3997.             }
  3998.         }
  3999.         av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  4000.                 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  4001.         if (a.size == 0) {
  4002.             a.size = atom.size - total_size + 8;
  4003.         }
  4004.         a.size -= 8;
  4005.         if (a.size < 0)
  4006.             break;
  4007.         a.size = FFMIN(a.size, atom.size - total_size);
  4008.  
  4009.         for (i = 0; mov_default_parse_table[i].type; i++)
  4010.             if (mov_default_parse_table[i].type == a.type) {
  4011.                 parse = mov_default_parse_table[i].parse;
  4012.                 break;
  4013.             }
  4014.  
  4015.         // container is user data
  4016.         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  4017.                        atom.type == MKTAG('i','l','s','t')))
  4018.             parse = mov_read_udta_string;
  4019.  
  4020.         if (!parse) { /* skip leaf atoms data */
  4021.             avio_skip(pb, a.size);
  4022.         } else {
  4023.             int64_t start_pos = avio_tell(pb);
  4024.             int64_t left;
  4025.             int err = parse(c, pb, a);
  4026.             if (err < 0) {
  4027.                 c->atom_depth --;
  4028.                 return err;
  4029.             }
  4030.             if (c->found_moov && c->found_mdat &&
  4031.                 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
  4032.                  start_pos + a.size == avio_size(pb))) {
  4033.                 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
  4034.                     c->next_root_atom = start_pos + a.size;
  4035.                 c->atom_depth --;
  4036.                 return 0;
  4037.             }
  4038.             left = a.size - avio_tell(pb) + start_pos;
  4039.             if (left > 0) /* skip garbage at atom end */
  4040.                 avio_skip(pb, left);
  4041.             else if (left < 0) {
  4042.                 av_log(c->fc, AV_LOG_WARNING,
  4043.                        "overread end of atom '%.4s' by %"PRId64" bytes\n",
  4044.                        (char*)&a.type, -left);
  4045.                 avio_seek(pb, left, SEEK_CUR);
  4046.             }
  4047.         }
  4048.  
  4049.         total_size += a.size;
  4050.     }
  4051.  
  4052.     if (total_size < atom.size && atom.size < 0x7ffff)
  4053.         avio_skip(pb, atom.size - total_size);
  4054.  
  4055.     c->atom_depth --;
  4056.     return 0;
  4057. }
  4058.  
  4059. static int mov_probe(AVProbeData *p)
  4060. {
  4061.     int64_t offset;
  4062.     uint32_t tag;
  4063.     int score = 0;
  4064.     int moov_offset = -1;
  4065.  
  4066.     /* check file header */
  4067.     offset = 0;
  4068.     for (;;) {
  4069.         /* ignore invalid offset */
  4070.         if ((offset + 8) > (unsigned int)p->buf_size)
  4071.             break;
  4072.         tag = AV_RL32(p->buf + offset + 4);
  4073.         switch(tag) {
  4074.         /* check for obvious tags */
  4075.         case MKTAG('m','o','o','v'):
  4076.             moov_offset = offset + 4;
  4077.         case MKTAG('m','d','a','t'):
  4078.         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  4079.         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  4080.         case MKTAG('f','t','y','p'):
  4081.             if (AV_RB32(p->buf+offset) < 8 &&
  4082.                 (AV_RB32(p->buf+offset) != 1 ||
  4083.                  offset + 12 > (unsigned int)p->buf_size ||
  4084.                  AV_RB64(p->buf+offset + 8) == 0)) {
  4085.                 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  4086.             } else if (tag == MKTAG('f','t','y','p') &&
  4087.                        (   AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
  4088.                         || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
  4089.                     )) {
  4090.                 score = FFMAX(score, 5);
  4091.             } else {
  4092.                 score = AVPROBE_SCORE_MAX;
  4093.             }
  4094.             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4095.             break;
  4096.         /* those are more common words, so rate then a bit less */
  4097.         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  4098.         case MKTAG('w','i','d','e'):
  4099.         case MKTAG('f','r','e','e'):
  4100.         case MKTAG('j','u','n','k'):
  4101.         case MKTAG('p','i','c','t'):
  4102.             score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  4103.             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4104.             break;
  4105.         case MKTAG(0x82,0x82,0x7f,0x7d):
  4106.         case MKTAG('s','k','i','p'):
  4107.         case MKTAG('u','u','i','d'):
  4108.         case MKTAG('p','r','f','l'):
  4109.             /* if we only find those cause probedata is too small at least rate them */
  4110.             score  = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  4111.             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4112.             break;
  4113.         default:
  4114.             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4115.         }
  4116.     }
  4117.     if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  4118.         /* moov atom in the header - we should make sure that this is not a
  4119.          * MOV-packed MPEG-PS */
  4120.         offset = moov_offset;
  4121.  
  4122.         while(offset < (p->buf_size - 16)){ /* Sufficient space */
  4123.                /* We found an actual hdlr atom */
  4124.             if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
  4125.                AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
  4126.                AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  4127.                 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  4128.                 /* We found a media handler reference atom describing an
  4129.                  * MPEG-PS-in-MOV, return a
  4130.                  * low score to force expanding the probe window until
  4131.                  * mpegps_probe finds what it needs */
  4132.                 return 5;
  4133.             }else
  4134.                 /* Keep looking */
  4135.                 offset+=2;
  4136.         }
  4137.     }
  4138.  
  4139.     return score;
  4140. }
  4141.  
  4142. // must be done after parsing all trak because there's no order requirement
  4143. static void mov_read_chapters(AVFormatContext *s)
  4144. {
  4145.     MOVContext *mov = s->priv_data;
  4146.     AVStream *st = NULL;
  4147.     MOVStreamContext *sc;
  4148.     int64_t cur_pos;
  4149.     int i;
  4150.  
  4151.     for (i = 0; i < s->nb_streams; i++)
  4152.         if (s->streams[i]->id == mov->chapter_track) {
  4153.             st = s->streams[i];
  4154.             break;
  4155.         }
  4156.     if (!st) {
  4157.         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  4158.         return;
  4159.     }
  4160.  
  4161.     st->discard = AVDISCARD_ALL;
  4162.     sc = st->priv_data;
  4163.     cur_pos = avio_tell(sc->pb);
  4164.  
  4165.     for (i = 0; i < st->nb_index_entries; i++) {
  4166.         AVIndexEntry *sample = &st->index_entries[i];
  4167.         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  4168.         uint8_t *title;
  4169.         uint16_t ch;
  4170.         int len, title_len;
  4171.  
  4172.         if (end < sample->timestamp) {
  4173.             av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  4174.             end = AV_NOPTS_VALUE;
  4175.         }
  4176.  
  4177.         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  4178.             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  4179.             goto finish;
  4180.         }
  4181.  
  4182.         // the first two bytes are the length of the title
  4183.         len = avio_rb16(sc->pb);
  4184.         if (len > sample->size-2)
  4185.             continue;
  4186.         title_len = 2*len + 1;
  4187.         if (!(title = av_mallocz(title_len)))
  4188.             goto finish;
  4189.  
  4190.         // The samples could theoretically be in any encoding if there's an encd
  4191.         // atom following, but in practice are only utf-8 or utf-16, distinguished
  4192.         // instead by the presence of a BOM
  4193.         if (!len) {
  4194.             title[0] = 0;
  4195.         } else {
  4196.             ch = avio_rb16(sc->pb);
  4197.             if (ch == 0xfeff)
  4198.                 avio_get_str16be(sc->pb, len, title, title_len);
  4199.             else if (ch == 0xfffe)
  4200.                 avio_get_str16le(sc->pb, len, title, title_len);
  4201.             else {
  4202.                 AV_WB16(title, ch);
  4203.                 if (len == 1 || len == 2)
  4204.                     title[len] = 0;
  4205.                 else
  4206.                     avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  4207.             }
  4208.         }
  4209.  
  4210.         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  4211.         av_freep(&title);
  4212.     }
  4213. finish:
  4214.     avio_seek(sc->pb, cur_pos, SEEK_SET);
  4215. }
  4216.  
  4217. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  4218.                                              uint32_t value, int flags)
  4219. {
  4220.     AVTimecode tc;
  4221.     char buf[AV_TIMECODE_STR_SIZE];
  4222.     AVRational rate = {st->codec->time_base.den,
  4223.                        st->codec->time_base.num};
  4224.     int ret = av_timecode_init(&tc, rate, flags, 0, s);
  4225.     if (ret < 0)
  4226.         return ret;
  4227.     av_dict_set(&st->metadata, "timecode",
  4228.                 av_timecode_make_string(&tc, buf, value), 0);
  4229.     return 0;
  4230. }
  4231.  
  4232. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  4233. {
  4234.     MOVStreamContext *sc = st->priv_data;
  4235.     int flags = 0;
  4236.     int64_t cur_pos = avio_tell(sc->pb);
  4237.     uint32_t value;
  4238.  
  4239.     if (!st->nb_index_entries)
  4240.         return -1;
  4241.  
  4242.     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  4243.     value = avio_rb32(s->pb);
  4244.  
  4245.     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  4246.     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  4247.     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  4248.  
  4249.     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  4250.      * not the case) and thus assume "frame number format" instead of QT one.
  4251.      * No sample with tmcd track can be found with a QT timecode at the moment,
  4252.      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  4253.      * format). */
  4254.     parse_timecode_in_framenum_format(s, st, value, flags);
  4255.  
  4256.     avio_seek(sc->pb, cur_pos, SEEK_SET);
  4257.     return 0;
  4258. }
  4259.  
  4260. static int mov_read_close(AVFormatContext *s)
  4261. {
  4262.     MOVContext *mov = s->priv_data;
  4263.     int i, j;
  4264.  
  4265.     for (i = 0; i < s->nb_streams; i++) {
  4266.         AVStream *st = s->streams[i];
  4267.         MOVStreamContext *sc = st->priv_data;
  4268.  
  4269.         if (!sc)
  4270.             continue;
  4271.  
  4272.         av_freep(&sc->ctts_data);
  4273.         for (j = 0; j < sc->drefs_count; j++) {
  4274.             av_freep(&sc->drefs[j].path);
  4275.             av_freep(&sc->drefs[j].dir);
  4276.         }
  4277.         av_freep(&sc->drefs);
  4278.  
  4279.         sc->drefs_count = 0;
  4280.  
  4281.         if (!sc->pb_is_copied)
  4282.             avio_closep(&sc->pb);
  4283.  
  4284.         sc->pb = NULL;
  4285.         av_freep(&sc->chunk_offsets);
  4286.         av_freep(&sc->stsc_data);
  4287.         av_freep(&sc->sample_sizes);
  4288.         av_freep(&sc->keyframes);
  4289.         av_freep(&sc->stts_data);
  4290.         av_freep(&sc->stps_data);
  4291.         av_freep(&sc->elst_data);
  4292.         av_freep(&sc->rap_group);
  4293.         av_freep(&sc->display_matrix);
  4294.     }
  4295.  
  4296.     if (mov->dv_demux) {
  4297.         avformat_free_context(mov->dv_fctx);
  4298.         mov->dv_fctx = NULL;
  4299.     }
  4300.  
  4301.     av_freep(&mov->trex_data);
  4302.     av_freep(&mov->bitrates);
  4303.  
  4304.     for (i = 0; i < mov->fragment_index_count; i++) {
  4305.         MOVFragmentIndex* index = mov->fragment_index_data[i];
  4306.         av_freep(&index->items);
  4307.         av_freep(&mov->fragment_index_data[i]);
  4308.     }
  4309.     av_freep(&mov->fragment_index_data);
  4310.  
  4311.     av_freep(&mov->aes_decrypt);
  4312.  
  4313.     return 0;
  4314. }
  4315.  
  4316. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  4317. {
  4318.     int i;
  4319.  
  4320.     for (i = 0; i < s->nb_streams; i++) {
  4321.         AVStream *st = s->streams[i];
  4322.         MOVStreamContext *sc = st->priv_data;
  4323.  
  4324.         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  4325.             sc->timecode_track == tmcd_id)
  4326.             return 1;
  4327.     }
  4328.     return 0;
  4329. }
  4330.  
  4331. /* look for a tmcd track not referenced by any video track, and export it globally */
  4332. static void export_orphan_timecode(AVFormatContext *s)
  4333. {
  4334.     int i;
  4335.  
  4336.     for (i = 0; i < s->nb_streams; i++) {
  4337.         AVStream *st = s->streams[i];
  4338.  
  4339.         if (st->codec->codec_tag  == MKTAG('t','m','c','d') &&
  4340.             !tmcd_is_referenced(s, i + 1)) {
  4341.             AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  4342.             if (tcr) {
  4343.                 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  4344.                 break;
  4345.             }
  4346.         }
  4347.     }
  4348. }
  4349.  
  4350. static int read_tfra(MOVContext *mov, AVIOContext *f)
  4351. {
  4352.     MOVFragmentIndex* index = NULL;
  4353.     int version, fieldlength, i, j;
  4354.     int64_t pos = avio_tell(f);
  4355.     uint32_t size = avio_rb32(f);
  4356.     void *tmp;
  4357.  
  4358.     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  4359.         return 1;
  4360.     }
  4361.     av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  4362.     index = av_mallocz(sizeof(MOVFragmentIndex));
  4363.     if (!index) {
  4364.         return AVERROR(ENOMEM);
  4365.     }
  4366.  
  4367.     tmp = av_realloc_array(mov->fragment_index_data,
  4368.                            mov->fragment_index_count + 1,
  4369.                            sizeof(MOVFragmentIndex*));
  4370.     if (!tmp) {
  4371.         av_freep(&index);
  4372.         return AVERROR(ENOMEM);
  4373.     }
  4374.     mov->fragment_index_data = tmp;
  4375.     mov->fragment_index_data[mov->fragment_index_count++] = index;
  4376.  
  4377.     version = avio_r8(f);
  4378.     avio_rb24(f);
  4379.     index->track_id = avio_rb32(f);
  4380.     fieldlength = avio_rb32(f);
  4381.     index->item_count = avio_rb32(f);
  4382.     index->items = av_mallocz_array(
  4383.             index->item_count, sizeof(MOVFragmentIndexItem));
  4384.     if (!index->items) {
  4385.         index->item_count = 0;
  4386.         return AVERROR(ENOMEM);
  4387.     }
  4388.     for (i = 0; i < index->item_count; i++) {
  4389.         int64_t time, offset;
  4390.         if (version == 1) {
  4391.             time   = avio_rb64(f);
  4392.             offset = avio_rb64(f);
  4393.         } else {
  4394.             time   = avio_rb32(f);
  4395.             offset = avio_rb32(f);
  4396.         }
  4397.         index->items[i].time = time;
  4398.         index->items[i].moof_offset = offset;
  4399.         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  4400.             avio_r8(f);
  4401.         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  4402.             avio_r8(f);
  4403.         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  4404.             avio_r8(f);
  4405.     }
  4406.  
  4407.     avio_seek(f, pos + size, SEEK_SET);
  4408.     return 0;
  4409. }
  4410.  
  4411. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  4412. {
  4413.     int64_t stream_size = avio_size(f);
  4414.     int64_t original_pos = avio_tell(f);
  4415.     int64_t seek_ret;
  4416.     int32_t mfra_size;
  4417.     int ret = -1;
  4418.     if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
  4419.         ret = seek_ret;
  4420.         goto fail;
  4421.     }
  4422.     mfra_size = avio_rb32(f);
  4423.     if (mfra_size < 0 || mfra_size > stream_size) {
  4424.         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  4425.         goto fail;
  4426.     }
  4427.     if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
  4428.         ret = seek_ret;
  4429.         goto fail;
  4430.     }
  4431.     if (avio_rb32(f) != mfra_size) {
  4432.         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  4433.         goto fail;
  4434.     }
  4435.     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  4436.         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  4437.         goto fail;
  4438.     }
  4439.     av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  4440.     do {
  4441.         ret = read_tfra(c, f);
  4442.         if (ret < 0)
  4443.             goto fail;
  4444.     } while (!ret);
  4445.     ret = 0;
  4446. fail:
  4447.     seek_ret = avio_seek(f, original_pos, SEEK_SET);
  4448.     if (seek_ret < 0) {
  4449.         av_log(c->fc, AV_LOG_ERROR,
  4450.                "failed to seek back after looking for mfra\n");
  4451.         ret = seek_ret;
  4452.     }
  4453.     return ret;
  4454. }
  4455.  
  4456. static int mov_read_header(AVFormatContext *s)
  4457. {
  4458.     MOVContext *mov = s->priv_data;
  4459.     AVIOContext *pb = s->pb;
  4460.     int j, err;
  4461.     MOVAtom atom = { AV_RL32("root") };
  4462.     int i;
  4463.  
  4464.     mov->fc = s;
  4465.     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  4466.     if (pb->seekable)
  4467.         atom.size = avio_size(pb);
  4468.     else
  4469.         atom.size = INT64_MAX;
  4470.  
  4471.     /* check MOV header */
  4472.     do {
  4473.     if (mov->moov_retry)
  4474.         avio_seek(pb, 0, SEEK_SET);
  4475.     if ((err = mov_read_default(mov, pb, atom)) < 0) {
  4476.         av_log(s, AV_LOG_ERROR, "error reading header\n");
  4477.         mov_read_close(s);
  4478.         return err;
  4479.     }
  4480.     } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
  4481.     if (!mov->found_moov) {
  4482.         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  4483.         mov_read_close(s);
  4484.         return AVERROR_INVALIDDATA;
  4485.     }
  4486.     av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  4487.  
  4488.     if (pb->seekable) {
  4489.         if (mov->chapter_track > 0)
  4490.             mov_read_chapters(s);
  4491.         for (i = 0; i < s->nb_streams; i++)
  4492.             if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
  4493.                 mov_read_timecode_track(s, s->streams[i]);
  4494.     }
  4495.  
  4496.     /* copy timecode metadata from tmcd tracks to the related video streams */
  4497.     for (i = 0; i < s->nb_streams; i++) {
  4498.         AVStream *st = s->streams[i];
  4499.         MOVStreamContext *sc = st->priv_data;
  4500.         if (sc->timecode_track > 0) {
  4501.             AVDictionaryEntry *tcr;
  4502.             int tmcd_st_id = -1;
  4503.  
  4504.             for (j = 0; j < s->nb_streams; j++)
  4505.                 if (s->streams[j]->id == sc->timecode_track)
  4506.                     tmcd_st_id = j;
  4507.  
  4508.             if (tmcd_st_id < 0 || tmcd_st_id == i)
  4509.                 continue;
  4510.             tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  4511.             if (tcr)
  4512.                 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  4513.         }
  4514.     }
  4515.     export_orphan_timecode(s);
  4516.  
  4517.     for (i = 0; i < s->nb_streams; i++) {
  4518.         AVStream *st = s->streams[i];
  4519.         MOVStreamContext *sc = st->priv_data;
  4520.         fix_timescale(mov, sc);
  4521.         if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
  4522.             st->skip_samples = sc->start_pad;
  4523.         }
  4524.         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  4525.             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  4526.                       sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  4527.         if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  4528.             if (st->codec->width <= 0 || st->codec->height <= 0) {
  4529.                 st->codec->width  = sc->width;
  4530.                 st->codec->height = sc->height;
  4531.             }
  4532.             if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  4533.                 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  4534.                     return err;
  4535.             }
  4536.         }
  4537.         if (mov->handbrake_version &&
  4538.             mov->handbrake_version <= 1000000*0 + 1000*10 + 2 &&  // 0.10.2
  4539.             st->codec->codec_id == AV_CODEC_ID_MP3
  4540.         ) {
  4541.             av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
  4542.             st->need_parsing = AVSTREAM_PARSE_FULL;
  4543.         }
  4544.     }
  4545.  
  4546.     if (mov->trex_data) {
  4547.         for (i = 0; i < s->nb_streams; i++) {
  4548.             AVStream *st = s->streams[i];
  4549.             MOVStreamContext *sc = st->priv_data;
  4550.             if (st->duration > 0)
  4551.                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  4552.         }
  4553.     }
  4554.  
  4555.     if (mov->use_mfra_for > 0) {
  4556.         for (i = 0; i < s->nb_streams; i++) {
  4557.             AVStream *st = s->streams[i];
  4558.             MOVStreamContext *sc = st->priv_data;
  4559.             if (sc->duration_for_fps > 0) {
  4560.                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
  4561.                     sc->duration_for_fps;
  4562.             }
  4563.         }
  4564.     }
  4565.  
  4566.     for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  4567.         if (mov->bitrates[i]) {
  4568.             s->streams[i]->codec->bit_rate = mov->bitrates[i];
  4569.         }
  4570.     }
  4571.  
  4572.     ff_rfps_calculate(s);
  4573.  
  4574.     for (i = 0; i < s->nb_streams; i++) {
  4575.         AVStream *st = s->streams[i];
  4576.         MOVStreamContext *sc = st->priv_data;
  4577.  
  4578.         switch (st->codec->codec_type) {
  4579.         case AVMEDIA_TYPE_AUDIO:
  4580.             err = ff_replaygain_export(st, s->metadata);
  4581.             if (err < 0) {
  4582.                 mov_read_close(s);
  4583.                 return err;
  4584.             }
  4585.             break;
  4586.         case AVMEDIA_TYPE_VIDEO:
  4587.             if (sc->display_matrix) {
  4588.                 AVPacketSideData *sd, *tmp;
  4589.  
  4590.                 tmp = av_realloc_array(st->side_data,
  4591.                                        st->nb_side_data + 1, sizeof(*tmp));
  4592.                 if (!tmp)
  4593.                     return AVERROR(ENOMEM);
  4594.  
  4595.                 st->side_data = tmp;
  4596.                 st->nb_side_data++;
  4597.  
  4598.                 sd = &st->side_data[st->nb_side_data - 1];
  4599.                 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  4600.                 sd->size = sizeof(int32_t) * 9;
  4601.                 sd->data = (uint8_t*)sc->display_matrix;
  4602.                 sc->display_matrix = NULL;
  4603.             }
  4604.             break;
  4605.         }
  4606.     }
  4607.     ff_configure_buffers_for_index(s, AV_TIME_BASE);
  4608.  
  4609.     return 0;
  4610. }
  4611.  
  4612. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  4613. {
  4614.     AVIndexEntry *sample = NULL;
  4615.     int64_t best_dts = INT64_MAX;
  4616.     int i;
  4617.     for (i = 0; i < s->nb_streams; i++) {
  4618.         AVStream *avst = s->streams[i];
  4619.         MOVStreamContext *msc = avst->priv_data;
  4620.         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  4621.             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  4622.             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  4623.             av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  4624.             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  4625.                 (s->pb->seekable &&
  4626.                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  4627.                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  4628.                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  4629.                 sample = current_sample;
  4630.                 best_dts = dts;
  4631.                 *st = avst;
  4632.             }
  4633.         }
  4634.     }
  4635.     return sample;
  4636. }
  4637.  
  4638. static int should_retry(AVIOContext *pb, int error_code) {
  4639.     if (error_code == AVERROR_EOF || avio_feof(pb))
  4640.         return 0;
  4641.  
  4642.     return 1;
  4643. }
  4644.  
  4645. static int mov_switch_root(AVFormatContext *s, int64_t target)
  4646. {
  4647.     MOVContext *mov = s->priv_data;
  4648.     int i, j;
  4649.     int already_read = 0;
  4650.  
  4651.     if (avio_seek(s->pb, target, SEEK_SET) != target) {
  4652.         av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
  4653.         return AVERROR_INVALIDDATA;
  4654.     }
  4655.  
  4656.     mov->next_root_atom = 0;
  4657.  
  4658.     for (i = 0; i < mov->fragment_index_count; i++) {
  4659.         MOVFragmentIndex *index = mov->fragment_index_data[i];
  4660.         int found = 0;
  4661.         for (j = 0; j < index->item_count; j++) {
  4662.             MOVFragmentIndexItem *item = &index->items[j];
  4663.             if (found) {
  4664.                 mov->next_root_atom = item->moof_offset;
  4665.                 break; // Advance to next index in outer loop
  4666.             } else if (item->moof_offset == target) {
  4667.                 index->current_item = FFMIN(j, index->current_item);
  4668.                 if (item->headers_read)
  4669.                     already_read = 1;
  4670.                 item->headers_read = 1;
  4671.                 found = 1;
  4672.             }
  4673.         }
  4674.         if (!found)
  4675.             index->current_item = 0;
  4676.     }
  4677.  
  4678.     if (already_read)
  4679.         return 0;
  4680.  
  4681.     mov->found_mdat = 0;
  4682.  
  4683.     if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  4684.         avio_feof(s->pb))
  4685.         return AVERROR_EOF;
  4686.     av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  4687.  
  4688.     return 1;
  4689. }
  4690.  
  4691. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  4692. {
  4693.     MOVContext *mov = s->priv_data;
  4694.     MOVStreamContext *sc;
  4695.     AVIndexEntry *sample;
  4696.     AVStream *st = NULL;
  4697.     int ret;
  4698.     mov->fc = s;
  4699.  retry:
  4700.     sample = mov_find_next_sample(s, &st);
  4701.     if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
  4702.         if (!mov->next_root_atom)
  4703.             return AVERROR_EOF;
  4704.         if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
  4705.             return ret;
  4706.         goto retry;
  4707.     }
  4708.     sc = st->priv_data;
  4709.     /* must be done just before reading, to avoid infinite loop on sample */
  4710.     sc->current_sample++;
  4711.  
  4712.     if (mov->next_root_atom) {
  4713.         sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  4714.         sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  4715.     }
  4716.  
  4717.     if (st->discard != AVDISCARD_ALL) {
  4718.         int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
  4719.         if (ret64 != sample->pos) {
  4720.             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  4721.                    sc->ffindex, sample->pos);
  4722.             sc->current_sample -= should_retry(sc->pb, ret64);
  4723.             return AVERROR_INVALIDDATA;
  4724.         }
  4725.         ret = av_get_packet(sc->pb, pkt, sample->size);
  4726.         if (ret < 0) {
  4727.             sc->current_sample -= should_retry(sc->pb, ret);
  4728.             return ret;
  4729.         }
  4730.         if (sc->has_palette) {
  4731.             uint8_t *pal;
  4732.  
  4733.             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  4734.             if (!pal) {
  4735.                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  4736.             } else {
  4737.                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
  4738.                 sc->has_palette = 0;
  4739.             }
  4740.         }
  4741. #if CONFIG_DV_DEMUXER
  4742.         if (mov->dv_demux && sc->dv_audio_container) {
  4743.             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  4744.             av_freep(&pkt->data);
  4745.             pkt->size = 0;
  4746.             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  4747.             if (ret < 0)
  4748.                 return ret;
  4749.         }
  4750. #endif
  4751.     }
  4752.  
  4753.     pkt->stream_index = sc->ffindex;
  4754.     pkt->dts = sample->timestamp;
  4755.     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  4756.         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  4757.         /* update ctts context */
  4758.         sc->ctts_sample++;
  4759.         if (sc->ctts_index < sc->ctts_count &&
  4760.             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  4761.             sc->ctts_index++;
  4762.             sc->ctts_sample = 0;
  4763.         }
  4764.         if (sc->wrong_dts)
  4765.             pkt->dts = AV_NOPTS_VALUE;
  4766.     } else {
  4767.         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  4768.             st->index_entries[sc->current_sample].timestamp : st->duration;
  4769.         pkt->duration = next_dts - pkt->dts;
  4770.         pkt->pts = pkt->dts;
  4771.     }
  4772.     if (st->discard == AVDISCARD_ALL)
  4773.         goto retry;
  4774.     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  4775.     pkt->pos = sample->pos;
  4776.  
  4777.     if (mov->aax_mode)
  4778.         aax_filter(pkt->data, pkt->size, mov);
  4779.  
  4780.     return 0;
  4781. }
  4782.  
  4783. static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
  4784. {
  4785.     MOVContext *mov = s->priv_data;
  4786.     int i, j;
  4787.  
  4788.     if (!mov->fragment_index_complete)
  4789.         return 0;
  4790.  
  4791.     for (i = 0; i < mov->fragment_index_count; i++) {
  4792.         if (mov->fragment_index_data[i]->track_id == st->id) {
  4793.             MOVFragmentIndex *index = index = mov->fragment_index_data[i];
  4794.             for (j = index->item_count - 1; j >= 0; j--) {
  4795.                 if (index->items[j].time <= timestamp) {
  4796.                     if (index->items[j].headers_read)
  4797.                         return 0;
  4798.  
  4799.                     return mov_switch_root(s, index->items[j].moof_offset);
  4800.                 }
  4801.             }
  4802.         }
  4803.     }
  4804.  
  4805.     return 0;
  4806. }
  4807.  
  4808. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  4809. {
  4810.     MOVStreamContext *sc = st->priv_data;
  4811.     int sample, time_sample;
  4812.     int i;
  4813.  
  4814.     int ret = mov_seek_fragment(s, st, timestamp);
  4815.     if (ret < 0)
  4816.         return ret;
  4817.  
  4818.     sample = av_index_search_timestamp(st, timestamp, flags);
  4819.     av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  4820.     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  4821.         sample = 0;
  4822.     if (sample < 0) /* not sure what to do */
  4823.         return AVERROR_INVALIDDATA;
  4824.     sc->current_sample = sample;
  4825.     av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  4826.     /* adjust ctts index */
  4827.     if (sc->ctts_data) {
  4828.         time_sample = 0;
  4829.         for (i = 0; i < sc->ctts_count; i++) {
  4830.             int next = time_sample + sc->ctts_data[i].count;
  4831.             if (next > sc->current_sample) {
  4832.                 sc->ctts_index = i;
  4833.                 sc->ctts_sample = sc->current_sample - time_sample;
  4834.                 break;
  4835.             }
  4836.             time_sample = next;
  4837.         }
  4838.     }
  4839.     return sample;
  4840. }
  4841.  
  4842. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  4843. {
  4844.     MOVContext *mc = s->priv_data;
  4845.     AVStream *st;
  4846.     int sample;
  4847.     int i;
  4848.  
  4849.     if (stream_index >= s->nb_streams)
  4850.         return AVERROR_INVALIDDATA;
  4851.  
  4852.     st = s->streams[stream_index];
  4853.     sample = mov_seek_stream(s, st, sample_time, flags);
  4854.     if (sample < 0)
  4855.         return sample;
  4856.  
  4857.     if (mc->seek_individually) {
  4858.         /* adjust seek timestamp to found sample timestamp */
  4859.         int64_t seek_timestamp = st->index_entries[sample].timestamp;
  4860.  
  4861.         for (i = 0; i < s->nb_streams; i++) {
  4862.             int64_t timestamp;
  4863.             MOVStreamContext *sc = s->streams[i]->priv_data;
  4864.             st = s->streams[i];
  4865.             st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  4866.  
  4867.             if (stream_index == i)
  4868.                 continue;
  4869.  
  4870.             timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  4871.             mov_seek_stream(s, st, timestamp, flags);
  4872.         }
  4873.     } else {
  4874.         for (i = 0; i < s->nb_streams; i++) {
  4875.             MOVStreamContext *sc;
  4876.             st = s->streams[i];
  4877.             sc = st->priv_data;
  4878.             sc->current_sample = 0;
  4879.         }
  4880.         while (1) {
  4881.             MOVStreamContext *sc;
  4882.             AVIndexEntry *entry = mov_find_next_sample(s, &st);
  4883.             if (!entry)
  4884.                 return AVERROR_INVALIDDATA;
  4885.             sc = st->priv_data;
  4886.             if (sc->ffindex == stream_index && sc->current_sample == sample)
  4887.                 break;
  4888.             sc->current_sample++;
  4889.         }
  4890.     }
  4891.     return 0;
  4892. }
  4893.  
  4894. #define OFFSET(x) offsetof(MOVContext, x)
  4895. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  4896. static const AVOption mov_options[] = {
  4897.     {"use_absolute_path",
  4898.         "allow using absolute path when opening alias, this is a possible security issue",
  4899.         OFFSET(use_absolute_path), AV_OPT_TYPE_INT, {.i64 = 0},
  4900.         0, 1, FLAGS},
  4901.     {"seek_streams_individually",
  4902.         "Seek each stream individually to the to the closest point",
  4903.         OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
  4904.         0, 1, FLAGS},
  4905.     {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_INT, {.i64 = 0},
  4906.         0, 1, FLAGS},
  4907.     {"use_mfra_for",
  4908.         "use mfra for fragment timestamps",
  4909.         OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  4910.         -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
  4911.         "use_mfra_for"},
  4912.     {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  4913.         FLAGS, "use_mfra_for" },
  4914.     {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  4915.         FLAGS, "use_mfra_for" },
  4916.     {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  4917.         FLAGS, "use_mfra_for" },
  4918.     { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  4919.         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  4920.     { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  4921.         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  4922.     { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
  4923.         AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  4924.     { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  4925.         "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
  4926.         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
  4927.         .flags = AV_OPT_FLAG_DECODING_PARAM },
  4928.     { NULL },
  4929. };
  4930.  
  4931. static const AVClass mov_class = {
  4932.     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  4933.     .item_name  = av_default_item_name,
  4934.     .option     = mov_options,
  4935.     .version    = LIBAVUTIL_VERSION_INT,
  4936. };
  4937.  
  4938. AVInputFormat ff_mov_demuxer = {
  4939.     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
  4940.     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  4941.     .priv_class     = &mov_class,
  4942.     .priv_data_size = sizeof(MOVContext),
  4943.     .extensions     = "mov,mp4,m4a,3gp,3g2,mj2",
  4944.     .read_probe     = mov_probe,
  4945.     .read_header    = mov_read_header,
  4946.     .read_packet    = mov_read_packet,
  4947.     .read_close     = mov_read_close,
  4948.     .read_seek      = mov_read_seek,
  4949.     .flags          = AVFMT_NO_BYTE_SEEK,
  4950. };
  4951.