/*
 * MOV demuxer
 * Copyright (c) 2001 Fabrice Bellard
 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <limits.h>

//#define DEBUG
//#define DEBUG_METADATA
//#define MOV_EXPORT_ALL_METADATA

#include "libavutil/intreadwrite.h"
#include "libavutil/avstring.h"
#include "avformat.h"
#include "avio_internal.h"
#include "riff.h"
#include "isom.h"
#include "libavutil/dict.h"
#include "libavcodec/get_bits.h"
#include "libavformat/avformat.h"


#if CONFIG_ZLIB
#include <zlib.h>
#endif

// #include <android/log.h>
// #undef LOG_TAG
// #define  LOG_TAG    "mov.c"
// #undef LOGI
// #define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
// #undef LOGE
// #define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
// #undef LOGW
// #define  LOGW(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
// #undef LOGV
// #define  LOGV(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
// #undef LOGD
// #define  LOGD(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)

#undef LOGD
#define  LOGD(...)  av_log(NULL, AV_LOG_DEBUG, __VA_ARGS__);
#undef LOGI
#define  LOGI(...)  av_log(NULL, AV_LOG_INFO, __VA_ARGS__);
#undef LOGE
#define  LOGE(...)  av_log(NULL, AV_LOG_ERROR, __VA_ARGS__);
#undef LOGW
#define  LOGW(...)  av_log(NULL, AV_LOG_WARNING, __VA_ARGS__);

// #undef LOG_TAG
// #define  LOG_TAG    "mov.c"
//#undef LOGD
//#define  LOGD(...)  ((void)0)
//#undef LOGI
//#define  LOGI(...)  ((void)0)
//#undef LOGE
//#define  LOGE(...)  ((void)0)
//#undef LOGW
//#define  LOGW(...)  ((void)0)  
//#undef LOGV
//#define  LOGV(...)  ((void)0) 
//#undef LOGD
//#define  LOGD(...)  ((void)0) 

/*
 * First version by Francois Revol revol@free.fr
 * Seek function by Gael Chardon gael.dev@4now.net
 *
 * Features and limitations:
 * - reads most of the QT files I have (at least the structure),
 *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
 * - the code is quite ugly... maybe I won't do it recursive next time :-)
 *
 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
 * when coding this :) (it's a writer anyway)
 *
 * Reference documents:
 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
 * Apple:
 *  http://developer.apple.com/documentation/QuickTime/QTFF/
 *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
 * QuickTime is a trademark of Apple (AFAIK :))
 */

#include "qtpalette.h"


#undef NDEBUG
#include <assert.h>

/* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */

/* those functions parse an atom */
/* return code:
  0: continue to parse next atom
 <0: error occurred, exit
*/
/* links atom IDs to parse functions */
typedef struct MOVParseTableEntry {
    uint32_t type;
    int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
} MOVParseTableEntry;

static const MOVParseTableEntry mov_default_parse_table[];

static int mov_metadata_trkn(MOVContext *c, AVIOContext *pb, unsigned len)
{
    char buf[16];

    avio_rb16(pb); // unknown
    snprintf(buf, sizeof(buf), "%d", avio_rb16(pb));
    av_dict_set(&c->fc->metadata, "track", buf, 0);

    avio_rb16(pb); // total tracks

    return 0;
}

static const uint32_t mac_to_unicode[128] = {
    0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
    0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
    0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
    0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
    0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
    0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
    0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
    0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
    0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
    0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
    0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
    0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
    0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
    0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
    0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
    0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
};

static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
                               char *dst, int dstlen)
{
    char *p = dst;
    char *end = dst+dstlen-1;
    int i;

    for (i = 0; i < len; i++) {
        uint8_t t, c = avio_r8(pb);
        if (c < 0x80 && p < end)
            *p++ = c;
        else
            PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
    }
    *p = 0;
    return p - dst;
}

static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
#ifdef MOV_EXPORT_ALL_METADATA
    char tmp_key[5];
#endif
    char str[1024], key2[16], language[4] = {0};
    const char *key = NULL;
    uint16_t str_size, langcode = 0;
    uint32_t data_type = 0;
    int (*parse)(MOVContext*, AVIOContext*, unsigned) = NULL;

    switch (atom.type) {
    case MKTAG(0xa9,'n','a','m'): key = "title";     break;
    case MKTAG(0xa9,'a','u','t'):
    case MKTAG(0xa9,'A','R','T'): key = "artist";    break;
    case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
    case MKTAG( 'c','p','r','t'):
    case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
    case MKTAG(0xa9,'c','m','t'):
    case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
    case MKTAG(0xa9,'a','l','b'): key = "album";     break;
    case MKTAG(0xa9,'d','a','y'): key = "date";      break;
    case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
    case MKTAG(0xa9,'t','o','o'):
    case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
    case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
    case MKTAG( 'd','e','s','c'): key = "description";break;
    case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
    case MKTAG( 't','v','s','h'): key = "show";      break;
    case MKTAG( 't','v','e','n'): key = "episode_id";break;
    case MKTAG( 't','v','n','n'): key = "network";   break;
    case MKTAG( 't','r','k','n'): key = "track";
        parse = mov_metadata_trkn; break;
    }

    if (c->itunes_metadata && atom.size > 8) {
        int data_size = avio_rb32(pb);
        int tag = avio_rl32(pb);
        if (tag == MKTAG('d','a','t','a')) {
            data_type = avio_rb32(pb); // type
            avio_rb32(pb); // unknown
            str_size = data_size - 16;
            atom.size -= 16;
        } else return 0;
    } else if (atom.size > 4 && key && !c->itunes_metadata) {
        str_size = avio_rb16(pb); // string length
        langcode = avio_rb16(pb);
        ff_mov_lang_to_iso639(langcode, language);
        atom.size -= 4;
    } else
        str_size = atom.size;

#ifdef MOV_EXPORT_ALL_METADATA
    if (!key) {
        snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
        key = tmp_key;
    }
#endif

    if (!key)
        return 0;
    if (atom.size < 0)
        return -1;

    str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);

    if (parse)
        parse(c, pb, str_size);
    else {
        if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
            mov_read_mac_string(c, pb, str_size, str, sizeof(str));
        } else {
            avio_read(pb, str, str_size);
            str[str_size] = 0;
        }
        av_dict_set(&c->fc->metadata, key, str, 0);
        if (*language && strcmp(language, "und")) {
            snprintf(key2, sizeof(key2), "%s-%s", key, language);
            av_dict_set(&c->fc->metadata, key2, str, 0);
        }
    }
#ifdef DEBUG_METADATA
    av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
    av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
           key, str, (char*)&atom.type, str_size, atom.size);
#endif

    return 0;
}

static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    int64_t start;
    int i, nb_chapters, str_len, version;
    char str[256+1];

    if ((atom.size -= 5) < 0)
        return 0;

    version = avio_r8(pb);
    avio_rb24(pb);
    if (version)
        avio_rb32(pb); // ???
    nb_chapters = avio_r8(pb);

    for (i = 0; i < nb_chapters; i++) {
        if (atom.size < 9)
            return 0;

        start = avio_rb64(pb);
        str_len = avio_r8(pb);

        if ((atom.size -= 9+str_len) < 0)
            return 0;

        avio_read(pb, str, str_len);
        str[str_len] = 0;
//         ff_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
    }
    return 0;
}

static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    int64_t total_size = 0;
    MOVAtom a;
    int i;

    if (atom.size < 0)
        atom.size = INT64_MAX;
    while (total_size + 8 < atom.size && !url_feof(pb)) {
        int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
        a.size = atom.size;
        a.type=0;
        if(atom.size >= 8) {
            a.size = avio_rb32(pb);
            a.type = avio_rl32(pb);
        }
//         LOGD("type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
//                 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
        total_size += 8;
        if (a.size == 1) { /* 64 bit extended size */
            a.size = avio_rb64(pb) - 8;
            total_size += 8;
        }
        if (a.size == 0) {
            a.size = atom.size - total_size;
            if (a.size <= 8)
                break;
        }
        a.size -= 8;
        if(a.size < 0)
            break;
        a.size = FFMIN(a.size, atom.size - total_size);

        for (i = 0; mov_default_parse_table[i].type; i++)
            if (mov_default_parse_table[i].type == a.type) {
                parse = mov_default_parse_table[i].parse;
                break;
            }

        // container is user data
        if (!parse && (atom.type == MKTAG('u','d','t','a') ||
                       atom.type == MKTAG('i','l','s','t')))
            parse = mov_read_udta_string;

    
    if (a.type == MKTAG('m', 'o', 'o', 'f') && !c->found_mfra){
        int64_t curPos = avio_tell(pb); //this is where we'll continue if we don't find the mfra
        uint32_t mfra_offset;
        MOVAtom mfraAtom;
        
	LOGE("will check for mfra, otherwise will return at %lld\n", curPos);
	
        if (avio_seek(pb, avio_size(pb) - 4, SEEK_SET) < 0){
           LOGE("could not seek to the end - 4\n");
        }
        LOGI("we are now at position %llu\n", avio_tell(pb));
        mfra_offset = avio_rb32(pb);
        LOGI("will look for mfra at %u from end\n", mfra_offset);
        avio_seek(pb, avio_size(pb) - mfra_offset, SEEK_SET);
        mfraAtom.size = avio_rb32(pb);
        mfraAtom.type = avio_rl32(pb);
        if (mfraAtom.size == 1){
           mfraAtom.size = avio_rb64(pb) - 8;
        }
        mfraAtom.size -= 8;
        LOGI("if it is mfra, it would be of size : %lld\n", mfraAtom.size + 8);
        if (mfraAtom.type == MKTAG('m', 'f', 'r', 'a')){
           LOGI("found mfra tag, will parse\n");
           mov_read_default(c, pb, mfraAtom);
           if (c->found_mfra == 1){
          c->seekmode = 1;
          LOGI("found valid mfra !!\n");
          return 0;
           }
        }else{
           c->found_mfra = -1;
        }
        avio_seek(pb, curPos, SEEK_SET); //finding mfra failed, resume parsing were we stopped
        LOGE("No mfra or not valid, will need parsing of all fragments\n");
        }
        if (!parse) { /* skip leaf atoms data */
//      LOGI("default : not handle, will skip\n");
            avio_skip(pb, a.size);
        } else {
            int64_t start_pos = avio_tell(pb);
            int64_t left;
//      LOGI("default : will parse\n");
            int err = parse(c, pb, a);
            if (err < 0)
                return err;
            if (c->found_moov && c->found_mdat &&
                (!pb->seekable || start_pos + a.size == avio_size(pb)))
                return 0;
            left = a.size - avio_tell(pb) + start_pos;
            if (left > 0) /* skip garbage at atom end */
                avio_skip(pb, left);
        }

        total_size += a.size;
    }

    if (total_size < atom.size && atom.size < 0x7ffff){
//        LOGI("default : skip end\n");
        avio_skip(pb, atom.size - total_size);
    }

    return 0;
}

static int mov_read_one(MOVContext *c, AVIOContext *pb)
{
   int64_t total_size = 0;
   MOVAtom a;
   int i;
   int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
   a.size = avio_rb32(pb);
   a.type = avio_rl32(pb);

   if (a.size == 1) { /* 64 bit extended size */
      a.size = avio_rb64(pb) - 8;
      total_size += 8;
   }
   a.size -= 8;
   if(a.size < 0)
      return -1;
   a.size = FFMIN(a.size, avio_size(pb));

   for (i = 0; mov_default_parse_table[i].type; i++)
      if (mov_default_parse_table[i].type == a.type) {
     parse = mov_default_parse_table[i].parse;
     break;
      }

      // container is user data


      if (!parse) { /* skip leaf atoms data */
     //avio_skip(pb, a.size);
      } else {
     int64_t start_pos = avio_tell(pb);
     int64_t left;
     int err = parse(c, pb, a);
     if (err < 0)
        return err;
     if (c->found_moov && c->found_mdat &&
        (!pb->seekable || start_pos + a.size == avio_size(pb)))
        return 0;
     left = a.size - avio_tell(pb) + start_pos;
//   if (left > 0) /* skip garbage at atom end */
//      avio_skip(pb, left);
      }
//       LOGI("end of read one\n");
   return 0;
}

static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    int entries, i, j;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    avio_rb32(pb); // version + flags
    entries = avio_rb32(pb);
    if (entries >= UINT_MAX / sizeof(*sc->drefs))
        return -1;
    sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
    if (!sc->drefs)
        return AVERROR(ENOMEM);
    sc->drefs_count = entries;

    for (i = 0; i < sc->drefs_count; i++) {
        MOVDref *dref = &sc->drefs[i];
        uint32_t size = avio_rb32(pb);
        int64_t next = avio_tell(pb) + size - 4;

        if (size < 12)
            return -1;

        dref->type = avio_rl32(pb);
        avio_rb32(pb); // version + flags
        av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);

        if (dref->type == MKTAG('a','l','i','s') && size > 150) {
            /* macintosh alias record */
            uint16_t volume_len, len;
            int16_t type;

            avio_skip(pb, 10);

            volume_len = avio_r8(pb);
            volume_len = FFMIN(volume_len, 27);
            avio_read(pb, dref->volume, 27);
            dref->volume[volume_len] = 0;
            av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);

            avio_skip(pb, 12);

            len = avio_r8(pb);
            len = FFMIN(len, 63);
            avio_read(pb, dref->filename, 63);
            dref->filename[len] = 0;
            av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);

            avio_skip(pb, 16);

            /* read next level up_from_alias/down_to_target */
            dref->nlvl_from = avio_rb16(pb);
            dref->nlvl_to   = avio_rb16(pb);
            av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
                   dref->nlvl_from, dref->nlvl_to);

            avio_skip(pb, 16);

            for (type = 0; type != -1 && avio_tell(pb) < next; ) {
                type = avio_rb16(pb);
                len = avio_rb16(pb);
                av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
                if (len&1)
                    len += 1;
                if (type == 2) { // absolute path
                    av_free(dref->path);
                    dref->path = av_mallocz(len+1);
                    if (!dref->path)
                        return AVERROR(ENOMEM);
                    avio_read(pb, dref->path, len);
                    if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
                        len -= volume_len;
                        memmove(dref->path, dref->path+volume_len, len);
                        dref->path[len] = 0;
                    }
                    for (j = 0; j < len; j++)
                        if (dref->path[j] == ':')
                            dref->path[j] = '/';
                    av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
                } else if (type == 0) { // directory name
                    av_free(dref->dir);
                    dref->dir = av_malloc(len+1);
                    if (!dref->dir)
                        return AVERROR(ENOMEM);
                    avio_read(pb, dref->dir, len);
                    dref->dir[len] = 0;
                    for (j = 0; j < len; j++)
                        if (dref->dir[j] == ':')
                            dref->dir[j] = '/';
                    av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
                } else
                    avio_skip(pb, len);
            }
        }
        avio_seek(pb, next, SEEK_SET);
    }
    return 0;
}

static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    uint32_t type;
    uint32_t ctype;

    if (c->fc->nb_streams < 1) // meta before first trak
        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */

    /* component type */
    ctype = avio_rl32(pb);
    type = avio_rl32(pb); /* component subtype */

    av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
    av_dlog(c->fc, "stype= %.4s\n", (char*)&type);

    if     (type == MKTAG('v','i','d','e'))
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
    else if(type == MKTAG('s','o','u','n'))
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
    else if(type == MKTAG('m','1','a',' '))
        st->codec->codec_id = CODEC_ID_MP2;
    else if(type == MKTAG('s','u','b','p'))
        st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
    else if (type == MKTAG('t','e','x','t'))
       st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;

    avio_rb32(pb); /* component  manufacture */
    avio_rb32(pb); /* component flags */
    avio_rb32(pb); /* component flags mask */

    return 0;
}

int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    int tag, len;
    if (fc->nb_streams < 1)
        return 0;
    st = fc->streams[fc->nb_streams-1];
    LOGI("in esds\n");
    avio_rb32(pb); /* version + flags */
    len = ff_mp4_read_descr(fc, pb, &tag);
    if (tag == MP4ESDescrTag) {
        avio_rb16(pb); /* ID */
        avio_r8(pb); /* priority */
    } else{
        avio_rb16(pb); /* ID */
   }
    len = ff_mp4_read_descr(fc, pb, &tag);
    if (tag == MP4DecConfigDescrTag){
       LOGI("esds : will read decoder config\n");
        ff_mp4_read_dec_config_descr(fc, st, pb);
    }
    LOGI("in esds end\n");
    return 0;
}

static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    return ff_mov_read_esds(c->fc, pb, atom);
}

static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    int ac3info, acmod, lfeon, bsmod;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];

    ac3info = avio_rb24(pb);
    bsmod = (ac3info >> 14) & 0x7;
    acmod = (ac3info >> 11) & 0x7;
    lfeon = (ac3info >> 10) & 0x1;
    st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
    st->codec->audio_service_type = bsmod;
    if (st->codec->channels > 1 && bsmod == 0x7)
        st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;

    return 0;
}

static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    const int num = avio_rb32(pb);
    const int den = avio_rb32(pb);
    AVStream *st;
   LOGE("in read pasp : %d:%d", num, den);
    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];

    if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
        (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
        av_log(c->fc, AV_LOG_WARNING,
               "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
               st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
               num, den);
    } else if (den != 0) {
        st->sample_aspect_ratio.num = num;
        st->sample_aspect_ratio.den = den;
    }
    return 0;
}

/* this atom contains actual media data */
static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    if(atom.size == 0) /* wrong one (MP4) */
        return 0;
    c->found_mdat=1;
    return 0; /* now go for moov */
}

/* read major brand, minor version and compatible brands and store them as metadata */
static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    uint32_t minor_ver;
    int comp_brand_size;
    char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
    char* comp_brands_str;
    uint8_t type[5] = {0};

    avio_read(pb, type, 4);
    if (strcmp(type, "qt  "))
        c->isom = 1;
    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
    av_dict_set(&c->fc->metadata, "major_brand", type, 0);
    minor_ver = avio_rb32(pb); /* minor version */
    snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
    av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);

    comp_brand_size = atom.size - 8;
    if (comp_brand_size < 0)
        return -1;
    comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
    if (!comp_brands_str)
        return AVERROR(ENOMEM);
    avio_read(pb, comp_brands_str, comp_brand_size);
    comp_brands_str[comp_brand_size] = 0;
    av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
    av_freep(&comp_brands_str);

    return 0;
}

/* this atom should contain all header atoms */
static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    int err;
    if ((err = mov_read_default(c, pb, atom)) < 0)
        return err;
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
    /* so we don't parse the whole file if over a network */
    c->found_moov=1;
    return 0; /* now go for mdat */
}

static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom){
   //Here we are in a new fragment
//    if (atom.size != 0){
//       LOGI("in read moof from linear parsing\n");
//       //This means we are parsing the file completely, position fragment based on sequence number
//       MOVFragment *tmp = c->current_frag;
//       c->current_frag = av_mallocz(sizeof(MOVFragment));
//       if (tmp){
//   LOGI("adding new fragment\n");
//   tmp->next = c->current_frag; //we already had one fragment in the chain
//       }else{
//   LOGI("creating first fragment\n");
//   c->first_frag = c->current_frag; //this is the first fragment in the chain
//       }
//    }
    c->seekmode = 1;
    c->fragment.moof_offset = avio_tell(pb) - 8;
    c->fragment.moof_end = c->fragment.moof_offset + atom.size;
    //LOGI("moof offset %llx\n", c->fragment.moof_offset);
    return mov_read_default(c, pb, atom);
}

static int mov_read_mfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom){
   avio_rb32(pb); //version + flags
   c->fragment.seq_number = avio_rb32(pb);
//    LOGI("read mfhd, seq number %d", c->fragment.seq_number);
   return 0;
}

static void mov_metadata_creation_time(AVDictionary **metadata, time_t time){
    char buffer[32];
    if (time) {
        struct tm *ptm;
        time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
        ptm = gmtime(&time);
        if (!ptm) return;
        strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
        av_dict_set(metadata, "creation_time", buffer, 0);
    }
}

static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    int version;
    char language[4] = {0};
    unsigned lang;
    time_t creation_time;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    version = avio_r8(pb);
    if (version > 1)
        return -1; /* unsupported */

    avio_rb24(pb); /* flags */
    if (version == 1) {
        creation_time = avio_rb64(pb);
        avio_rb64(pb);
    } else {
        creation_time = avio_rb32(pb);
        avio_rb32(pb); /* modification time */
    }
    mov_metadata_creation_time(&st->metadata, creation_time);

    sc->time_scale = avio_rb32(pb);
    st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
    st->time_base.num = 1;
    st->time_base.den = sc->time_scale;
    st->codec->time_base = st->time_base;
    LOGE("in mdhd, setting duration for stream %llu, in s : %lf, timescale is %d", (uint64_t)st->duration, (((uint64_t)st->duration) / (double)sc->time_scale), sc->time_scale);
    
    lang = avio_rb16(pb); /* language */
    if (ff_mov_lang_to_iso639(lang, language))
        av_dict_set(&st->metadata, "language", language, 0);
    avio_rb16(pb); /* quality */

    return 0;
}

static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    time_t creation_time;
    int version = avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */

    if (version == 1) {
        creation_time = avio_rb64(pb);
        avio_rb64(pb);
    } else {
        creation_time = avio_rb32(pb);
        avio_rb32(pb); /* modification time */
    }
    mov_metadata_creation_time(&c->fc->metadata, creation_time);
    c->time_scale = avio_rb32(pb); /* time scale */

    av_dlog(c->fc, "time scale = %i\n", c->time_scale);

    c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
    avio_rb32(pb); /* preferred scale */

    avio_rb16(pb); /* preferred volume */

    avio_skip(pb, 10); /* reserved */

    avio_skip(pb, 36); /* display matrix */

    avio_rb32(pb); /* preview time */
    avio_rb32(pb); /* preview duration */
    avio_rb32(pb); /* poster time */
    avio_rb32(pb); /* selection time */
    avio_rb32(pb); /* selection duration */
    avio_rb32(pb); /* current time */
    avio_rb32(pb); /* next track ID */

    return 0;
}

static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];

    if((uint64_t)atom.size > (1<<30))
        return -1;

    // currently SVQ3 decoder expect full STSD header - so let's fake it
    // this should be fixed and just SMI header should be passed
    av_free(st->codec->extradata);
    st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
    if (!st->codec->extradata)
        return AVERROR(ENOMEM);
    st->codec->extradata_size = 0x5a + atom.size;
    memcpy(st->codec->extradata, "SVQ3", 4); // fake
    avio_read(pb, st->codec->extradata + 0x5a, atom.size);
    av_dlog(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
    return 0;
}

static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    int little_endian;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];

    little_endian = avio_rb16(pb);
    av_dlog(c->fc, "enda %d\n", little_endian);
    if (little_endian == 1) {
        switch (st->codec->codec_id) {
        case CODEC_ID_PCM_S24BE:
            st->codec->codec_id = CODEC_ID_PCM_S24LE;
            break;
        case CODEC_ID_PCM_S32BE:
            st->codec->codec_id = CODEC_ID_PCM_S32LE;
            break;
        case CODEC_ID_PCM_F32BE:
            st->codec->codec_id = CODEC_ID_PCM_F32LE;
            break;
        case CODEC_ID_PCM_F64BE:
            st->codec->codec_id = CODEC_ID_PCM_F64LE;
            break;
        default:
            break;
        }
    }
    return 0;
}

/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    uint64_t size;
    uint8_t *buf;

    if (c->fc->nb_streams < 1) // will happen with jp2 files
        return 0;
    st= c->fc->streams[c->fc->nb_streams-1];
    size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
    if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
        return -1;
    buf= av_realloc(st->codec->extradata, size);
    if(!buf)
        return -1;
    st->codec->extradata= buf;
    buf+= st->codec->extradata_size;
    st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
    AV_WB32(       buf    , atom.size + 8);
    AV_WL32(       buf + 4, atom.type);
    avio_read(pb, buf + 8, atom.size);
    return 0;
}

static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];

    if((uint64_t)atom.size > (1<<30))
        return -1;

    if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
        // pass all frma atom to codec, needed at least for QDMC and QDM2
        av_free(st->codec->extradata);
        st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
        if (!st->codec->extradata)
            return AVERROR(ENOMEM);
        st->codec->extradata_size = atom.size;
        avio_read(pb, st->codec->extradata, atom.size);
    } else if (atom.size > 8) { /* to read frma, esds atoms */
        if (mov_read_default(c, pb, atom) < 0)
            return -1;
    } else
        avio_skip(pb, atom.size);
    return 0;
}

/**
 * This function reads atom content and puts data in extradata without tag
 * nor size unlike mov_read_extradata.
 */
static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];

    if((uint64_t)atom.size > (1<<30))
        return -1;
    
    av_free(st->codec->extradata);
    st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
    if (!st->codec->extradata)
        return AVERROR(ENOMEM);
    st->codec->extradata_size = atom.size;
    LOGE("reading extrada for stream %d of size %lld", c->fc->nb_streams -1, atom.size);
    avio_read(pb, st->codec->extradata, atom.size);
    return 0;
}

/**
 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
 * but can have extradata appended at the end after the 40 bytes belonging
 * to the struct.
 */
static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;

    if (c->fc->nb_streams < 1)
        return 0;
    if (atom.size <= 40)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];

    if((uint64_t)atom.size > (1<<30))
        return -1;

    av_free(st->codec->extradata);
    st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
    if (!st->codec->extradata)
        return AVERROR(ENOMEM);
    st->codec->extradata_size = atom.size - 40;
    avio_skip(pb, 40);
    avio_read(pb, st->codec->extradata, atom.size - 40);
    return 0;
}

static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    unsigned int i, entries;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */

    entries = avio_rb32(pb);

    if(entries >= UINT_MAX/sizeof(int64_t))
        return -1;

    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
    if (!sc->chunk_offsets)
        return AVERROR(ENOMEM);
    sc->chunk_count = entries;

    if      (atom.type == MKTAG('s','t','c','o'))
        for(i=0; i<entries; i++)
            sc->chunk_offsets[i] = avio_rb32(pb);
    else if (atom.type == MKTAG('c','o','6','4'))
        for(i=0; i<entries; i++)
            sc->chunk_offsets[i] = avio_rb64(pb);
    else
        return -1;

    return 0;
}

/**
 * Compute codec id for 'lpcm' tag.
 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
 */
enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
{
    if (flags & 1) { // floating point
        if (flags & 2) { // big endian
            if      (bps == 32) return CODEC_ID_PCM_F32BE;
            else if (bps == 64) return CODEC_ID_PCM_F64BE;
        } else {
            if      (bps == 32) return CODEC_ID_PCM_F32LE;
            else if (bps == 64) return CODEC_ID_PCM_F64LE;
        }
    } else {
        if (flags & 2) {
            if      (bps == 8)
                // signed integer
                if (flags & 4)  return CODEC_ID_PCM_S8;
                else            return CODEC_ID_PCM_U8;
            else if (bps == 16) return CODEC_ID_PCM_S16BE;
            else if (bps == 24) return CODEC_ID_PCM_S24BE;
            else if (bps == 32) return CODEC_ID_PCM_S32BE;
        } else {
            if      (bps == 8)
                if (flags & 4)  return CODEC_ID_PCM_S8;
                else            return CODEC_ID_PCM_U8;
            else if (bps == 16) return CODEC_ID_PCM_S16LE;
            else if (bps == 24) return CODEC_ID_PCM_S24LE;
            else if (bps == 32) return CODEC_ID_PCM_S32LE;
        }
    }
    return CODEC_ID_NONE;
}

int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
{
    AVStream *st;
    MOVStreamContext *sc;
    int j, pseudo_stream_id;
    int color_table_id;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;
   LOGI("in stsd_entries : %d\n", entries);
    for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
        //Parsing Sample description table
        enum AVCodecID id;
        int dref_id = 1;
        MOVAtom a = { AV_RL32("stsd") };
        int64_t start_pos = avio_tell(pb);
        int size = avio_rb32(pb); /* size */
        uint32_t format = avio_rl32(pb); /* data format */
//  LOGI("in stsd_entries begin of for\n");

        if (size >= 16) {
            avio_rb32(pb); /* reserved */
            avio_rb16(pb); /* reserved */
            dref_id = avio_rb16(pb);
        }
        
//         LOGI("in stsd_entries 1\n");
        if (st->codec->codec_tag &&
            st->codec->codec_tag != format &&
            (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
                                   : st->codec->codec_tag != MKTAG('j','p','e','g'))
           ){
            /* Multiple fourcc, we skip JPEG. This is not correct, we should
             * export it as a separate AVStream but this needs a few changes
             * in the MOV demuxer, patch welcome. */
        multiple_stsd:
        LOGE("multiple fourcc not supported\n");
            av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
            avio_skip(pb, size - (avio_tell(pb) - start_pos));
            continue;
        }
        /* we cannot demux concatenated h264 streams because of different extradata */
        if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
            goto multiple_stsd;
        sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
        sc->dref_id= dref_id;

        st->codec->codec_tag = format;
//  LOGI("in stsd_entries 2\n");
        id = ff_codec_get_id(ff_codec_movaudio_tags, format);
//  LOGI("in stsd_entries 3\n");
        if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
            id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
//  LOGI("in stsd_entries 4\n");
        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
           LOGI("stsd : found audio codec\n");
            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
        } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
                   format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
              LOGI("stsd : looking for video codec\n");
            id = ff_codec_get_id(ff_codec_movvideo_tags, format);
            if (id <= 0)
                id = ff_codec_get_id(ff_codec_bmp_tags, format);
            if (id > 0){
                st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
                LOGI("stsd : found video codec\n");
            }
            else if(st->codec->codec_type == AVMEDIA_TYPE_DATA || st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE){
                id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
                if(id > 0){
                   LOGI("stsd : found subtitle codec\n");
                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
                }
            }
        }

        av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
                (format >> 24) & 0xff, st->codec->codec_type);

        if(st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
            unsigned int color_depth, len;
            int color_greyscale;
        LOGI("stsd : reading video codec infos\n");
            st->codec->codec_id = id;
            avio_rb16(pb); /* version */
            avio_rb16(pb); /* revision level */
            avio_rb32(pb); /* vendor */
            avio_rb32(pb); /* temporal quality */
            avio_rb32(pb); /* spatial quality */

            st->codec->width = avio_rb16(pb); /* width */
            st->codec->height = avio_rb16(pb); /* height */
            LOGI("stsd : reading video codec infos, video size is %dx%d\n", st->codec->width, st->codec->height);
            avio_rb32(pb); /* horiz resolution */
            avio_rb32(pb); /* vert resolution */
            avio_rb32(pb); /* data size, always 0 */
            avio_rb16(pb); /* frames per samples */
//      LOGI("in stsd_entries 7\n");
            len = avio_r8(pb); /* codec name, pascal string */
            if (len > 31)
                len = 31;
            mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
            if (len < 31)
                avio_skip(pb, 31 - len);
            /* codec_tag YV12 triggers an UV swap in rawdec.c */
            if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
                st->codec->codec_tag=MKTAG('I', '4', '2', '0');
//      LOGI("in stsd_entries 8\n");
            st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
            color_table_id = avio_rb16(pb); /* colortable id */
    av_dlog(c->fc, "depth %d, ctab id %d\n",
            st->codec->bits_per_coded_sample, color_table_id);
    /* figure out the palette situation */
    color_depth     = st->codec->bits_per_coded_sample & 0x1F;
    color_greyscale = st->codec->bits_per_coded_sample & 0x20;

    /* if the depth is 2, 4, or 8 bpp, file is palettized */
    if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
        /* for palette traversal */
        unsigned int color_start, color_count, color_end;
        unsigned char a, r, g, b;

        if (color_greyscale) {
            int color_index, color_dec;
            /* compute the greyscale palette */
            st->codec->bits_per_coded_sample = color_depth;
            color_count = 1 << color_depth;
            color_index = 255;
            color_dec   = 256 / (color_count - 1);
            for (j = 0; j < color_count; j++) {
                if (st->codec->codec_id == AV_CODEC_ID_CINEPAK){
                    r = g = b = color_count - 1 - color_index;
                } else
                r = g = b = color_index;
                sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
                color_index -= color_dec;
                if (color_index < 0)
                    color_index = 0;
            }
        } else if (color_table_id) {
            const uint8_t *color_table;
            /* if flag bit 3 is set, use the default palette */
            color_count = 1 << color_depth;
            if (color_depth == 2)
                color_table = ff_qt_default_palette_4;
            else if (color_depth == 4)
                color_table = ff_qt_default_palette_16;
            else
                color_table = ff_qt_default_palette_256;

            for (j = 0; j < color_count; j++) {
                r = color_table[j * 3 + 0];
                g = color_table[j * 3 + 1];
                b = color_table[j * 3 + 2];
                sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
            }
        } else {
            /* load the palette from the file */
            color_start = avio_rb32(pb);
            color_count = avio_rb16(pb);
            color_end   = avio_rb16(pb);
            if ((color_start <= 255) && (color_end <= 255)) {
                for (j = color_start; j <= color_end; j++) {
                    /* each A, R, G, or B component is 16 bits;
                        * only use the top 8 bits */
                    a = avio_r8(pb);
                    avio_r8(pb);
                    r = avio_r8(pb);
                    avio_r8(pb);
                    g = avio_r8(pb);
                    avio_r8(pb);
                    b = avio_r8(pb);
                    avio_r8(pb);
                    sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
                }
            }
        }
        sc->has_palette = 1;
    }
//             LOGI("in stsd_entries 10\n");
        } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
            int bits_per_sample, flags;
            uint16_t version = avio_rb16(pb);
        LOGI("reading audio codec infos\n");
            st->codec->codec_id = id;
            avio_rb16(pb); /* revision level */
            avio_rb32(pb); /* vendor */

            st->codec->channels = avio_rb16(pb);             /* channel count */
            av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
            st->codec->bits_per_coded_sample = avio_rb16(pb);      /* sample size */

            sc->audio_cid = avio_rb16(pb);
            avio_rb16(pb); /* packet size = 0 */
//      LOGI("in stsd_entries 12");
            st->codec->sample_rate = ((avio_rb32(pb) >> 16));

            //Read QT version 1 fields. In version 0 these do not exist.
            av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
            if(!c->isom) {
               LOGI("stsd: reading not isom infos\n");
                if(version==1) {
                    sc->samples_per_frame = avio_rb32(pb);
                    avio_rb32(pb); /* bytes per packet */
                    sc->bytes_per_frame = avio_rb32(pb);
                    avio_rb32(pb); /* bytes per sample */
                } else if(version==2) {
                    avio_rb32(pb); /* sizeof struct only */
                    st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
                    st->codec->channels = avio_rb32(pb);
                    avio_rb32(pb); /* always 0x7F000000 */
                    st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
                    flags = avio_rb32(pb); /* lpcm format specific flag */
                    sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
                    sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
                    if (format == MKTAG('l','p','c','m'))
                        st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
                }
            }
//             LOGI("in stsd_entries 13");
            switch (st->codec->codec_id) {
            case AV_CODEC_ID_PCM_S8:
            case AV_CODEC_ID_PCM_U8:
                if (st->codec->bits_per_coded_sample == 16)
                    st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
                break;
            case AV_CODEC_ID_PCM_S16LE:
            case AV_CODEC_ID_PCM_S16BE:
                if (st->codec->bits_per_coded_sample == 8)
                    st->codec->codec_id = AV_CODEC_ID_PCM_S8;
                else if (st->codec->bits_per_coded_sample == 24)
                    st->codec->codec_id =
                        st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
                        AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
                break;
            /* set values for old format before stsd version 1 appeared */
            case AV_CODEC_ID_MACE3:
                sc->samples_per_frame = 6;
                sc->bytes_per_frame = 2*st->codec->channels;
                break;
            case AV_CODEC_ID_MACE6:
                sc->samples_per_frame = 6;
                sc->bytes_per_frame = 1*st->codec->channels;
                break;
            case AV_CODEC_ID_ADPCM_IMA_QT:
                sc->samples_per_frame = 64;
                sc->bytes_per_frame = 34*st->codec->channels;
                break;
            case AV_CODEC_ID_GSM:
                sc->samples_per_frame = 160;
                sc->bytes_per_frame = 33;
                break;
                break;
            default:
                break;
            }

            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
            if (bits_per_sample) {
                st->codec->bits_per_coded_sample = bits_per_sample;
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
            }
//             LOGI("in stsd_entries 14");
        } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
            // ttxt stsd contains display flags, justification, background
            // color, fonts, and default styles, so fake an atom to read it
            MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
                mov_read_glbl(c, pb, fake_atom);
            st->codec->codec_id= id;
            st->codec->width = sc->width;
            st->codec->height = sc->height;
        } else {
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
            avio_skip(pb, size - (avio_tell(pb) - start_pos));
        }
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
        a.size = size - (avio_tell(pb) - start_pos);
//  LOGI("in stsd_entries 14.1 : %llu", a.size);
        if (a.size > 8) {
       LOGI("in stsd, reading remaining infos : %llu\n", a.size);
            if (mov_read_default(c, pb, a) < 0)
                return -1;
        } else if (a.size > 0){
//     LOGI("in stsd_entries 14.12 : %llu", a.size);
            avio_skip(pb, a.size);
    }
//  LOGI("in stsd_entries 14.2");
    }
//     LOGI("in stsd_entries 15");
    if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
        st->codec->sample_rate= sc->time_scale;

    /* special codec parameters handling */
    switch (st->codec->codec_id) {
#if CONFIG_DV_DEMUXER
    case CODEC_ID_DVAUDIO:
        c->dv_fctx = avformat_alloc_context();
        c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
        if (!c->dv_demux) {
            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
            return -1;
        }
        sc->dv_audio_container = 1;
        st->codec->codec_id = CODEC_ID_PCM_S16LE;
        break;
#endif
    /* no ifdef since parameters are always those */
    case CODEC_ID_QCELP:
        // force sample rate for qcelp when not stored in mov
        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
            st->codec->sample_rate = 8000;
        st->codec->frame_size= 160;
        st->codec->channels= 1; /* really needed */
        break;
    case CODEC_ID_AMR_NB:
    case CODEC_ID_AMR_WB:
        st->codec->frame_size= sc->samples_per_frame;
        st->codec->channels= 1; /* really needed */
        /* force sample rate for amr, stsd in 3gp does not store sample rate */
        if (st->codec->codec_id == CODEC_ID_AMR_NB)
            st->codec->sample_rate = 8000;
        else if (st->codec->codec_id == CODEC_ID_AMR_WB)
            st->codec->sample_rate = 16000;
        break;
    case CODEC_ID_MP2:
    case CODEC_ID_MP3:
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
        st->need_parsing = AVSTREAM_PARSE_FULL;
        break;
    case CODEC_ID_GSM:
    case CODEC_ID_ADPCM_MS:
    case CODEC_ID_ADPCM_IMA_WAV:
        st->codec->frame_size = sc->samples_per_frame;
        st->codec->block_align = sc->bytes_per_frame;
        break;
    case CODEC_ID_ALAC:
        if (st->codec->extradata_size == 36) {
            st->codec->frame_size = AV_RB32(st->codec->extradata+12);
            st->codec->channels   = AV_RB8 (st->codec->extradata+21);
            st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
        }
        break;
    default:
        break;
    }
//     LOGI("end of stsd_entries");
    return 0;
}

static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    int entries;

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */
    entries = avio_rb32(pb);
//    LOGI("read_stsd");
    return ff_mov_read_stsd_entries(c, pb, entries);
}

static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    unsigned int i, entries;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */

    entries = avio_rb32(pb);

    av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);

    if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
        return -1;
    sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
    if (!sc->stsc_data)
        return AVERROR(ENOMEM);
    sc->stsc_count = entries;

    for(i=0; i<entries; i++) {
        sc->stsc_data[i].first = avio_rb32(pb);
        sc->stsc_data[i].count = avio_rb32(pb);
        sc->stsc_data[i].id = avio_rb32(pb);
    }
    return 0;
}

static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    unsigned i, entries;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    avio_rb32(pb); // version + flags

    entries = avio_rb32(pb);
    if (entries >= UINT_MAX / sizeof(*sc->stps_data))
        return -1;
    sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
    if (!sc->stps_data)
        return AVERROR(ENOMEM);
    sc->stps_count = entries;

    for (i = 0; i < entries; i++) {
        sc->stps_data[i] = avio_rb32(pb);
        //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
    }

    return 0;
}

static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    unsigned int i, entries;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */

    entries = avio_rb32(pb);

    av_dlog(c->fc, "keyframe_count = %d\n", entries);

    if(entries >= UINT_MAX / sizeof(int))
        return -1;
    sc->keyframes = av_malloc(entries * sizeof(int));
    if (!sc->keyframes)
        return AVERROR(ENOMEM);
    sc->keyframe_count = entries;

    for(i=0; i<entries; i++) {
        sc->keyframes[i] = avio_rb32(pb);
        //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
    }
    return 0;
}

static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    unsigned int i, entries, sample_size, field_size, num_bytes;
    GetBitContext gb;
    unsigned char* buf;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */

    if (atom.type == MKTAG('s','t','s','z')) {
        sample_size = avio_rb32(pb);
        if (!sc->sample_size) /* do not overwrite value computed in stsd */
            sc->sample_size = sample_size;
        field_size = 32;
    } else {
        sample_size = 0;
        avio_rb24(pb); /* reserved */
        field_size = avio_r8(pb);
    }
    entries = avio_rb32(pb);

    av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);

    sc->sample_count = entries;
    if (sample_size)
        return 0;

    if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
        av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
        return -1;
    }

    if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
        return -1;
    sc->sample_sizes = av_malloc(entries * sizeof(int));
    if (!sc->sample_sizes)
        return AVERROR(ENOMEM);

    num_bytes = (entries*field_size+4)>>3;

    buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
    if (!buf) {
        av_freep(&sc->sample_sizes);
        return AVERROR(ENOMEM);
    }

    if (avio_read(pb, buf, num_bytes) < num_bytes) {
        av_freep(&sc->sample_sizes);
        av_free(buf);
        return -1;
    }

    init_get_bits(&gb, buf, 8*num_bytes);

    for(i=0; i<entries; i++)
        sc->sample_sizes[i] = get_bits_long(&gb, field_size);

    av_free(buf);
    return 0;
}

static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    unsigned int i, entries;
    int64_t duration=0;
    int64_t total_sample_count=0;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */
    entries = avio_rb32(pb);

    av_dlog(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);

    if(entries >= UINT_MAX / sizeof(*sc->stts_data))
        return -1;
    sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
    if (!sc->stts_data)
        return AVERROR(ENOMEM);
    sc->stts_count = entries;

    for(i=0; i<entries; i++) {
        int sample_duration;
        int sample_count;

        sample_count=avio_rb32(pb);
        sample_duration = avio_rb32(pb);
        sc->stts_data[i].count= sample_count;
        sc->stts_data[i].duration= sample_duration;

        av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);

        duration+=(int64_t)sample_duration*sample_count;
        total_sample_count+=sample_count;
    }

    st->nb_frames= total_sample_count;
    if(duration){
        st->duration= duration;
    sc->stts_duration = duration;
        LOGE("in stts, setting duration for stream : %"PRIx64"", st->duration);
    }
    return 0;
}

static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    unsigned int i, entries;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */
    entries = avio_rb32(pb);

    av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);

    if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
        return -1;
    sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
    if (!sc->ctts_data)
        return AVERROR(ENOMEM);
    sc->ctts_count = entries;

    for(i=0; i<entries; i++) {
        int count    =avio_rb32(pb);
        int duration =avio_rb32(pb);

        sc->ctts_data[i].count   = count;
        sc->ctts_data[i].duration= duration;
        if (duration < 0 && i+1<entries)
            sc->dts_shift = FFMAX(sc->dts_shift, -duration);
    }

    av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);

    return 0;
}

static void mov_build_index(MOVContext *mov, AVStream *st)
{
    MOVStreamContext *sc = st->priv_data;
    int64_t current_offset;
    int64_t current_dts = 0;
    unsigned int stts_index = 0;
    unsigned int stsc_index = 0;
    unsigned int stss_index = 0;
    unsigned int stps_index = 0;
    unsigned int i, j;
    uint64_t stream_size = 0;

    /* adjust first dts according to edit list */
    if (sc->time_offset && mov->time_scale > 0) {
        int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
        current_dts = -rescaled;
        if (sc->ctts_data && sc->stts_data &&
            sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
            /* more than 16 frames delay, dts are likely wrong
               this happens with files created by iMovie */
            sc->wrong_dts = 1;
            st->codec->has_b_frames = 1;
        }
    }

    /* only use old uncompressed audio chunk demuxing when stts specifies it */
    if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
          sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
        unsigned int current_sample = 0;
        unsigned int stts_sample = 0;
        unsigned int sample_size;
        unsigned int distance = 0;
        int key_off = sc->keyframes && sc->keyframes[0] == 1;

        current_dts -= sc->dts_shift;

        if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
            return;
        st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
        if (!st->index_entries)
            return;
        st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);

        for (i = 0; i < sc->chunk_count; i++) {
            current_offset = sc->chunk_offsets[i];
            while (stsc_index + 1 < sc->stsc_count &&
                i + 1 == sc->stsc_data[stsc_index + 1].first)
                stsc_index++;
            for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
                int keyframe = 0;
                if (current_sample >= sc->sample_count) {
                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
                    return;
                }

                if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
                    keyframe = 1;
                    if (stss_index + 1 < sc->keyframe_count)
                        stss_index++;
                } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
                    keyframe = 1;
                    if (stps_index + 1 < sc->stps_count)
                        stps_index++;
                }
                if (keyframe)
                    distance = 0;
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
                if(sc->pseudo_stream_id == -1 ||
                   sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
                    AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
                    e->pos = current_offset;
                    e->timestamp = current_dts;
                    e->size = sample_size;
                    e->min_distance = distance;
                    e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
                    av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
                            "size %d, distance %d, keyframe %d\n", st->index, current_sample,
                            current_offset, current_dts, sample_size, distance, keyframe);
                }

                current_offset += sample_size;
                stream_size += sample_size;
                current_dts += sc->stts_data[stts_index].duration;
                distance++;
                stts_sample++;
                current_sample++;
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
                    stts_sample = 0;
                    stts_index++;
                }
            }
        }
        if (st->duration > 0)
            st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
    } else {
        unsigned chunk_samples, total = 0;

        // compute total chunk count
        for (i = 0; i < sc->stsc_count; i++) {
            unsigned count, chunk_count;

            chunk_samples = sc->stsc_data[i].count;
            if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
                av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
                return;
            }

            if (sc->samples_per_frame >= 160) { // gsm
                count = chunk_samples / sc->samples_per_frame;
            } else if (sc->samples_per_frame > 1) {
                unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
                count = (chunk_samples+samples-1) / samples;
            } else {
                count = (chunk_samples+1023) / 1024;
            }

            if (i < sc->stsc_count - 1)
                chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
            else
                chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
            total += chunk_count * count;
        }

        av_dlog(mov->fc, "chunk count %d\n", total);
        if (total >= UINT_MAX / sizeof(*st->index_entries))
            return;
        st->index_entries = av_malloc(total*sizeof(*st->index_entries));
        if (!st->index_entries)
            return;
        st->index_entries_allocated_size = total*sizeof(*st->index_entries);

        // populate index
        for (i = 0; i < sc->chunk_count; i++) {
            current_offset = sc->chunk_offsets[i];
            if (stsc_index + 1 < sc->stsc_count &&
                i + 1 == sc->stsc_data[stsc_index + 1].first)
                stsc_index++;
            chunk_samples = sc->stsc_data[stsc_index].count;

            while (chunk_samples > 0) {
                AVIndexEntry *e;
                unsigned size, samples;

                if (sc->samples_per_frame >= 160) { // gsm
                    samples = sc->samples_per_frame;
                    size = sc->bytes_per_frame;
                } else {
                    if (sc->samples_per_frame > 1) {
                        samples = FFMIN((1024 / sc->samples_per_frame)*
                                        sc->samples_per_frame, chunk_samples);
                        size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
                    } else {
                        samples = FFMIN(1024, chunk_samples);
                        size = samples * sc->sample_size;
                    }
                }

                if (st->nb_index_entries >= total) {
                    av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
                    return;
                }
                e = &st->index_entries[st->nb_index_entries++];
                e->pos = current_offset;
                e->timestamp = current_dts;
                e->size = size;
                e->min_distance = 0;
                e->flags = AVINDEX_KEYFRAME;
                av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
                        "size %d, duration %d\n", st->index, i, current_offset, current_dts,
                        size, samples);

                current_offset += size;
                current_dts += samples;
                chunk_samples -= samples;
            }
        }
    }
}

static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref)
{
    /* try relative path, we do not try the absolute because it can leak information about our
       system to an attacker */
    if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
        char filename[1024];
        char *src_path;
        int i, l;

        /* find a source dir */
        src_path = strrchr(src, '/');
        if (src_path)
            src_path++;
        else
            src_path = src;

        /* find a next level down to target */
        for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
            if (ref->path[l] == '/') {
                if (i == ref->nlvl_to - 1)
                    break;
                else
                    i++;
            }

        /* compose filename if next level down to target was found */
        if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
            memcpy(filename, src, src_path - src);
            filename[src_path - src] = 0;

            for (i = 1; i < ref->nlvl_from; i++)
                av_strlcat(filename, "../", 1024);

            av_strlcat(filename, ref->path + l + 1, 1024);

            if (!avio_open(pb, filename, AVIO_FLAG_READ))
                return 0;
        }
    }

    return AVERROR(ENOENT);
}

static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    AVStream *st;
    MOVStreamContext *sc;
    int ret;

    st = avformat_new_stream(c->fc, NULL);
    if (!st) return AVERROR(ENOMEM);
    sc = av_mallocz(sizeof(MOVStreamContext));
    if (!sc) return AVERROR(ENOMEM);

    st->priv_data = sc;
    st->codec->codec_type = AVMEDIA_TYPE_DATA;
    sc->ffindex = st->index;

    if ((ret = mov_read_default(c, pb, atom)) < 0)
        return ret;

    /* sanity checks */
    if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
                            (!sc->sample_size && !sc->sample_count))) {
        av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
               st->index);
        return 0;
    }

    if (sc->time_scale <= 0) {
        av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
        sc->time_scale = c->time_scale;
        if (sc->time_scale <= 0)
            sc->time_scale = 1;
    }

    avpriv_set_pts_info(st, 64, 1, sc->time_scale);

    if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
        !st->codec->frame_size && sc->stts_count == 1) {
        st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
                                           st->codec->sample_rate, sc->time_scale);
        av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
    }

    mov_build_index(c, st);

    if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
        MOVDref *dref = &sc->drefs[sc->dref_id - 1];
        if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
            av_log(c->fc, AV_LOG_ERROR,
                   "stream %d, error opening alias: path='%s', dir='%s', "
                   "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
                   st->index, dref->path, dref->dir, dref->filename,
                   dref->volume, dref->nlvl_from, dref->nlvl_to);
    } else
        sc->pb = c->fc->pb;

    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
        if (!st->sample_aspect_ratio.num &&
            (st->codec->width != sc->width || st->codec->height != sc->height)) {
            st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
                                             ((double)st->codec->width * sc->height), INT_MAX);
        }

        av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
                  sc->time_scale*st->nb_frames, st->duration, INT_MAX);

        if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
                      sc->time_scale, sc->stts_data[0].duration, INT_MAX);
    }

    switch (st->codec->codec_id) {
#if CONFIG_H261_DECODER
    case CODEC_ID_H261:
#endif
#if CONFIG_H263_DECODER
    case CODEC_ID_H263:
#endif
#if CONFIG_H264_DECODER
    case CODEC_ID_H264:
#endif
#if CONFIG_MPEG4_DECODER
    case CODEC_ID_MPEG4:
#endif
        //st->codec->width = 0; /* let decoder init width/height */
        //st->codec->height= 0;
        //LOGI("let decoder init width/height");
        break;
    }

    /* Do not need those anymore. */
    av_freep(&sc->chunk_offsets);
    av_freep(&sc->stsc_data);
    av_freep(&sc->sample_sizes);
    av_freep(&sc->keyframes);
    av_freep(&sc->stts_data);
    av_freep(&sc->stps_data);

    return 0;
}

static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    int ret;
    c->itunes_metadata = 1;
    ret = mov_read_default(c, pb, atom);
    c->itunes_metadata = 0;
    return ret;
}

static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    while (atom.size > 8) {
        uint32_t tag = avio_rl32(pb);
        atom.size -= 4;
        if (tag == MKTAG('h','d','l','r')) {
            avio_seek(pb, -8, SEEK_CUR);
            atom.size += 8;
            return mov_read_default(c, pb, atom);
        }
    }
    return 0;
}

static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    int i;
    int width;
    int height;
    int64_t disp_transform[2];
    int display_matrix[3][2];
    AVStream *st;
    MOVStreamContext *sc;
    int version;

    if (c->fc->nb_streams < 1)
        return 0;
    st = c->fc->streams[c->fc->nb_streams-1];
    sc = st->priv_data;

    version = avio_r8(pb);
    avio_rb24(pb); /* flags */
    /*
    MOV_TRACK_ENABLED 0x0001
    MOV_TRACK_IN_MOVIE 0x0002
    MOV_TRACK_IN_PREVIEW 0x0004
    MOV_TRACK_IN_POSTER 0x0008
    */

    if (version == 1) {
        avio_rb64(pb);
        avio_rb64(pb);
    } else {
        avio_rb32(pb); /* creation time */
        avio_rb32(pb); /* modification time */
    }
    st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
    avio_rb32(pb); /* reserved */

    /* highlevel (considering edits) duration in movie timebase */
    (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
    avio_rb32(pb); /* reserved */
    avio_rb32(pb); /* reserved */

    avio_rb16(pb); /* layer */
    avio_rb16(pb); /* alternate group */
    avio_rb16(pb); /* volume */
    avio_rb16(pb); /* reserved */

    //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
    // they're kept in fixed point format through all calculations
    // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
    for (i = 0; i < 3; i++) {
        display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
        display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
        avio_rb32(pb);           // 2.30 fixed point (not used)
    }

    width = avio_rb32(pb);       // 16.16 fixed point track width
    height = avio_rb32(pb);      // 16.16 fixed point track height
    sc->width = width >> 16;
    sc->height = height >> 16;
    LOGE("display with is %dx%d", sc->width, sc->height);
    // transform the display width/height according to the matrix
    // skip this if the display matrix is the default identity matrix
    // or if it is rotating the picture, ex iPhone 3GS
    // to keep the same scale, use [width height 1<<16]
    if (width && height &&
        ((display_matrix[0][0] != 65536  ||
          display_matrix[1][1] != 65536) &&
         !display_matrix[0][1] &&
         !display_matrix[1][0] &&
         !display_matrix[2][0] && !display_matrix[2][1])) {
        for (i = 0; i < 2; i++)
            disp_transform[i] =
                (int64_t)  width  * display_matrix[0][i] +
                (int64_t)  height * display_matrix[1][i] +
                ((int64_t) display_matrix[2][i] << 16);
     LOGE("special aspect ratio %lld, %lld\n", disp_transform[0], disp_transform[1]);
        //sample aspect ratio is new width/height divided by old width/height
        st->sample_aspect_ratio = av_d2q(
            ((double) disp_transform[0] * height) /
            ((double) disp_transform[1] * width), INT_MAX);
    }
//     LOGI("end of read_tkhd\n");
    return 0;
}

static MOVFragment* mov_get_fragment(MOVStreamContext *c, uint64_t offset){
   MOVFragment *tmp = c->first_frag;
   if (!tmp){ //we are the first
      //LOGE("get fragment : first in the list\n");
      tmp = av_mallocz(sizeof(MOVFragment));
      if (!tmp){
         return NULL;
      }
      c->first_frag = tmp;
      c->fragment_count++;
      return c->first_frag;
   }
   if (tmp->moof_offset > offset){// we are before everyone
      //LOGE("get fragment : before everyone else\n");
      c->first_frag = av_mallocz(sizeof(MOVFragment));
      if (!c->first_frag){
         return NULL;
      }
      c->first_frag->next = tmp;
      c->fragment_count++;
      return c->first_frag;
   }
   while (tmp->next && tmp->next->moof_offset <= offset){
      tmp = tmp->next;
   }
   if (tmp->moof_offset == offset){ //already exist, return existing
//       LOGE("using existing fragment with same offset\n");
      return tmp;
   }else{ //we create one after tmp and before tmp->next
//       LOGI("in mov get fragment nb %d\n", c->fragment_count);
      MOVFragment *newFrag = av_mallocz(sizeof(MOVFragment));
      if (!newFrag){
         return NULL;
      }
      c->fragment_count++;
      newFrag->next = tmp->next;
      tmp->next = newFrag;
      return newFrag;
   }
}

static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom){
    MOVFragment *frag = NULL;
    MOVTrackExt *trex = NULL;
    AVStream *st = NULL;
    MOVStreamContext *sc;
    int flags, track_id, i;
    
    avio_r8(pb); /* version */
    flags = avio_rb24(pb);

    track_id = avio_rb32(pb);
    if (!track_id)
        return -1;

    for (i = 0; i < c->fc->nb_streams; i++) {
       if (c->fc->streams[i]->id == track_id) {
      st = c->fc->streams[i];
      break;
       }
    }
    //LOGI("in tfhd for track index %d", i);
    if (!st) {
       LOGE("read tfhd : could not find corresponding track id %d\n", track_id);
       return -1;
    }
    sc = st->priv_data;
    frag = mov_get_fragment(sc, c->fragment.moof_offset);
    frag->track_id = track_id;
    c->curFrag = frag;
    c->curFrag->moof_offset = c->fragment.moof_offset;
    c->curFrag->seq_number = c->fragment.seq_number;
   
    for (i = 0; i < c->trex_count; i++)
        if (c->trex_data[i].track_id == frag->track_id) {
            trex = &c->trex_data[i];
            break;
        }
    if (!trex) {
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
        return -1;
    }

    if (flags & 0x01){
      
        frag->base_data_offset = avio_rb64(pb);
	LOGI("in tfhd, using base data offset : %lld\n", frag->base_data_offset);
//      avio_rb64(pb);
      //frag->base_data_offset = frag->moof_offset; //<lgy : safer that way <- that was a bug actually
    }else{
       frag->base_data_offset = frag->moof_offset;
       LOGI("in tfhd, using moof offset as base data offset : %lld\n", frag->base_data_offset);
    }
    if (flags & 0x02) frag->stsd_id          = avio_rb32(pb);
    else              frag->stsd_id          = trex->stsd_id;

    frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
    frag->size     = flags & 0x10 ? avio_rb32(pb) : trex->size;
    frag->flags    = flags & 0x20 ? avio_rb32(pb) : trex->flags;
    av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);

    frag->traf_data.encboxpos = -1;
    frag->traf_data.encboxsize = 0;
    frag->traf_data.count = 0;
    return 0;
}

static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    c->chapter_track = avio_rb32(pb);
    return 0;
}

static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    MOVTrackExt *trex;
   LOGI("in read_trex\n");
    if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
        return -1;
    trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
    if (!trex)
        return AVERROR(ENOMEM);
    c->trex_data = trex;
    trex = &c->trex_data[c->trex_count++];
    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */
    trex->track_id = avio_rb32(pb);
    trex->stsd_id  = avio_rb32(pb);
    trex->duration = avio_rb32(pb);
    trex->size     = avio_rb32(pb);
    trex->flags    = avio_rb32(pb);
    return 0;
}

static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom){
   MOVFragment *frag = &c->fragment;
   AVStream *st = NULL;
   MOVStreamContext *sc;
   unsigned int format;
   enum AVCodecID id;
   LOGI("in read frma\n");
   if (c->fc->nb_streams < 1){
      LOGE("no stream yet :/\n");
   }
   st = c->fc->streams[c->fc->nb_streams - 1];
   if (!st) {
      LOGE("could not find corresponding track id %d\n", frag->track_id);
      return -1;
   }
   sc = st->priv_data;
   format = avio_rl32(pb);
   st->codec->codec_tag = format;
   id = ff_codec_get_id(ff_codec_movaudio_tags, format);
   if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
      id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
   
   if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
      LOGI("frma : found audio codec\n");
      st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
   } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
      format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
     id = ff_codec_get_id(ff_codec_movvideo_tags, format);
     if (id <= 0)
        id = ff_codec_get_id(ff_codec_bmp_tags, format);
     if (id > 0){
        LOGI("frma : found video codec\n");
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     }
     else if(st->codec->codec_type == AVMEDIA_TYPE_DATA){
        id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
        if(id > 0)
           st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
     }
   }
   st->codec->codec_id = id;
   if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
      st->codec->sample_rate= sc->time_scale;
   
   
   /* special codec parameters handling */
   switch (st->codec->codec_id) {
     /* no ifdef since parameters are always those */
     case CODEC_ID_QCELP:
        // force sample rate for qcelp when not stored in mov
        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
           st->codec->sample_rate = 8000;
        st->codec->frame_size= 160;
        st->codec->channels= 1; /* really needed */
        break;
     case CODEC_ID_AMR_NB:
     case CODEC_ID_AMR_WB:
        st->codec->frame_size= sc->samples_per_frame;
        st->codec->channels= 1; /* really needed */
        /* force sample rate for amr, stsd in 3gp does not store sample rate */
        if (st->codec->codec_id == CODEC_ID_AMR_NB)
           st->codec->sample_rate = 8000;
        else if (st->codec->codec_id == CODEC_ID_AMR_WB)
           st->codec->sample_rate = 16000;
        break;
     case CODEC_ID_MP2:
     case CODEC_ID_MP3:
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
        st->need_parsing = AVSTREAM_PARSE_FULL;
        break;
     case CODEC_ID_GSM:
     case CODEC_ID_ADPCM_MS:
     case CODEC_ID_ADPCM_IMA_WAV:
        st->codec->frame_size = sc->samples_per_frame;
        st->codec->block_align = sc->bytes_per_frame;
        break;
     case CODEC_ID_ALAC:
        if (st->codec->extradata_size == 36) {
           st->codec->frame_size = AV_RB32(st->codec->extradata+12);
           st->codec->channels   = AV_RB8 (st->codec->extradata+21);
           st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
        }
        break;
     default:
        break;
   }
   return 0;
}



static int mov_read_tfra(MOVContext *c, AVIOContext *pb, MOVAtom atom){
   int version, traf_num_size, sample_num_size, trun_num_size;
   uint32_t trackId, entries, i;
   uint8_t temp, sample_num;
   AVStream *st = NULL;
   MOVStreamContext *sc;
   MOVFragment *last = NULL, *blast = NULL;
   version = avio_r8(pb);
   avio_rb24(pb); //flags
   trackId = avio_rb32(pb);
   avio_rb24(pb);
   temp = avio_r8(pb);
   sample_num_size = temp & 0xFF;
   trun_num_size = (temp >> 2) & 0xFF;
   traf_num_size = (temp >> 4) & 0xFF;
   entries = avio_rb32(pb);
   
   for (i = 0; i < c->fc->nb_streams; i++) {
      if (c->fc->streams[i]->id == trackId) {
     st = c->fc->streams[i];
     break;
      }
   }
   if (!st) {
      av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", trackId);
      return -1;
   }
   sc = st->priv_data;
   LOGI("in read tfra for stream %d", st->index);
   if (entries <= 0 || traf_num_size != 0 || trun_num_size != 0 || sample_num_size != 0){ //we don't handle complicated cases right now :)
      LOGE("not handled tfra\n");
      c->found_mfra = -1;
      return -1;
   }
   
   for (i = 0; i < entries; i++){
      int64_t time;
      uint64_t moof_offset;
      MOVFragment *frag;
      if (version == 1){
	time = avio_rb64(pb);
	moof_offset = avio_rb64(pb);
      }else{
	time = avio_rb32(pb);
	moof_offset = avio_rb32(pb);
      }
      avio_rb16(pb); //traf and trun number, we don't care about them
      sample_num = avio_r8(pb);
      frag = mov_get_fragment(sc, moof_offset);
      if (!frag->moof_offset){ //only do something if we did not know about this moof
//      if (sample_num != 1){//case too complicated to handle
//         LOGE("random sample index != 1 in moof\n");
//         c->found_mfra = -1;
//         return -1;
//      }
     if (i == 0){
            LOGI("first fragment starts at %lld\n", time);
     }
     frag->moof_offset = moof_offset;
     frag->first_cts = time;
      }
      if (i == entries - 1){
         last = frag;
      }else if (i == entries - 2){
         blast = frag;
      }
   }
   if ((double)st->duration / sc->time_scale <=0 && last && blast){
      LOGE("trying ack to fix stream duration\n");
      st->duration = blast->first_cts + (last->first_cts - blast->first_cts);
      LOGE("now we set a duration of %lld", st->duration);
      LOGE("this codec is %d, size of extradata : %d\n", st->codec->codec_id, st->codec->extradata_size);
   }
   if (!c->found_mfra) //because there are several tfra in a mfra
      c->found_mfra = 1;
   return 0;
}

static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom){
    MOVFragment *frag = c->curFrag;
    AVStream *st = NULL;
    MOVStreamContext *sc;
    uint64_t offset;
    int64_t dts;
    int data_offset = 0;
    unsigned entries, first_sample_flags = 0;
    int flags, distance, i;
 
   for (i = 0; i < c->fc->nb_streams; i++) {
        if (c->fc->streams[i]->id == frag->track_id) {
            st = c->fc->streams[i];
            break;
        }
    }
    if (!st) {
        LOGE("trun : could not find corresponding track id %d\n", frag->track_id);
        return -1;
    }
    sc = st->priv_data;
    first_sample_flags = frag->flags;
    //LOGI("in trun for stream %d", st->index);
    if (sc->pseudo_stream_id+1 != frag->stsd_id)
        return 0;
    avio_r8(pb); /* version */
    flags = avio_rb24(pb);
    entries = avio_rb32(pb);
    
//     LOGE("flags 0x%x entries %d\n", flags, entries);
    if (flags & 0x001){
       data_offset        = avio_rb32(pb);
        LOGI("in trun, custom data offset for samples : %d\n", data_offset);
    }
    if (flags & 0x004) first_sample_flags = avio_rb32(pb);
    if (flags & 0x800) {
        MOVStts *ctts_data;
    //LOGD("each sample (%d) of the fragment has a composition time offset, previous ctts count : %d", entries, frag->ctts_count);
        if ((uint64_t)entries+frag->ctts_count >= UINT_MAX/sizeof(*frag->ctts_data))
            return -1;
//  if ((entries+sc->ctts_count)*sizeof(*sc->ctts_data) > sc->ctts_alloc){
//     sc->ctts_alloc =  fmax((entries+sc->ctts_count)*sizeof(*sc->ctts_data), sc->ctts_alloc * 2);
        //LOGI("trun: will realloc from 0X%08X with size of : %d", frag->ctts_data, (entries+frag->ctts_count)*sizeof(MOVStts));
        ctts_data = av_realloc(frag->ctts_data, (entries+frag->ctts_count)*sizeof(MOVStts));
        //LOGI("result is 0X%08X", ctts_data);
//  }
        if (!ctts_data)
            return AVERROR(ENOMEM);
        frag->ctts_data = ctts_data;
    }
    
    dts = sc->stts_duration;
//     LOGI("trun : base data offset : %llu", frag->base_data_offset ); 
    offset = frag->base_data_offset + data_offset;
    distance = 0;
    frag->index_entries = av_realloc(frag->index_entries, (frag->sample_count + entries) * sizeof(AVIndexEntry));
    if (!frag->index_entries){
       return AVERROR(ENOMEM);
    }
//     LOGD("first sample ok trun, frag is 0X%08X, ctts data : 0X%08X", frag, frag->ctts_data);
    for (i = 0; i < entries; i++) {
        unsigned sample_size = frag->size;
        int sample_flags = i ? frag->flags : first_sample_flags;
        unsigned sample_duration = frag->duration;
        int keyframe;
    AVIndexEntry *entry;

        if (flags & 0x100) sample_duration = avio_rb32(pb);
        if (flags & 0x200) sample_size     = avio_rb32(pb);
        if (flags & 0x400) sample_flags    = avio_rb32(pb);
        if (flags & 0x800) {
       frag->ctts_data[frag->ctts_count].count = 1;
       frag->ctts_data[frag->ctts_count].duration = avio_rb32(pb);
//      if (sc->ctts_data[sc->ctts_count].duration < 0 && i+1<entries)
//         sc->dts_shift = FFMAX(sc->dts_shift, -sc->ctts_data[sc->ctts_count].duration);
        frag->ctts_count++;
        }
        if (i == 0){ //store first cts of fragment
           if (frag->first_cts || frag->next){
          //LOGE("parsing trun while reading first cts of frag : %"PRId64"", frag->first_cts);
          //we are parsing fragment while reading/seeking, so we know the first cts, retrieve dts based on this
          dts = frag->first_cts  + frag->cur_duration - ((flags & 0x800) ? frag->ctts_data[frag->ctts_count - 1].duration : 0);
       }else{
          //LOGE("parsing trun linearly, current dts : %"PRId64" and duration of first sample : %d", dts, (flags & 0x800) ? frag->ctts_data[frag->ctts_count - 1].duration : 0);
          //otherwise we are parsing the file linearly, we know the dts, retrieve the first cts
          frag->first_cts = dts + (unsigned)((flags & 0x800) ? frag->ctts_data[frag->ctts_count - 1].duration : 0);
          //LOGI("after computation, first cts is %"PRId64"", frag->first_cts);
       }
        }
    if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
        (flags & 0x004 && !i) || sample_flags & 0x2000000))
        distance = 0;
    entry = &frag->index_entries[frag->sample_count + i];
    entry->flags = keyframe ? AVINDEX_KEYFRAME : 0;
    entry->min_distance = distance;
    entry->pos = offset;
    entry->size = sample_size;
    entry->timestamp = dts - sc->dts_shift;
//   av_add_index_entry(st, offset, dts -sc->dts_shift, sample_size, distance,
//             keyframe ? AVINDEX_KEYFRAME : 0);
      
//         if (i == 0)
        //LOGD("AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
        //        "duration %d, distance %d, keyframe %d, sampleflags %x\n", st->index, sc->sample_count+i,
        //        offset, dts, sample_duration, distance, keyframe, sample_flags);
        distance++;
        dts += sample_duration;
	frag->cur_duration += sample_duration;
        offset += sample_size;
    }
    frag->sample_count += entries;
    //frag->moof_offset = offset; 
    sc->stts_duration = dts;
//     LOGD("end of trun");
    return 0;
}

/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
/* like the files created with Adobe Premiere 5.0, for samples see */
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom){
    int err;

    if (atom.size < 8)
        return 0; /* continue */
    if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
        avio_skip(pb, atom.size - 4);
        return 0;
    }
    atom.type = avio_rl32(pb);
    atom.size -= 8;
    if (atom.type != MKTAG('m','d','a','t')) {
        avio_skip(pb, atom.size);
        return 0;
    }
    err = mov_read_mdat(c, pb, atom);
    return err;
}

static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom){
#if CONFIG_ZLIB
    AVIOContext ctx;
    uint8_t *cmov_data;
    uint8_t *moov_data; /* uncompressed data */
    long cmov_len, moov_len;
    int ret = -1;

    avio_rb32(pb); /* dcom atom */
    if (avio_rl32(pb) != MKTAG('d','c','o','m'))
        return -1;
    if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
        av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
        return -1;
    }
    avio_rb32(pb); /* cmvd atom */
    if (avio_rl32(pb) != MKTAG('c','m','v','d'))
        return -1;
    moov_len = avio_rb32(pb); /* uncompressed size */
    cmov_len = atom.size - 6 * 4;

    cmov_data = av_malloc(cmov_len);
    if (!cmov_data)
        return AVERROR(ENOMEM);
    moov_data = av_malloc(moov_len);
    if (!moov_data) {
        av_free(cmov_data);
        return AVERROR(ENOMEM);
    }
    avio_read(pb, cmov_data, cmov_len);
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
        goto free_and_return;
    if(ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
        goto free_and_return;
    atom.type = MKTAG('m','o','o','v');
    atom.size = moov_len;
#ifdef DEBUG
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
#endif
    ret = mov_read_default(c, &ctx, atom);
free_and_return:
    av_free(moov_data);
    av_free(cmov_data);
    return ret;
#else
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
    return -1;
#endif
}

/* edit list atom */
static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    MOVStreamContext *sc;
    int i, edit_count;

    if (c->fc->nb_streams < 1)
        return 0;
    sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;

    avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */
    edit_count = avio_rb32(pb); /* entries */

    if((uint64_t)edit_count*12+8 > atom.size)
        return -1;

    for(i=0; i<edit_count; i++){
        int time;
        int duration = avio_rb32(pb); /* Track duration */
        time = avio_rb32(pb); /* Media time */
        avio_rb32(pb); /* Media rate */
        if (i == 0 && time >= -1) {
            sc->time_offset = time != -1 ? time : -duration;
        }
    }

    if(edit_count > 1)
        av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
               "a/v desync might occur, patch welcome\n");

    av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
    return 0;
}


static int mov_read_pssh(MOVContext *c, AVIOContext *pb, MOVAtom atom){
   uint8_t systemId[16];
   int dataSize;
   uint8_t *data = NULL;
   int err = 0;
   LOGI("Found protection system specific box, value of drm struct : 0x%08x\n", (unsigned)c->drm);
   avio_r8(pb); ///version
   avio_rb24(pb); ///flags
   avio_read(pb, systemId, 16);
   dataSize = avio_rb32(pb);
   data = av_malloc(dataSize);
   if (!data){
      return AVERROR(ENOMEM);
   }
   avio_read(pb, data, dataSize);
   c->drm = c->fc->drm_st;
   c->drmState = c->fc->drm_state;
   if (c->drm && c->drm->alloc2){
      if (memcmp(systemId, (MOVUUID){0x9A, 0x04, 0xF0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xAB, 0x92, 0xE6, 0x5B, 0xE0, 0x88, 0x5F, 0x95}, 16) == 0){
         LOGI("This is a microsoft playready encrypted file\n");
         c->drmContext = c->drm->alloc2(c->drmState, AVDRM_PLAYREADY, data, dataSize, NULL, &err);
	 LOGI("result of alloc : %p\n", c->drmContext);
      }
   }
   
     
   av_free(data);
   if (!c->drmContext){
     c->fc->drm_error = err;
     return AVERROR_DRM_PROBLEM;
   }else{
     return 0;
   }
   
}

static int mov_read_tenc(MOVContext *c, AVIOContext *pb, MOVAtom atom){
   MOVFragment *frag = &c->fragment;
   AVStream *st = NULL;
   MOVStreamContext *sc;
   //LOGI("found sample enc box");
   if (c->fc->nb_streams < 1){
      LOGE("no stream yet :/\n");
   }
   st = c->fc->streams[c->fc->nb_streams - 1];
   if (!st) {
      LOGE("could not find corresponding track id %d\n", frag->track_id);
      return -1;
   }
   sc = st->priv_data;
   avio_r8(pb); ///version
   avio_rb24(pb); ///flags
   avio_rb24(pb); /// default algoId
   sc->ivSize = avio_r8(pb);
   avio_skip(pb, 16); ///default kid
//    LOGE("read iv size in media header : %d", sc->ivSize);
   return 0;
}               

static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
  MOVFragment *frag = c->curFrag;
  MOVTraf *traf = NULL;
  AVStream *st = NULL;
  MOVStreamContext *sc;
  int flags;
  int i;
  int64_t begin = avio_tell(pb) - (atom.type == MKTAG('u', 'u', 'i', 'd') ? 24 : 8);
  //LOGI("found sample enc box\n");
  for (i = 0; i < c->fc->nb_streams; i++) {
    if (c->fc->streams[i]->id == frag->track_id) {
      st = c->fc->streams[i];
      break;
    }
  }
  if (!st) {
    av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
    return -1;
  }
  sc = st->priv_data;
  avio_r8(pb); ///version
  flags = avio_rb24(pb);
  traf = &frag->traf_data;
  traf->ivSize = sc->ivSize;
  if (!traf->ivSize){
    traf->ivSize = 8;
  }
  if (!traf){
    LOGE("error finding traf\n");
    return -1;
  }
  if (flags & 0x001){
    avio_rb24(pb); //algoId
    traf->ivSize = avio_r8(pb); //ivSize
    avio_skip(pb, 16); //KID
  }
  traf->count = avio_rb32(pb);
  traf->encboxpos = avio_tell(pb);
  traf->encboxsize = atom.size + 8 - (traf->encboxpos - begin);
  LOGE("count in senc is %d, size is %d\n", traf->count, traf->encboxsize);
  traf->flags = flags;
  if (sc->current_frag){
    sc->encbox_data = av_realloc(sc->encbox_data, traf->encboxsize);
    if (!sc->encbox_data){
      return AVERROR(ENOMEM);
    }
    if (avio_read(pb, sc->encbox_data, traf->encboxsize) != traf->encboxsize){	
      LOGE("error reading encbox for stream %d\n", sc->ffindex);
    }else{

    }
    sc->encbox_cur = sc->encbox_data;
    sc->encbox_ok = 1;
  }
  return 0;
}

static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom){
   uint8_t extended[16];
   avio_read(pb, extended, 16);
   if (memcmp(extended, (MOVUUID){0xd0, 0x8a, 0x4f, 0x18, 0x10, 0xf3, 0x4a, 0x82, 0xb6, 0xc8, 0x32, 0xd8, 0xab, 0xa1, 0x83, 0xd3}, 16) == 0){
      //This is a protection system specific box
      return mov_read_pssh(c, pb, (MOVAtom){ AV_RL32("pssh"), atom.size - 16 });
   }else if (memcmp(extended, (MOVUUID){0xA2, 0x39, 0x4F, 0x52, 0x5A, 0x9B, 0x4f, 0x14, 0xA2, 0x44, 0x6C, 0x42, 0x7C, 0x64, 0x8D, 0xF4}, 16) == 0){
      //This is a sample enc box
      return mov_read_senc(c, pb, atom);
//       LOGE("in sample enc box stream %d, nb samples : %d, size of encbox : %d", sc->ffindex, traf->count, traf->encboxsize);
   }else if (memcmp(extended, (MOVUUID){0x89, 0x74, 0xdb,0xce, 0x7b, 0xe7, 0x4c, 0x51, 0x84, 0xf9, 0x71, 0x48, 0xf9, 0x88, 0x25, 0x54}, 16) == 0){
      return mov_read_tenc(c, pb, (MOVAtom){ AV_RL32("tenc"), atom.size - 16 });
   }  
   return 0;
}

static const MOVParseTableEntry mov_default_parse_table[] = {
{ MKTAG('a','v','s','s'), mov_read_extradata },
{ MKTAG('c','h','p','l'), mov_read_chpl },
{ MKTAG('c','o','6','4'), mov_read_stco },
{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
{ MKTAG('d','i','n','f'), mov_read_default },
{ MKTAG('d','r','e','f'), mov_read_dref },
{ MKTAG('e','d','t','s'), mov_read_default },
{ MKTAG('e','l','s','t'), mov_read_elst },
{ MKTAG('e','n','d','a'), mov_read_enda },
{ MKTAG('f','i','e','l'), mov_read_extradata },
{ MKTAG('f','t','y','p'), mov_read_ftyp },
{ MKTAG('g','l','b','l'), mov_read_glbl },
{ MKTAG('h','d','l','r'), mov_read_hdlr },
{ MKTAG('i','l','s','t'), mov_read_ilst },
{ MKTAG('j','p','2','h'), mov_read_extradata },
{ MKTAG('m','d','a','t'), mov_read_mdat },
{ MKTAG('m','d','h','d'), mov_read_mdhd },
{ MKTAG('m','d','i','a'), mov_read_default },
{ MKTAG('m','e','t','a'), mov_read_meta },
{ MKTAG('m','i','n','f'), mov_read_default },
{ MKTAG('m','o','o','f'), mov_read_moof },
{ MKTAG('m','o','o','v'), mov_read_moov },
{ MKTAG('m','v','e','x'), mov_read_default },
{ MKTAG('m','v','h','d'), mov_read_mvhd },
{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
{ MKTAG('a','v','c','C'), mov_read_glbl },
{ MKTAG('h','v','c','C'), mov_read_glbl },
{ MKTAG('p','a','s','p'), mov_read_pasp },
{ MKTAG('s','e','n','c'), mov_read_senc },
{ MKTAG('s','t','b','l'), mov_read_default },
{ MKTAG('s','t','c','o'), mov_read_stco },
{ MKTAG('s','t','p','s'), mov_read_stps },
{ MKTAG('s','t','r','f'), mov_read_strf },
{ MKTAG('s','t','s','c'), mov_read_stsc },
{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
{ MKTAG('s','t','t','s'), mov_read_stts },
{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
{ MKTAG('t','r','a','k'), mov_read_trak },
{ MKTAG('t','r','a','f'), mov_read_default },
{ MKTAG('t','r','e','f'), mov_read_default },
{ MKTAG('c','h','a','p'), mov_read_chap },
{ MKTAG('t','r','e','x'), mov_read_trex },
{ MKTAG('t','r','u','n'), mov_read_trun },
{ MKTAG('u','d','t','a'), mov_read_default },
{ MKTAG('w','a','v','e'), mov_read_wave },
{ MKTAG('e','s','d','s'), mov_read_esds },
{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
{ MKTAG('c','m','o','v'), mov_read_cmov },
{ MKTAG('u','u','i','d'), mov_read_uuid },
{ MKTAG('s','i','n','f'), mov_read_default},
{ MKTAG('s','c','h','i'), mov_read_default},
{ MKTAG('i','p','r','o'), mov_read_default},
{ MKTAG('f','r','m','a'), mov_read_frma },
{ MKTAG('t','f','r','a'), mov_read_tfra },
{ MKTAG('m','f','h','d'), mov_read_mfhd },
{ MKTAG('p','s','s','h'), mov_read_pssh },
{ MKTAG('t','e','n','c'), mov_read_tenc },
{ 0, NULL }
};

static int mov_probe(AVProbeData *p)
{
    unsigned int offset;
    uint32_t tag;
    int score = 0;
    //LOGE("in mov probe first bytes %x %x %x %x %x %x %x %x", p->buf[0], p->buf[1], p->buf[2], p->buf[3], p->buf[4], p->buf[5], p->buf[6], p->buf[7] );
    /* check file header */
    offset = 0;
    for(;;) {
        /* ignore invalid offset */
        if ((offset + 8) > (unsigned int)p->buf_size)
            return score;
        tag = AV_RL32(p->buf + offset + 4);
        switch(tag) {
        /* check for obvious tags */
        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
        case MKTAG('m','o','o','v'):
        case MKTAG('m','d','a','t'):
        case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
        case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
        case MKTAG('f','t','y','p'):
           LOGD("found specific tag, returning max score\n");
            return AVPROBE_SCORE_MAX;
        /* those are more common words, so rate then a bit less */
        case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
        case MKTAG('w','i','d','e'):
        case MKTAG('f','r','e','e'):
        case MKTAG('j','u','n','k'):
        case MKTAG('p','i','c','t'):
            return AVPROBE_SCORE_MAX - 5;
        case MKTAG(0x82,0x82,0x7f,0x7d):
        case MKTAG('s','k','i','p'):
        case MKTAG('u','u','i','d'):
        case MKTAG('p','r','f','l'):
            offset = AV_RB32(p->buf+offset) + offset;
            /* if we only find those cause probedata is too small at least rate them */
            score = AVPROBE_SCORE_MAX - 50;
            break;
        default:
            /* unrecognized tag */
            return score;
        }
    }
    return score;
}

// must be done after parsing all trak because there's no order requirement
static void mov_read_chapters(AVFormatContext *s){
    MOVContext *mov = s->priv_data;
    AVStream *st = NULL;
    MOVStreamContext *sc;
    int64_t cur_pos;
    int i;

    for (i = 0; i < s->nb_streams; i++)
        if (s->streams[i]->id == mov->chapter_track) {
            st = s->streams[i];
            break;
        }
    if (!st) {
        av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
        return;
    }

    st->discard = AVDISCARD_ALL;
    sc = st->priv_data;
    cur_pos = avio_tell(sc->pb);

    for (i = 0; i < st->nb_index_entries; i++) {
        AVIndexEntry *sample = &st->index_entries[i];
        int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
        uint8_t *title;
        uint16_t ch;
        int len, title_len;

        if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
            av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
            goto finish;
        }

        // the first two bytes are the length of the title
        len = avio_rb16(sc->pb);
        if (len > sample->size-2)
            continue;
        title_len = 2*len + 1;
        if (!(title = av_mallocz(title_len)))
            goto finish;

        // The samples could theoretically be in any encoding if there's an encd
        // atom following, but in practice are only utf-8 or utf-16, distinguished
        // instead by the presence of a BOM
        if (!len) {
            title[0] = 0;
        } else {
            ch = avio_rb16(sc->pb);
            if (ch == 0xfeff)
                avio_get_str16be(sc->pb, len, title, title_len);
            else if (ch == 0xfffe)
                avio_get_str16le(sc->pb, len, title, title_len);
            else {
                AV_WB16(title, ch);
                if (len == 1 || len == 2)
                    title[len] = 0;
                else
                    avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
            }
        }

        avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
        av_freep(&title);
    }
finish:
    avio_seek(sc->pb, cur_pos, SEEK_SET);
}

static int mov_read_header(AVFormatContext *s)
{
    MOVContext *mov = s->priv_data;
    AVIOContext *pb = s->pb;
    int err, i;
    MOVAtom atom = { AV_RL32("root") };

    mov->fc = s;
    /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
    if(pb->seekable)
        atom.size = avio_size(pb);
    else
        atom.size = INT64_MAX;

    LOGI("will read file\n");
    /* check MOV header */
    if ((err = mov_read_default(mov, pb, atom)) < 0) {
        av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
        return err;
    }
    LOGI("end of read file\n");
    if (!mov->found_moov) {
        av_log(s, AV_LOG_ERROR, "moov atom not found\n");
    LOGE("moov atom not found\n");
        return -1;
    }
    av_dlog(mov->fc, "on_parse_exit_offset=%lld\n", avio_tell(pb));

    if (pb->seekable && mov->chapter_track > 0)
        mov_read_chapters(s);

    for (i = 0; i < s->nb_streams; i++){
       ((MOVStreamContext*)s->streams[i]->priv_data)->current_frag = NULL;
    }

    return 0;
}

static void mov_reset_fragment(MOVFragment *frag, int full){
   LOGI("will reset fragment\n");
   frag->cur_sample = 0;
   frag->ctts_index = 0;
   frag->ctts_sample = 0;
   if (!full)
      return;
   if (frag->ctts_data){
      av_freep(&frag->ctts_data);
   }
   if (frag->index_entries){
      av_freep(&frag->index_entries);
   }
   frag->parsed = 0;
   frag->sample_count = 0;
   frag->duration = 0;
   frag->base_data_offset = 0;
   frag->flags = 0;
   memset(&frag->traf_data, 0, sizeof(MOVTraf));
}

static int mov_parse_fragment(MOVContext *c, MOVStreamContext *msc, AVFormatContext *s, MOVFragment *frag){
   msc->encbox_ok = 0;
   if (!frag->parsed){
//       LOGI("will parse fragment\n");
      if (frag->next){
         LOGI("first see if it's complete by checking next fragment\n");
         if (avio_seek(s->pb, frag->next->moof_offset, SEEK_SET) < 0 || (avio_rb32(s->pb) == 0 && s->pb->error)){
            LOGE("mov_find_next_sample, next fragment not ready, let's wait\n");
            return -1;
         }
      }
      LOGI("ok, now we seek to fragment\n");
      if (avio_seek(s->pb, frag->moof_offset, SEEK_SET) < 0){
         LOGE("mov_find_next_sample, could not seek to fragment\n");
         return -1;
      }
//       LOGI("now we read it");
      if (mov_read_one(c, s->pb)){
         LOGE("error parsing moof when reading\n");
         mov_reset_fragment(frag, 1);
         return -1;
      }
//       LOGI("new fragment has %d entries", frag->sample_count);
      frag->parsed = 1;
   }
   return 0;
}



static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st, MOVFragment **frag){
    AVIndexEntry *sample = NULL;
    int64_t best_dts = INT64_MAX;
    int i;
    MOVContext *c = (MOVContext*)s->priv_data;
    //LOGI("in mov find next sample");
    if (c->seekmode){
       for (i = 0; i < s->nb_streams; i++) {
      AVStream *avst = s->streams[i];
      MOVStreamContext *msc = avst->priv_data;
      AVIndexEntry *current_sample;
      int64_t dts;
      //LOGI("in mov find next sample with fragments for stream %d", i);
      if (!msc->current_frag){
         LOGI("no current frag for stream %d, getting first\n", i);
             msc->current_frag = msc->first_frag;
             mov_reset_fragment(msc->current_frag, 0);
             msc->encbox_ok = 0;
      }
      if (!msc->current_frag->parsed){
             LOGI("mov_find_next_sample, fragment is not parsed\n");
             if (mov_parse_fragment(c, msc, s, msc->current_frag)){
               LOGE("mov_find_next_sample, could not parse fragment, returning NULL\n");
               return NULL;
             }
          }
     if (msc->current_frag->cur_sample >= msc->current_frag->sample_count){
            if (msc->current_frag->next){
               LOGI("we are at the end of fragment (%d) for stream %d, switching to next one with start time of %lld\n", msc->current_frag->sample_count, i, msc->current_frag->next->first_cts);
               mov_reset_fragment(msc->current_frag, 0);
               msc->encbox_ok = 0;
               msc->current_frag = msc->current_frag->next;
               mov_reset_fragment(msc->current_frag, 0);
               msc->encbox_ok = 0;
               if (!msc->current_frag->parsed && mov_parse_fragment(c, msc, s, msc->current_frag)){
                  LOGE("could not parse new fragment\n");
                  return NULL;
               }
            }else{
               LOGE("reached last fragment of stream, return NULL\n");
               continue;
            }
     }
     if (msc->current_frag->sample_count == 0 || msc->current_frag->cur_sample >= msc->current_frag->sample_count){
        LOGE("new fragment has no entries or no more fragments\n");
        continue;
     }
     current_sample = &msc->current_frag->index_entries[msc->current_frag->cur_sample];
     dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
     if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
        (s->pb->seekable &&
        ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
        ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
        (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
        //LOGD("ok we choose a sample for stream %d with dts %"PRId64" and pos %"PRId64", seekable : %d", msc->ffindex, current_sample->timestamp, current_sample->pos, s->pb->seekable);
        sample = current_sample;
        best_dts = dts;
        *st = avst;
        *frag = msc->current_frag;
      }
       }
    }else{
       //LOGI("in regular mov find next sample\n");
       for (i = 0; i < s->nb_streams; i++) {
      AVStream *avst = s->streams[i];
      MOVStreamContext *msc = avst->priv_data;
      if (msc->pb && msc->current_sample < avst->nb_index_entries) {
         AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
         int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
         //LOGD("stream %d, sample %d, dts \n", i, msc->current_sample, dts);
         if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
        (s->pb->seekable &&
        ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
        ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
        (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
        sample = current_sample;
                best_dts = dts;
                *st = avst;
             }
      }
       }
    }
   

    return sample;
}

static void skip_one_encbox(MOVStreamContext *sc, MOVFragment *frag, MOVTraf *traf){
      if (frag && traf && sc->encbox_data && sc->encbox_ok && sc->encbox_cur - sc->encbox_data + traf->ivSize <= traf->encboxsize) {
        sc->encbox_cur += traf->ivSize;
        if (traf->flags & 0x002) {
            int entries, i;
	    int avail = traf->encboxsize - (sc->encbox_cur - sc->encbox_data);
	    if (avail >= 2){
	      sc->encbox_cur += 2;
	      avail -= 2;
	    }else{
	      sc->encbox_ok = 0; 
	    }
	    
            for (i = 0; i < entries && sc->encbox_ok && avail >= 6; ++i) {
                sc->encbox_cur += 2;
                sc->encbox_cur += 4;
		avail -= 6;
            }

            //sc->encbox_cur += 4;
        } 
      }
}

static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    MOVContext *mov = s->priv_data;
    MOVFragment *frag = NULL;
    MOVStreamContext *sc;
    AVIndexEntry *sample;
    AVStream *st = NULL;
    MOVTraf *traf = NULL;
    int ret;
retry:
//      LOGI("in mov read packet\n");
    sample = mov_find_next_sample(s, &st, &frag);
    if (!sample) {
        LOGE("No sample found\n");
        if (s->pb->seekable ||
        ( !mov->found_mdat && mov_read_default(mov, s->pb, (MOVAtom) {
        AV_RL32("root"), INT64_MAX
        }) < 0) ||
                url_feof(s->pb)) {

            LOGE("will return averror_eof\n");
            return AVERROR_EOF;
        }
        av_dlog(s, "read fragments, offset 0x%llx\n", avio_tell(s->pb));
        LOGE("we will retry\n");
        goto retry;
    }
//      LOGI("found sample\n");
    if (!st) {
        LOGE("oups no AVSTREAM !!\n");
        return -1;
    }
    sc = st->priv_data;
    /* must be done just before reading, to avoid infinite loop on sample */
    sc->current_sample++;
    if (frag) {
        frag->cur_sample++;
    }

//        LOGI("will test traf\n");
//    LOGI("we have trafs\n");
    if (frag) {
        if (st->discard != AVDISCARD_ALL) {
            traf = &frag->traf_data;
            if (traf->encboxpos >= 0 && traf->encboxsize && (!sc->encbox_data || !sc->encbox_ok)) {
                LOGE("don't have sample enc box yet for stream %d, get it at pos : %lld\n", sc->ffindex, traf->encboxpos);
                if (avio_seek(sc->pb, traf->encboxpos, SEEK_SET) != traf->encboxpos) {
                    LOGE("error finding sample enc box\n");
                    return -1;
                }
                sc->encbox_data = av_realloc(sc->encbox_data, traf->encboxsize);
                if (!sc->encbox_data) {
                    LOGE("could not allocate encbox\n");
                    return AVERROR(ENOMEM);
                }
                if (avio_read(sc->pb, sc->encbox_data, traf->encboxsize) != traf->encboxsize) {
                    LOGE("error reading sample enc box\n");
                    av_freep(&sc->encbox_data);
                    return -1;
                }
                LOGI("we have it\n");
                sc->encbox_cur = sc->encbox_data;
                sc->encbox_ok = 1;
                if (frag->cur_sample != 1) { //because cur_sample++ is always called at the beginning
                    int i;
		    int avail = traf->encboxsize;
                    LOGE("not starting at first sample of box (%d/%d), updating position", frag->cur_sample, frag->sample_count);
                    //we have to update encbox_cur

                    for (i = 0; i < frag->cur_sample - 1 && avail >= traf->ivSize; i++) {
                        sc->encbox_cur += traf->ivSize;
			avail -= traf->ivSize;
//                         LOGE("updating with new iv size (%d) : %d", i, traf->ivSize);
                        if (traf->flags & 0x002) {
                            //there will be subsambles
                            int i;
                            int entries;
			    if (avail < 2) break;
			    entries = AV_RB16(sc->encbox_cur);
                            sc->encbox_cur += 2;
			    avail -= 2;
//                            LOGE("updating, sample %d has %d entries", i, entries);
                            for (i = 0; i < entries && avail >= 6; ++i) {
                                sc->encbox_cur += 6;
				avail -= 6;
                            }
                            if (i != entries) break;
                        }
                    }
                    if (i < frag->cur_sample - 1) sc->encbox_ok = 0; //we stopped in the loop, data is corrupted
//                      LOGE("updated now, remains %d bytes", traf->encboxsize - (sc->encbox_cur - sc->encbox_data));
                }

            } else if (traf->encboxpos < 0 || !traf->encboxsize) {
                traf = NULL;
            }
        } else {
            if (sc->encbox_data && sc->encbox_ok) {
                av_freep(&sc->encbox_data);
                sc->encbox_ok = 0;
            }
        }
    }

    if (st->discard == AVDISCARD_ALL)
        goto retry;
	
//        LOGI("will seek to sample pos\n");
    if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
        av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
               sc->ffindex, sample->pos);
        LOGE("stream %d, offset 0x%"PRIx64": partial file\n",
             sc->ffindex, sample->pos);
	skip_one_encbox(sc, frag, traf);
        return AVERROR_EOF;
    }
//         LOGI("will get packet now, of size %d at pos %ld",sample->size, sample->pos);
    ret = av_get_packet(sc->pb, pkt, sample->size);
    if (pkt->size != sample->size){
      LOGE("wrong packet size !!!!\n");
      skip_one_encbox(sc, frag, traf);
      return -1;
    }
    if (ret < 0) {
        LOGE("error getting packet for steam %d\n", sc->ffindex);
	skip_one_encbox(sc, frag, traf);
        return ret;
    }
#if CONFIG_DV_DEMUXER
    if (mov->dv_demux && sc->dv_audio_container) {
        avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
        av_free(pkt->data);
        pkt->size = 0;
        ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
        if (ret < 0)
            return ret;
    }
#endif


    pkt->stream_index = sc->ffindex;
    pkt->dts = sample->timestamp;
    //LOGI("ok now frag pointer 0X%08X, frag ctts data pointer 0X%08X, frag ctts count %d", (unsigned)frag, (unsigned)frag->ctts_data, frag->ctts_count);
    if (frag && frag->ctts_data && frag->ctts_count > 0) {
        pkt->pts = pkt->dts + sc->dts_shift + frag->ctts_data[frag->ctts_index].duration;
        frag->ctts_sample++;
        if (frag->ctts_index < frag->ctts_count &&  frag->ctts_data[frag->ctts_index].count == frag->ctts_sample) {
            frag->ctts_index++;
            frag->ctts_sample = 0;
        }
    } else if (sc->ctts_data && sc->ctts_count > 0) {
        pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
        // LOGI("stream %d, pts %"PRId64", dts %"PRId64" ", pkt->stream_index, pkt->pts, pkt->dts);
        /* update ctts context */
        sc->ctts_sample++;
        if (sc->ctts_index < sc->ctts_count &&
                sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
            sc->ctts_index++;
            sc->ctts_sample = 0;
        }
        if (sc->wrong_dts)
            pkt->dts = AV_NOPTS_VALUE;
    } else {
        if (frag) {
            int64_t next_dts;
            if (frag->cur_sample < frag->sample_count) {
                next_dts = frag->index_entries[frag->cur_sample].timestamp;
            } else if (sc->current_frag->next && sc->current_frag->next->sample_count) {
                next_dts = sc->current_frag->next->index_entries[0].timestamp;
            }
            pkt->duration = next_dts - pkt->dts;
        } else {
            int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
                               st->index_entries[sc->current_sample].timestamp : st->duration;
            pkt->duration = next_dts - pkt->dts;
        }
        pkt->pts = pkt->dts;
    }
    if (frag && traf && sc->encbox_data && sc->encbox_ok && (sc->encbox_cur - sc->encbox_data) + traf->ivSize <= traf->encboxsize) {
        char curIV[16] = {0};
	int res;
        memcpy(curIV, sc->encbox_cur, traf->ivSize);
        mov->drm->set_iv(mov->drmState, mov->drmContext, sc->encbox_cur, traf->ivSize);
        sc->encbox_cur += traf->ivSize;
        if (traf->flags & 0x002) {
            int subOffset = 0, subSize, i;
            uint32_t total_enc = 0;
            int entries;
	    int avail = traf->encboxsize - (sc->encbox_cur - sc->encbox_data);
	    if (avail >= 2){
	      entries = AV_RB16(sc->encbox_cur);// (*sc->encbox_cur++ << 8) + (*sc->encbox_cur++);
	      sc->encbox_cur += 2;
	      avail -= 2;
	    }else{
              LOGE("error: reached end of senc prematurely\n");
	      sc->encbox_ok = 0; 
	    }
	    
            for (i = 0; i < entries && sc->encbox_ok && avail >= 6; ++i) {
                int enc_mod_16 = total_enc % 16;
// 		LOGE("packet video first bytes are %02X %02X %02X %02X %02X\n", pkt->data[0 + subOffset], pkt->data[1 + subOffset], pkt->data[2 + subOffset], pkt->data[3 + subOffset], pkt->data[4 + subOffset]);
	        
                if (enc_mod_16 && (traf->ivSize == 8)) {
                    unsigned char iv[16];
                    uint64_t ivRight;
                    // Increment right part of IV with the number of samples read
                    memcpy(iv, curIV, 16);
                    ivRight = AV_RB64(iv+8);
                    ivRight += total_enc / 16;
                    AV_WB64(iv+8, ivRight);
                    mov->drm->set_iv(mov->drmState, mov->drmContext, iv, 16);
                }
                subOffset += AV_RB16(sc->encbox_cur);
                sc->encbox_cur += 2;
                subSize = AV_RB32(sc->encbox_cur);
                sc->encbox_cur += 4;
		avail -= 6;
                //LOGI("\t\tmodd16: %i, offset: %i, subSize: %i, size : %i\n", enc_mod_16, subOffset, subSize, pkt->size);

                if (subSize + subOffset > pkt->size) {
                    LOGE("error: subSize + offset is more thant packet size by %d !\n", subSize + subOffset - pkt->size);
                    subSize = pkt->size - subOffset;
		    sc->encbox_ok = 0;
                }
//         LOGE("will decode with offset %d and size %d for track %d of type %d", subOffset, subSize, pkt->stream_index, st->codec->codec_type);
                if (enc_mod_16) {
                    unsigned char temp[16];
                    int first_size = FFMIN(subSize, (16-enc_mod_16));
                    //LOGI("\t\t\tcopy/decrypt from %i to %i in subsample...\n", enc_mod_16, enc_mod_16 + first_size);

                    memcpy(temp + enc_mod_16, pkt->data + subOffset, first_size);
                    mov->drm->decrypt_packet(mov->drmState, mov->drmContext, temp, 16);
                    memcpy(pkt->data + subOffset, temp + enc_mod_16, first_size);

                    if (subSize - first_size > 0) {
                        res = mov->drm->decrypt_packet(mov->drmState, mov->drmContext, pkt->data + subOffset + first_size, subSize - first_size);
			if (res != subSize - first_size){
			  LOGE("error decrypting packet for track %d\n", pkt->stream_index);
			}
                    }
                } else {
                    res = mov->drm->decrypt_packet(mov->drmState, mov->drmContext, pkt->data + subOffset, subSize);
// 		    mov->drm->decrypt_packet(mov->drmState, mov->drmContext, NULL, 0);
		    if (res != subSize){
			  LOGE("error decrypting packet for stream %d, pkt size is %d\n", pkt->stream_index, pkt->size);
		    }
                }

                subOffset += subSize;
                total_enc += subSize;
            }

            //sc->encbox_cur += 4;
        } else {
            if (mov->drm && mov->drmContext){
                res = mov->drm->decrypt_packet(mov->drmState, mov->drmContext, pkt->data, pkt->size);

                if (res != pkt->size){
                  LOGE("error decrypting packet for stream %d\n", pkt->stream_index);
                }
           }
        }
    }else if (frag && traf && sc->encbox_data){
      LOGE("error: could not decrypt sample, no IV data\n");
    }



    if (st->discard == AVDISCARD_ALL)
        goto retry;
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
    pkt->pos = sample->pos;
    pkt->level = 0;
    pkt->bitrate = st->codec->bit_rate;
    mov->last_dts = av_rescale_q(pkt->dts, AV_TIME_BASE_Q, st->time_base);
//     if (pkt->dts == 0){
//        int i;
//        char *pktdata = av_mallocz(pkt->size * 3 + 1);
//        if (!pktdata){
//           return AVERROR(ENOMEM);
//        }
//        char temp[4];
//        for(i= 0; i < pkt->size; i++){
//           snprintf(temp, 4, "%02x ", pkt->data[i]);
//           av_strlcat(pktdata, temp, pkt->size * 3 + 1);
//        }
//        LOGE("first packet : %s", pktdata);
//        av_free(pktdata);
//     }
//     LOGD("stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d, first %02x %02x %02x %02x %02x %02x %02x %02x\n",
//          pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration, pkt->data[0], pkt->data[1], pkt->data[2], pkt->data[3], pkt->data[4], pkt->data[5], pkt->data[6], pkt->data[7]);
    return 0;
}

static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags, MOVFragment **frag)
{
    MOVStreamContext *sc = st->priv_data;
    int sample, time_sample;
    int i;
    sample = 0;

    LOGD("in seek for stream with index %d\n", st->index);
    if (sc->first_frag){
       MOVFragment *fr = sc->first_frag;
       LOGI("in mov_seek_stream with fragments, looking for %"PRId64", first frag has timestamp %"PRId64"\n", timestamp, fr->first_cts);
       while (fr->next && fr->next->first_cts < timestamp){
          fr = fr->next;
       }
       LOGI("stopped at fragment with first cts of %"PRId64"\n", fr->first_cts);
       mov_reset_fragment(fr, 0);
       sc->current_frag = fr;
       if (!fr->parsed){
          LOGE("need to parse fragment we are seeking to\n");
          if (mov_parse_fragment((MOVContext*)s->priv_data, sc, s, fr)){
            LOGE("could not parse fragment\n");
            return -1;
          }
       }else{
         sc->encbox_ok = 0;
       }
       sample = 0;
       for (i = 0; i < fr->sample_count; i++){
          if (fr->index_entries[i].timestamp < timestamp && (fr->index_entries[i].flags & AVINDEX_KEYFRAME)){
             sample = i;
          }else{
             break;
          }
       }
       fr->cur_sample = sample;
       LOGI("when seeking, we are at fragment with seq_number %d, and sample %d, dts is %"PRId64"\n", fr->seq_number, sample, fr->index_entries[sample].timestamp);
       if (fr->ctts_data) {
          time_sample = 0;
          for (i = 0; i < fr->ctts_count; i++) {
             int next = time_sample + fr->ctts_data[i].count;
             if (next > fr->cur_sample) {
                fr->ctts_index = i;
                fr->ctts_sample = fr->cur_sample - time_sample;
                break;
             }
             time_sample = next;
          }
       }
       if (fr->cur_sample != 0 && fr->traf_data.encboxpos >= 0 && sc->encbox_ok){ 
         //we have to update encbox_cur
         int i; MOVTraf *traf = &fr->traf_data;
	 int avail = fr->traf_data.encboxsize;
	 LOGE("not starting at first sample of encbox, updating position\n");
         sc->encbox_cur = sc->encbox_data;
         for (i = 0; i < fr->cur_sample && avail >= traf->ivSize; i++){
            sc->encbox_cur += traf->ivSize;
	    avail -= traf->ivSize;
            if (traf->flags & 0x002){
               //there will be subsambles
               int i;
               int entries = AV_RB16(sc->encbox_cur);
	       if (avail >= 2){
		 sc->encbox_cur += 2;
		 avail -= 2;
	       }else sc->encbox_ok = 0;
               for (i = 0; i < entries && avail >= 6; ++i){
                  sc->encbox_cur += 6;
		  avail -= 6;
               }
               if (i != entries) sc->encbox_ok = 0;
            }
         }
         if (i != fr->cur_sample) sc->encbox_ok = 0;
       }else if (sc->encbox_ok && sc->encbox_data){
          LOGE("starting at beginning of fragment, setting encbox cur\n");
          sc->encbox_cur = sc->encbox_data;
       }
       *frag = fr;
    }else{
       sample = av_index_search_timestamp(st, timestamp, flags);
       LOGE("mov stream %d not fragmented, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
       if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
          sample = 0;
       if (sample < 0) /* not sure what to do */
          return -1;
       sc->current_sample = sample;
       LOGD("stream %d, found sample %d\n", st->index, sc->current_sample);
       /* adjust ctts index */
       if (sc->ctts_data) {
          time_sample = 0;
          for (i = 0; i < sc->ctts_count; i++) {
             int next = time_sample + sc->ctts_data[i].count;
             if (next > sc->current_sample) {
                sc->ctts_index = i;
                sc->ctts_sample = sc->current_sample - time_sample;
                break;
             }
             time_sample = next;
          }
       }
    }
    
   return sample;
}

static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags){
    AVStream *st;
    int64_t seek_timestamp, timestamp;
    int sample;
    int i;
    MOVFragment *frag = NULL;

    if (stream_index >= s->nb_streams)
        return -1;
    if (sample_time < 0)
        sample_time = 0;

    st = s->streams[stream_index];
    sample = mov_seek_stream(s, st, sample_time, flags, &frag);
    if (sample < 0)
        goto fail;

    /* adjust seek timestamp to found sample timestamp */
    if (frag)
       seek_timestamp = frag->index_entries[sample].timestamp;
    else
       seek_timestamp = st->index_entries[sample].timestamp;

    for (i = 0; i < s->nb_streams; i++) {
        st = s->streams[i];
        if (stream_index == i)
            continue;

        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
        if (mov_seek_stream(s, st, timestamp, flags, &frag) < 0){
           LOGE("could not seek one of the other streams\n");
           goto fail;
        }
    }
    return 0;
    
    fail:
//     if (((MOVContext*)s->priv_data)->last_dts != sample_time){
//       LOGE("failed to seek one stream, revert to %lld\n", ((MOVContext*)s->priv_data)->last_dts);
//       st = s->streams[stream_index];
//       olddts = av_rescale_q(((MOVContext*)s->priv_data)->last_dts, st->time_base, AV_TIME_BASE_Q);
//       mov_read_seek(s, stream_index, olddts, flags);
//     }
    return -1;
}

static int mov_read_close(AVFormatContext *s){
    MOVContext *mov = s->priv_data;
    int i, j;

    if (mov->drm && mov->drmContext){
       mov->drm->release(mov->drmState, mov->drmContext);
    }
    mov->drm = NULL;
    mov->drmContext = NULL;
    mov->drmState = NULL;
    for (i = 0; i < s->nb_streams; i++) {
        AVStream *st = s->streams[i];
        MOVStreamContext *sc = st->priv_data;

        av_freep(&sc->ctts_data);
    sc->ctts_alloc = 0;
        for (j = 0; j < sc->drefs_count; j++) {
            av_freep(&sc->drefs[j].path);
            av_freep(&sc->drefs[j].dir);
        }
        av_freep(&sc->drefs);
        if (sc->pb && sc->pb != s->pb)
            avio_close(sc->pb);

        LOGE("freeing encbox data\n");
        if (sc->encbox_data){
            av_freep(&sc->encbox_data);
        }
//         if (sc->traf_data){
//      av_freep(&sc->traf_data);
//  }
//  sc->traf_alloc = 0;
//  sc->traf_count = 0;
     if(sc->first_frag){
     MOVFragment *tmp = sc->first_frag;
     while (tmp){
        sc->current_frag = tmp;
        tmp = tmp->next;
        if (sc->current_frag->ctts_data){
           av_free(sc->current_frag->ctts_data);
        }
        if (sc->current_frag->index_entries){
           av_free(sc->current_frag->index_entries);
        }
        av_free(sc->current_frag);
     }
}
    }


    if (mov->dv_demux) {
        for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
            av_freep(&mov->dv_fctx->streams[i]->codec);
            av_freep(&mov->dv_fctx->streams[i]);
        }
        av_freep(&mov->dv_fctx);
        av_freep(&mov->dv_demux);
    }

    av_freep(&mov->trex_data);

    return 0;
}

AVInputFormat ff_mov_demuxer = {
    .name = "mov,mp4,m4a,3gp,3g2,mj2",
    .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
    .priv_data_size = sizeof(MOVContext),
    .read_probe = mov_probe,
    .read_header = mov_read_header,
    .read_packet = mov_read_packet,
    .read_close = mov_read_close,
    .read_seek = mov_read_seek,
    .flags          = AVFMT_NO_BYTE_SEEK,
};
