/*
    libMakeMKV - MKV multiplexer library

    Copyright (C) 2007-2013 GuinpinSoft inc <libmkv@makemkv.com>

    This library 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.

    This library 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 this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/
#include <libmkv/libmkv.h>
#include <libmkv/internal.h>
#include <libmkv/ebmlwrite.h>
#include <lgpl/cassert>
#include <exception>
#include <list>
#include <lgpl/sstring.h>
#include <time.h>
#include <lgpl/world.h>

#define TIMECODE_SCALE              1000000
#define MAX_TIMECODE_SIZE_BYTES     6
#define MAX_TIMECODE                ((((uint64_t)1)<<(8*MAX_TIMECODE_SIZE_BYTES))-1)
#define AUTO_DURATION_TIMECODE      4500000000ll
#define BAD_TIMECODE                ((1ll<<62)+1)

#define CNZ(x) if (!(x)) { throw mkv_error_exception( "Error in " #x ); };

template <class Tv,class Te>
static inline Tv& GetChild(EbmlMaster *node)
{
    return * (static_cast<Tv *>(&GetChild<Te>( *node )));
}

template <class Tv,class Te>
static inline Tv& GetChild(EbmlMaster &node)
{
    return GetChild<Tv,Te>(&node);
}

template <class Te> class NoDefault : public Te
{
    bool IsDefaultValue() const { return false; };
};

static inline int64_t ScaleTimecode(int64_t UnscaledTimecode)
{
    return UnscaledTimecode / TIMECODE_SCALE;
}

static inline int64_t TimecodeFromClock(int64_t MkvClockTimecode)
{
    return ((MkvClockTimecode*25)/27);
}

static KaxSeek* CreateSeekEntry(KaxSeekHead& Seek,const EbmlId& aId)
{
    KaxSeek & aNewPoint = AddNewChild<KaxSeek>(Seek);

    // add the informations to this element
    KaxSeekPosition & aNewPos = GetChild<KaxSeekPosition>(aNewPoint);
    EbmlUInteger * pNewPos = static_cast<EbmlUInteger *>(&aNewPos);
    pNewPos->SetDefaultSize(8);
    *pNewPos = 0;

    KaxSeekID & aNewID = GetChild<KaxSeekID>(aNewPoint);
    binary ID[4];
    aId.Fill(ID);
    aNewID.CopyBuffer(ID, EBML_ID_LENGTH(aId));
    return &aNewPoint;
}

template <class Te>
static inline KaxSeek* AddSeekEntry(KaxSeekHead& Seek)
{
    return CreateSeekEntry(Seek,EBML_ID(Te));
}

static inline void UpdateSeekEntry(KaxSeek* Seek,IOCallback &File,const EbmlElement & aElt, const KaxSegment & ParentSegment)
{
    GetChild<EbmlUInteger,KaxSeekPosition>(Seek) = ParentSegment.GetRelativePosition(aElt);
    GetChild<KaxSeekPosition>(*Seek).OverwriteData(File,true);
}

static inline void VoidElement(EbmlMaster* Element,IOCallback &File)
{
    EbmlVoid v;
    CNZ(v.Overwrite(*Element,File));

    uint64 CurrentPosition = File.getFilePointer();
    File.setFilePointer(v.GetElementPosition()+v.HeadSize());
    CNZ(v.RenderData(File,true));
    File.setFilePointer(CurrentPosition);
}

static void OverwriteIntegerData(IOCallback & output, uint64_t Value, uint64_t Position, unsigned int Size)
{
	binary FinalData[8]; // we don't handle more than 64 bits integers
	
	uint64 TempValue = Value;
	for (unsigned int i=0; i<Size;i++) {
		FinalData[Size-i-1] = TempValue & 0xFF;
		TempValue >>= 8;
	}

	uint64 CurrentPosition = output.getFilePointer();
	output.setFilePointer(Position);
	output.writeFully(FinalData,Size);
	output.setFilePointer(CurrentPosition);
}

static void FinishCluster(KaxCluster *cluster,IOCallback *File,KaxSegment *Segment);

static bool AtKeyFrame(IMkvTrack *Input)
{
    bool rtn = false;
    for (unsigned int i=0;i<Input->MkvGetStreamCount();i++)
    {
        IMkvFrameSource *p;
        p = Input->MkvGetStream(i);

        if (false==p->FetchFrames(1)) return false;
        if (0==p->GetAvailableFramesCount()) continue;

        if (false==p->PeekFrame(0)->keyframe()) return false;
    }

    return true;
}

static bool AtClusterStart(IMkvTrack *Input)
{
    bool rtn = false;
    for (unsigned int i=0;i<Input->MkvGetStreamCount();i++)
    {
        IMkvFrameSource *p;
        p = Input->MkvGetStream(i);

        if (false==p->FetchFrames(1)) return false;
        if (0==p->GetAvailableFramesCount()) continue;

        if (false==p->PeekFrame(0)->cluster_start()) return false;
    }

    return true;
}

static int64_t GetClusterTimecode(IMkvTrack *Input)
{
    int64_t rtn = -1;
    for (unsigned int i=0;i<Input->MkvGetStreamCount();i++)
    {
        IMkvFrameSource *p;
        unsigned int frameCount;

        p = Input->MkvGetStream(i);

        if (false==p->FetchFrames(1)) return false;

        frameCount = p->GetAvailableFramesCount();

        if (i==0)
        {
            if (frameCount>16) frameCount=16;
        } else {
            if (frameCount>2) frameCount=2;
        }

        for (unsigned int j=0;j<frameCount;j++)
        {
            int64_t ft;

            ft = p->PeekFrame(j)->timecode;

            MKV_ASSERT(ft!=-1);

            if (rtn==-1) rtn = ft;

            if (ft<rtn) rtn=ft;
        }
    }

    MKV_ASSERT(rtn!=-1);

    return rtn;
}

static UTFstring UTF8string(const char *str)
{
    UTFstring rtn;

    rtn.SetUTF8(str);

    return rtn;
}

static uint64_t Rand64()
{
    uint64_t value;
    for (unsigned int k=0;k<sizeof(value);k++)
    {
        ((uint8_t*)&value)[k]=lgpl_get_random_byte();
    }
    return value;
}

class CChapters
{
private:
    KaxChapters         m_Chapters;
    std::vector<KaxChapterAtom*>    m_ChapterMarks;
    std::vector<KaxChapterAtom*>    m_Atoms;
    unsigned int        m_RealCount;
    bool                m_DoRender;
    IMkvTitleInfo*      m_TitleInfo;
    MkvFormatInfo*      m_FormatInfo;
public:
    CChapters(IMkvTitleInfo* TitleInfo,MkvFormatInfo* FormatInfo) 
        : m_RealCount(0) , m_TitleInfo(TitleInfo) , m_FormatInfo(FormatInfo)
    {
        Init();
    }
    void Init()
    {
        MkvChapterType  ctype;
        MkvChapterInfo  ti;
        unsigned int chap_count = m_TitleInfo->GetChapterCount();

        m_DoRender=false;

        if (chap_count==0) return;

        memset(&ti,0,sizeof(ti));
        m_TitleInfo->GetChapterInfo(&ti,0);
        ctype = ti.type;

        // verify type
        for (unsigned int i=0;i<chap_count;i++)
        {
            memset(&ti,0,sizeof(ti));
            m_TitleInfo->GetChapterInfo(&ti,i);
            if (ti.type!=ctype)
            {
                throw mkv_error_exception("Mixed chapter types are not supported (yet?).");
            }
        }

        m_Atoms.reserve(chap_count+1);

        switch(ctype)
        {
        case mccChapterMark:
            ReserveChapterMarks(1+chap_count);
            SetEmptyChapterName(m_ChapterMarks[0],0);
            for (unsigned int i=0;i<chap_count;i++)
            {
                memset(&ti,0,sizeof(ti));
                m_TitleInfo->GetChapterInfo(&ti,i);
                if (ti.name_count)
                {
                    for (unsigned int j=0;j<ti.name_count;j++)
                    {
                        SetChapterName(m_ChapterMarks[i+1],ti.name_lang[j],ti.name_text[j]);
                    }
                } else {
                    SetEmptyChapterName(m_ChapterMarks[i+1],i+1);
                }
            }
            m_DoRender = (chap_count>0);
            break;
        case mccTimecode:
            {
                unsigned int nameIndex = 1;
                KaxEditionEntry &edit = CreateEdition();
                uint64_t nextTimecode;

                for (unsigned int i=0;i<chap_count;i++)
                {
                    memset(&ti,0,sizeof(ti));
                    m_TitleInfo->GetChapterInfo(&ti,i);

                    if ((i+1)==chap_count)
                    {
                        nextTimecode = 0;
                    } else {
                        MkvChapterInfo  nc;
                        memset(&nc,0,sizeof(nc));
                        m_TitleInfo->GetChapterInfo(&nc,i+1);
                        nextTimecode = nc.position.time_c;
                    }

                    if (i==0)
                    {
                        if (IsVerySmallTimecode(ti.position.time_c))
                        {
                            ti.position.time_c=0;
                        } else {
                            if (m_FormatInfo->profile.insertFirstChapter00IfMissing)
                            {
                                KaxChapterAtom& first_atom = AddNewChild<KaxChapterAtom>(edit);
                                GetChild<EbmlUInteger,KaxChapterUID>( first_atom ) = Rand64();
                                GetChild<EbmlUInteger,KaxChapterTimeStart>( first_atom ) = 0;
                                GetChild<EbmlUInteger,KaxChapterTimeEnd>( first_atom ) = TimecodeFromClock(ti.position.time_c);;
                                SetEmptyChapterName(&first_atom,0);
                                m_RealCount++;
                                m_Atoms.push_back(&first_atom);
                            }
                        }
                    }

                    KaxChapterAtom& atom = AddNewChild<KaxChapterAtom>(edit);
                    GetChild<EbmlUInteger,KaxChapterUID>( atom ) = Rand64();
                    GetChild<EbmlUInteger,KaxChapterTimeStart>( atom ) = TimecodeFromClock(ti.position.time_c);
                    GetChild<EbmlUInteger,KaxChapterTimeEnd>( atom ) = TimecodeFromClock(nextTimecode);
                    if (0==nextTimecode)
                    {
                        GetChild<EbmlUInteger,KaxChapterTimeEnd>( atom ).SetDefaultSize(MAX_TIMECODE_SIZE_BYTES);
                    }

                    if (ti.name_count)
                    {
                        for (unsigned int j=0;j<ti.name_count;j++)
                        {
                            SetChapterName(&atom,ti.name_lang[j],ti.name_text[j]);
                        }
                    } else {
                        SetEmptyChapterName(&atom,nameIndex);
                    }
                    nameIndex++;
                    m_RealCount++;
                    m_Atoms.push_back(&atom);
                }
            }
            m_DoRender = (m_RealCount>1);
            break;
        default:
            throw mkv_error_exception("Unsupported chapter type");
            break;
        }
    }
    void Render(IOCallback &File,KaxSeek* Seek,const KaxSegment & FileSegment)
    {
        if (m_DoRender)
        {
            CNZ(m_Chapters.Render(File,true));
            UpdateSeekEntry(Seek,File,m_Chapters,FileSegment);
        } else {
            VoidElement(Seek,File);
        }
    }
    void AddChapterMark(uint64_t Timecode,IOCallback &File)
    {
        if (!m_DoRender) return;

        MKV_ASSERT(m_RealCount < m_ChapterMarks.size() );
        MKV_ASSERT(Timecode < MAX_TIMECODE);

        if (m_RealCount==0)
        {
            MKV_ASSERT( m_ChapterMarks.size() >= 2 );

            if (m_FormatInfo->profile.insertFirstChapter00IfMissing)
            {
                if (IsVerySmallTimecode(Timecode))
                {
                    m_ChapterMarks[0]->VoidMe(File);
                    Timecode = 0;
                } else {
                    GetChild<EbmlUInteger,KaxChapterTimeStart>( *(m_ChapterMarks[0]) ) = 0;
                    GetChild<EbmlUInteger,KaxChapterTimeEnd>( *(m_ChapterMarks[0]) ) = TimecodeFromClock(Timecode);
                    CNZ(m_ChapterMarks[0]->OverwriteData(File,true));
                    m_Atoms.push_back(m_ChapterMarks[0]);
                }
            } else {
                m_ChapterMarks[0]->VoidMe(File);
            }
            m_RealCount=1;
        }

        if (m_RealCount>1)
        {
            GetChild<EbmlUInteger,KaxChapterTimeEnd>( *(m_ChapterMarks[m_RealCount-1]) ) = TimecodeFromClock(Timecode);
            CNZ(m_ChapterMarks[m_RealCount-1]->OverwriteData(File,true));
        }
        GetChild<EbmlUInteger,KaxChapterTimeStart>( *(m_ChapterMarks[m_RealCount]) ) = TimecodeFromClock(Timecode);
        CNZ(m_ChapterMarks[m_RealCount]->OverwriteData(File,true));
        m_Atoms.push_back(m_ChapterMarks[m_RealCount]);
        m_RealCount++;
    }
    void Finalize(IOCallback &File,KaxSeek* Seek,uint64_t Duration)
    {
        if (!m_DoRender) return;

        if (m_RealCount<2)
        {
            CNZ(m_Chapters.VoidMe(File));
            VoidElement(Seek,File);
            return;
        }

        if (!m_ChapterMarks.empty())
        {
            for (unsigned int i=m_RealCount;i<m_ChapterMarks.size();i++)
            {
                CNZ(m_ChapterMarks[i]->VoidMe(File));
            }
        }

        unsigned int lastChapterId = (unsigned int)(m_Atoms.size()-1);
        while(lastChapterId!=0)
        {
            uint64_t chapterTime;

            chapterTime = GetChild<EbmlUInteger,KaxChapterTimeStart>( *m_Atoms[lastChapterId] );

            if (chapterTime<Duration) break;

            lastChapterId--;
        }

        GetChild<EbmlUInteger,KaxChapterTimeEnd>( *m_Atoms[lastChapterId] ) = TimecodeFromClock(Duration);
        CNZ(m_Atoms[lastChapterId]->OverwriteData(File,true));

        for (unsigned int i=(lastChapterId+1);i<m_Atoms.size();i++)
        {
            CNZ(m_Atoms[i]->VoidMe(File));
        }
    }
    static bool IsVerySmallTimecode(uint64_t Timecode)
    {
        static const uint64_t SmallTimecode = 108000000ll;  // 0.1 sec
        return (Timecode<=SmallTimecode);
    }
private:
    void SetChapterName(KaxChapterAtom* atom,const char *lang,const mkv_utf8_t* name)
    {
        char langBuf[4];
        if (m_FormatInfo->profile.useISO639Type2T)
        {
            strcpy(langBuf,lang);
            lgpl_iso6392T(langBuf);
            lang=langBuf;
        }
        KaxChapterDisplay& disp = GetChild<KaxChapterDisplay>(*atom);
        GetChild<EbmlString,KaxChapterLanguage>(disp) = lang;
        GetChild<EbmlUnicodeString,KaxChapterString>(disp) = UTF8string(name);
    }
    void SetEmptyChapterName(KaxChapterAtom* atom,unsigned int Id)
    {
        char ChapterName[128];
        sprintf_s(ChapterName,128,"Chapter %02u",Id+0);
        SetChapterName(atom,"eng",ChapterName);
    }
    void ReserveChapterMarks(unsigned int Count)
    {
        if (0==Count) return;

        m_ChapterMarks.resize(Count);

        KaxEditionEntry &edit = CreateEdition();

        for (unsigned int i=0;i<Count;i++)
        {
            m_ChapterMarks[i] = & AddNewChild<KaxChapterAtom>(edit);
            GetChild<EbmlUInteger,KaxChapterUID>( *(m_ChapterMarks[i]) ) = Rand64();

            GetChild<EbmlUInteger,KaxChapterTimeStart>( *(m_ChapterMarks[i]) ) = 0;
            GetChild<EbmlUInteger,KaxChapterTimeStart>( *(m_ChapterMarks[i]) ).SetDefaultSize(MAX_TIMECODE_SIZE_BYTES);
            GetChild<EbmlUInteger,KaxChapterTimeEnd>( *(m_ChapterMarks[i]) ) = 0;
            GetChild<EbmlUInteger,KaxChapterTimeEnd>( *(m_ChapterMarks[i]) ).SetDefaultSize(MAX_TIMECODE_SIZE_BYTES);
        }
    }
    KaxEditionEntry& CreateEdition()
    {
        KaxEditionEntry &edit = GetChild<KaxEditionEntry>(m_Chapters);
        GetChild<EbmlUInteger,KaxEditionFlagDefault>(edit) = 1;
        GetChild<EbmlUInteger,KaxEditionUID>(edit) = Rand64();

        return edit;
    }
};

static bool CompareTimecode(int64_t Timecode1,int64_t Timecode2)
{
    int64_t Diff;
    if (Timecode1>Timecode2)
    {
        Diff = Timecode1 - Timecode2;
    } else {
        Diff = Timecode2 - Timecode1;
    }
    return (Diff<3);
}

static bool IsFirstTrackOfType(IMkvTrack *Input,MkvTrackType Type,unsigned int Id)
{
    MkvTrackInfo ti;

    for (unsigned int i=0;i<Input->MkvGetStreamCount();i++)
    {
        memset(&ti,0,sizeof(ti));
        if (false==Input->MkvGetStream(i)->UpdateTrackInfo(&ti))
        {
            throw mkv_error_exception("UpdateTrackInfo failed");
        }
        if (ti.type!=Type) continue;
        return (Id==i);
    }
    return false;
}

class MyMkvTrackInfo
{
public:
    MkvTrackInfo    info;
    uint64_t        duration_pos;
    uint64_t        duration_time;
    uint64_t        refs[2];
    unsigned int    duration_size;
    unsigned int    frame_count;
    unsigned int    compression_type;
    unsigned int    compression_level;
};

class MyDataBuffer : public DataBuffer
{
private:
    void*   ref;
public:
    MyDataBuffer(IMkvChunk* aChunk,unsigned int aOffset=0);
private:
    bool FreeBuffer() const
    {
        lgpl_free_chunk_ref(ref);
        return true;
    }
    static bool MyFreeBufferStatic(const DataBuffer & aBuffer)
    {
        const DataBuffer* p = &aBuffer;
        const MyDataBuffer* pm = static_cast<const MyDataBuffer*>(p);
        return pm->FreeBuffer();
    }
};

MyDataBuffer::MyDataBuffer(IMkvChunk* aChunk,unsigned int aOffset)
 : DataBuffer((binary*)aChunk->get_data()+aOffset,aChunk->get_size()-aOffset,MyFreeBufferStatic)
{
    ref = aChunk->get_ref();
}

static void RenderVoid(IOCallback &File,unsigned int Size)
{
    if (Size==0) return;

    if ( (Size>4) && (Size<30000) )
    {
        EbmlVoid v;
        v.SetSize(Size-3);
        v.SetSizeLength(2);
        CNZ(v.Render(File,true));
        return;
    }

    throw mkv_error_exception("RenderVoid failed");
}

static DataBuffer* GetDataBuffer(IMkvChunk* frame,MyMkvTrackInfo* track)
{
    DataBuffer* mkv_buffer;

    if (track->compression_type==MKV_TRACK_COMPRESSION_HEADERS)
    {
        MKV_ASSERT(frame->get_size()>track->info.header_comp_size);
        if (memcmp(frame->get_data(),track->info.header_comp_data,track->info.header_comp_size))
        {
            throw mkv_error_exception("header_comp_data missing");
        }
        mkv_buffer = new MyDataBuffer(frame,track->info.header_comp_size);
    } else {
        CNZ(frame->compress_start(track->compression_type,track->compression_level));
        CNZ(frame->compress_wait());
        mkv_buffer = new MyDataBuffer(frame);
    }
    return mkv_buffer;
}

static void MkvCreateFileInternal(IOCallback &File,IMkvTrack *Input,IMkvTitleInfo* TitleInfo,MkvFormatInfo* FormatInfo,const char *WritingApp)
{
    EbmlHead FileHead;

    EDocType & MyDocType = GetChild<EDocType>(FileHead);
    *static_cast<EbmlString *>(&MyDocType) = "matroska";

    EDocTypeVersion & MyDocTypeVer = GetChild<EDocTypeVersion>(FileHead);
    *(static_cast<EbmlUInteger *>(&MyDocTypeVer)) = MATROSKA_VERSION;

    EDocTypeReadVersion & MyDocTypeReadVer = GetChild<EDocTypeReadVersion>(FileHead);
    *(static_cast<EbmlUInteger *>(&MyDocTypeReadVer)) = 2;

    CNZ(FileHead.Render(File,true));

    // objects
    KaxSegment FileSegment;

    KaxCues AllCues;
    AllCues.SetGlobalTimecodeScale(TIMECODE_SCALE);

    CChapters Chapters(TitleInfo,FormatInfo);

    // start render
    uint64_t SegmentSize = FileSegment.WriteHead(File, 8);

    KaxSeekHead & MetaSeek = AddNewChild<KaxSeekHead>(FileSegment);

    KaxSeek* seek_infos = AddSeekEntry<KaxInfo>(MetaSeek);
    KaxSeek* seek_tracks = AddSeekEntry<KaxTracks>(MetaSeek);
    KaxSeek* seek_cues = AddSeekEntry<KaxCues>(MetaSeek);
    KaxSeek* seek_chap = AddSeekEntry<KaxChapters>(MetaSeek);
    KaxSeek* seek_att = AddSeekEntry<KaxAttachments>(MetaSeek);

    CNZ(MetaSeek.Render(File));

    MkvTitleInfo    titleInfo;

    memset(&titleInfo,0,sizeof(titleInfo));
    TitleInfo->GetMkvTitleInfo(&titleInfo);

    // fill the mandatory Info section
    KaxInfo & MyInfos = GetChild<KaxInfo>(FileSegment);

    GetChild<EbmlUInteger,KaxTimecodeScale>(MyInfos) = TIMECODE_SCALE;
    GetChild<EbmlFloat,KaxDuration>(MyInfos) = (double)0;

    GetChild<EbmlUnicodeString,KaxMuxingApp>(MyInfos) = GetLibraryVersionString();
    GetChild<EbmlUnicodeString,KaxWritingApp>(MyInfos) = UTF8string(WritingApp);

    if (titleInfo.name)
    {
        GetChild<EbmlUnicodeString,KaxTitle>(MyInfos) = UTF8string(titleInfo.name);
    }

    uint8_t SegmentUid[16];
    for (unsigned int i=0;i<16;i++)
    {
        SegmentUid[i] = lgpl_get_random_byte();
    }
    GetChild<EbmlDate,KaxDateUTC>(MyInfos).SetEpochDate((uint32_t)time(NULL));
    GetChild<EbmlBinary,KaxSegmentUID>(MyInfos).CopyBuffer(SegmentUid, 16);

    RenderVoid(File,FormatInfo->debug.evoid[0]);
    CNZ(MyInfos.Render(File,true));


    // tracks
    KaxTracks & MyTracks = GetChild<KaxTracks>(FileSegment);

    std::vector<MyMkvTrackInfo> track_info;
    std::vector<KaxTrackEntry*> tracks;

    track_info.resize(Input->MkvGetStreamCount());
    tracks.resize(Input->MkvGetStreamCount());

    for (unsigned int i=0;i<Input->MkvGetStreamCount();i++)
    {
        MkvTrackInfo *ti;
        KaxTrackEntry *cur_track;
        unsigned int    track_default;

        ti = & track_info[i].info;
        track_info[i].frame_count = 0;
        track_info[i].duration_pos=0;
        track_info[i].refs[0]=BAD_TIMECODE;
        track_info[i].refs[1]=BAD_TIMECODE;

        memset(ti,0,sizeof(*ti));
        if (false==Input->MkvGetStream(i)->UpdateTrackInfo(ti))
        {
            throw mkv_error_exception("UpdateTrackInfo failed");
        }

        cur_track = & AddNewChild<KaxTrackEntry>(MyTracks);
        cur_track->SetGlobalTimecodeScale(TIMECODE_SCALE);

        tracks[i] = cur_track;

        GetChild<EbmlUInteger,KaxTrackNumber>(cur_track) = (i+1);
        GetChild<EbmlUInteger,KaxTrackUID>(cur_track) = (i+1);
        if (FormatInfo->debug.compatFlags&1)
        {
            GetChild<EbmlUInteger,KaxTrackUID>(cur_track).SetSizeLength(4);
        }

        track_type ttype;
        switch(ti->type)
        {
        case mttVideo : ttype = track_video; break;
        case mttAudio : ttype = track_audio; break;
        case mttSubtitle : ttype = track_subtitle; break;
        default: throw mkv_error_exception("bad track type");
        }

        GetChild<EbmlUInteger,KaxTrackType>(cur_track) = ttype;

        track_default = 0;

        if ( (ttype==track_audio) &&
            (FormatInfo->profile.setFirstAudioTrackAsDefault) &&
            IsFirstTrackOfType(Input,mttAudio,i) )
        {
            track_default = 1;
        }

        if ( (ttype==track_subtitle) && 
            (FormatInfo->profile.setFirstSubtitleTrackAsDefault) &&
            IsFirstTrackOfType(Input,mttSubtitle,i) )
        {
            track_default = 1;
        }

        GetChild<EbmlUInteger,KaxTrackFlagDefault>(cur_track) = track_default;

        if ( (!FormatInfo->profile.ignoreForcedSubtitlesFlag) &&
            (ttype==track_subtitle) &&
            ((ti->stream_flags&MKV_STREAM_FLAG_FORCED_SUBTITLE)>0) )
        {
            GetChild<EbmlUInteger,KaxTrackFlagForced>(cur_track) = 1;
        }

        if (NULL!=ti->lang)
        {
            char langBuf[4];
            strcpy(langBuf,ti->lang);
            if (FormatInfo->profile.useISO639Type2T)
            {
                lgpl_iso6392T(langBuf);
            }
            cur_track->PushElement(*new NoDefault<KaxTrackLanguage>);
            GetChild<EbmlString,KaxTrackLanguage>(cur_track) = langBuf;
        } else {
            if (FormatInfo->debug.compatFlags&1)
            {
                GetChild<EbmlString,KaxTrackLanguage>(cur_track) = "und";
            }
        }

        GetChild<EbmlString,KaxCodecID>(cur_track) = ti->codec_id;

        if (0!=ti->codec_private_size)
        {
            GetChild<EbmlBinary,KaxCodecPrivate>(cur_track).CopyBuffer(ti->codec_private,ti->codec_private_size);
        }

        if (0!=ti->default_duration)
        {
            GetChild<EbmlUInteger,KaxTrackDefaultDuration>(cur_track) = TimecodeFromClock(ti->default_duration);
        }

        GetChild<EbmlUInteger,KaxTrackMinCache>(cur_track) = ti->min_cache;

        if ( (NULL!=ti->name) && (0==(FormatInfo->debug.compatFlags&2)) )
        {
            UTFstring tmp;
            tmp = UTF8string(ti->name);
            GetChild<EbmlUnicodeString,KaxTrackName>(cur_track) = tmp;
        }

        GetChild<EbmlUInteger,KaxTrackFlagLacing>(cur_track) = (ti->use_lacing)?1:0;

        if (mttVideo==ti->type)
        {
            KaxTrackVideo*  vid_track = & GetChild<KaxTrackVideo>(*cur_track);

            GetChild<EbmlUInteger,KaxVideoPixelWidth>(vid_track) = ti->u.video.pixel_h;
            GetChild<EbmlUInteger,KaxVideoPixelHeight>(vid_track) = ti->u.video.pixel_v;

            GetChild<EbmlUInteger,KaxVideoDisplayWidth>(vid_track) = ti->u.video.display_h;
            GetChild<EbmlUInteger,KaxVideoDisplayHeight>(vid_track) = ti->u.video.display_v;
            if (FormatInfo->debug.compatFlags&1)
            {
                GetChild<KaxVideoDisplayWidth>(*vid_track).SetSizeLength(3);
                GetChild<KaxVideoDisplayHeight>(*vid_track).SetSizeLength(3);
            }

            GetChild<EbmlUInteger,KaxVideoDisplayUnit>(vid_track) = 0;


            if (ti->u.video.fps_n!=0)
            {
                char fps_string[128];

                fps_string[sizeof(fps_string)-1]=0;

                if (ti->u.video.fps_d==1)
                {
                    sprintf_s(fps_string,sizeof(fps_string),"%d",ti->u.video.fps_n);
                }
                else 
                {
                    int fps_1=ti->u.video.fps_n/ti->u.video.fps_d;
                    int64_t fps_2=( ( ((int64_t)ti->u.video.fps_n) * 10000) / ti->u.video.fps_d) - (((int64_t)fps_1)*10000);


                    while( ((fps_2%10)==0) && (fps_2!=0) )
                    {
                        fps_2/=10;
                    }

                    sprintf_s(fps_string,sizeof(fps_string),"%d.%d (%d/%d)",fps_1,((int)fps_2),ti->u.video.fps_n,ti->u.video.fps_d);
                }
            }
        }

        if (mttAudio==ti->type)
        {
            KaxTrackAudio*  aud_track = & GetChild<KaxTrackAudio>(*cur_track);

            GetChild<EbmlFloat,KaxAudioSamplingFreq>(aud_track) = ti->u.audio.sample_rate;
            GetChild<EbmlUInteger,KaxAudioChannels>(aud_track) = ti->u.audio.channels_count;
            if (0!=ti->u.audio.bits_per_sample)
            {
                if ( (!(FormatInfo->debug.compatFlags&1)) || strcmp(ti->codec_id,"A_DTS") )
                {
                    GetChild<EbmlUInteger,KaxAudioBitDepth>(aud_track) = ti->u.audio.bits_per_sample;
                }
            }
        }

        if (track_info[i].info.profile_track_info)
        {
            track_info[i].compression_type=track_info[i].info.profile_track_info->compressionType;
            track_info[i].compression_level=track_info[i].info.profile_track_info->compressionLevel;
        } else {
            track_info[i].compression_type=MKV_TRACK_COMPRESSION_NONE;
        }

        if ( (!ti->header_comp_size) && (track_info[i].compression_type==MKV_TRACK_COMPRESSION_HEADERS) )
        {
            track_info[i].compression_type=MKV_TRACK_COMPRESSION_NONE;
        }

        if (track_info[i].compression_type!=MKV_TRACK_COMPRESSION_NONE)
        {
            KaxContentEncodings &cs = GetChild<KaxContentEncodings>(*cur_track);
            KaxContentEncoding &ce = GetChild<KaxContentEncoding>(cs);
            KaxContentCompression &cc = GetChild<KaxContentCompression>(ce);

            cc.PushElement(*new NoDefault<KaxContentCompAlgo>);
            GetChild<EbmlUInteger,KaxContentCompAlgo>(cc) = track_info[i].compression_type;
            
            if (ti->header_comp_size)
            {
                GetChild<EbmlBinary,KaxContentCompSettings>(cc).CopyBuffer(ti->header_comp_data,ti->header_comp_size);
            }
        }
    }

    CNZ(MyTracks.Render(File));

    Chapters.Render(File,seek_chap,FileSegment);
    RenderVoid(File,FormatInfo->debug.evoid[1]);

    MkvAttachmentInfo   ainfo;
    if (TitleInfo->GetAttachmentCount())
    {
        KaxAttachments & MyAttachments = GetChild<KaxAttachments>(FileSegment);
        for (unsigned int i=0;i<TitleInfo->GetAttachmentCount();i++)
        {
            KaxAttached *pa;

            TitleInfo->GetAttachmentInfo(&ainfo,i);
            
            pa = & AddNewChild<KaxAttached>(MyAttachments);
            GetChild<EbmlUnicodeString,KaxFileName>(pa) = UTF8string(ainfo.name);
            GetChild<EbmlString,KaxMimeType>(pa) = ainfo.mime_type;
            GetChild<EbmlUInteger,KaxFileUID>(pa) = 1+i;
            GetChild<EbmlBinary,KaxFileData>(pa).CopyBuffer((const binary *)ainfo.data,ainfo.size);
        }
        CNZ(MyAttachments.Render(File));
        UpdateSeekEntry(seek_att,File,MyAttachments,FileSegment);
        MyAttachments.RemoveAll();
    } else {
        VoidElement(seek_att,File);
    }

    // finish all meta info
    UpdateSeekEntry(seek_infos,File,MyInfos,FileSegment);
    UpdateSeekEntry(seek_tracks,File,MyTracks,FileSegment);
    MyTracks.RemoveAll();

    KaxCluster *curr_cluster=NULL,*prev_cluster=NULL;
    int64_t cluster_timecode=0,cue_timecode=0,frame_timecode;
    int64_t max_duration=0;
    uint64_t prg_val=0;
    int64_t frame_end;
    bool cue_cluster=false;

    cue_timecode -= 9990000000ll;

    while(true)
    {
        int64_t min_timecode;
        unsigned int stream_id;
        IMkvFrameSource *stream;

        min_timecode=BAD_TIMECODE;

        for (unsigned int i=0;i<Input->MkvGetStreamCount();i++)
        {
            bool force_fetch;
            unsigned int frames_scan;

            force_fetch = ( (track_info[i].info.type==mttVideo) || (track_info[i].info.type==mttAudio) );

            if (false==Input->MkvGetStream(i)->FetchFrames(1,force_fetch))
            {
                throw mkv_error_exception("Error while reading input");
            }

            frames_scan = (track_info[i].info.type==mttVideo)?16:1;
            if (Input->MkvGetStream(i)->GetAvailableFramesCount()<frames_scan)
            {
                frames_scan = Input->MkvGetStream(i)->GetAvailableFramesCount();
            }
            for (unsigned int j=0;j<frames_scan;j++)
            {
                int64_t dts;

                IMkvChunk* tf = Input->MkvGetStream(i)->PeekFrame(j);

                dts = ScaleTimecode(TimecodeFromClock(tf->timecode)+(TIMECODE_SCALE/2));

                if ( (dts<min_timecode) )
                {
                    if (tf->timecode==-1) throw mkv_error_exception("Frame not timestamped");

                    min_timecode = dts;
                    stream_id = i;
                }
            }
            if (track_info[i].compression_type==MKV_TRACK_COMPRESSION_ZLIB)
            {
                frames_scan = Input->MkvGetStream(i)->GetAvailableFramesCount();
                for (unsigned int k=0;k<frames_scan;k++)
                {
                    CNZ(Input->MkvGetStream(i)->PeekFrame(k)->compress_start(
                        track_info[i].compression_type,
                        track_info[i].compression_level));
                }
            }
        }
        if (min_timecode==BAD_TIMECODE)
        {
            // no more frames
            break;
        }

        // update UI
        if (0==stream_id)
        {
            lgpl_update_current_progress(Input,&prg_val);
        }

        IMkvChunk*  frame,*prev_frame;

        stream = Input->MkvGetStream(stream_id); 
        frame = stream->PeekFrame(0);

        if (frame->chapter_mark())
        {
            // dvd-style position based chapters
            Chapters.AddChapterMark(frame->timecode,File);
        }

        bool new_cluster;

        new_cluster=false;
        if (NULL==curr_cluster)
        {
            new_cluster=true;
        } else {
            int64_t cluster_duration,cluster_size;

            cluster_duration = frame->timecode - cluster_timecode;
            cluster_size = File.getFilePointer() - curr_cluster->GetElementPosition();

            if (cluster_duration > 432000000ll)
            {
                if (AtKeyFrame(Input)) 
                {
                    new_cluster=true;
                }
            }
            if (cluster_duration > 864000000ll)
            {
                if (AtClusterStart(Input)) 
                {
                    new_cluster=true;
                }
            }
            if (cluster_size > (12*1024*1024))
            {
                if (AtClusterStart(Input)) 
                {
                    new_cluster=true;
                }
            }
        }

        if (new_cluster)
        {
            if (NULL!=curr_cluster)
            {
                FinishCluster(curr_cluster,&File,&FileSegment);
            }
            prev_cluster = curr_cluster;
            cue_cluster = false;
            curr_cluster = & AddNewChild<KaxCluster>(FileSegment);
            curr_cluster->SetSizeInfinite();
            curr_cluster->SetParent(FileSegment);

            if (FormatInfo->debug.compatFlags&1)
            {
                CNZ(curr_cluster->WriteHead(File, 3));
            } else {
                CNZ(curr_cluster->WriteHead(File, 4));
            }

            cluster_timecode = GetClusterTimecode(Input);

            curr_cluster->InitTimecode(ScaleTimecode(TimecodeFromClock(cluster_timecode)),TIMECODE_SCALE);

            GetChild<EbmlUInteger,KaxClusterTimecode>(curr_cluster) = ScaleTimecode(TimecodeFromClock(cluster_timecode));
            GetChild<KaxClusterTimecode>(*curr_cluster).Render(File);

            if (NULL!=prev_cluster)
            {
                GetChild<EbmlUInteger,KaxClusterPrevSize>(curr_cluster) = curr_cluster->GetElementPosition() - prev_cluster->GetElementPosition();
                GetChild<KaxClusterPrevSize>(*curr_cluster).Render(File);
            }
        }

        // have a frame and a cluster

        // update entire file duration
        frame_timecode = frame->timecode;
        frame_end=frame->timecode+frame->duration;
        if (frame_end>max_duration) max_duration = frame_end;

        unsigned int lacing_frames,fetch_frames,frames_count,same_frame_size;
        bool frame_keyframe,all_same;

        if (track_info[stream_id].info.use_lacing)
        {
            if (FormatInfo->debug.compatFlags&1)
            {
                lacing_frames = 8;
            } else {
                lacing_frames = (unsigned int)(108000000 / track_info[stream_id].info.default_duration);
            }
            if (lacing_frames>180)
            {
                lacing_frames = 180;
            }
            if (lacing_frames==0)
            {
                lacing_frames = 1;
                fetch_frames = 1;
            } else {
                fetch_frames=lacing_frames+1;
            }
        } else {
            lacing_frames = 1;
            fetch_frames = 1;
        }

        if (false==stream->FetchFrames(fetch_frames,true)) 
        {
            throw mkv_error_exception("Error while reading input");
        }

        frames_count = stream->GetAvailableFramesCount();

        if (frames_count>lacing_frames) frames_count=lacing_frames;

        MKV_ASSERT(frames_count>0);

        if (frames_count>1)
        {
            CNZ(frame->compress_start(track_info[stream_id].compression_type,track_info[stream_id].compression_level));
            CNZ(frame->compress_wait());
        }

        frame_keyframe = frame->keyframe();
        same_frame_size = frame->get_size();
        all_same = true;
        for (unsigned int i=1;i<frames_count;i++)
        {
            prev_frame = frame;
            frame=stream->PeekFrame(i);
            if (frame->keyframe()!=frame_keyframe)
            {
                frames_count=i;
                break;
            }
            if (frame->duration!=track_info[stream_id].info.default_duration)
            {
                frames_count=i;
                break;
            }
            if ( !CompareTimecode( prev_frame->timecode+prev_frame->duration , frame->timecode ))
            {
                frames_count=i;
                break;
            }

            CNZ(frame->compress_start(track_info[stream_id].compression_type,track_info[stream_id].compression_level));
            CNZ(frame->compress_wait());

            if (frame->get_size()!=same_frame_size)
            {
                all_same=false;
            }
        }

        frame = stream->PeekFrame(0);

        KaxBlockGroup       *blkg;
        KaxSimpleBlock      *blks;
        KaxInternalBlock    *blki;
        uint64_t            refs[2];

        blkg=NULL;
        blks=NULL;
        if (frame->old_block())
        {
            blkg = new KaxBlockGroup();
            blki = &(KaxInternalBlock&)(*blkg);
            blkg->SetParent(*curr_cluster);

            frames_count=1;

            DataBuffer* mkv_buffer = GetDataBuffer(frame,&track_info[stream_id]);
            CNZ(blkg->AddFrame( * (tracks[stream_id]) , TimecodeFromClock(frame->timecode)+(TIMECODE_SCALE/2) , *mkv_buffer));
            track_info[stream_id].frame_count++;

            if (frame->auto_duration())
            {
                blkg->SetBlockDuration( AUTO_DURATION_TIMECODE );
            } else {
                if ( (frame->duration != track_info[stream_id].info.default_duration) || (track_info[stream_id].info.type==mttVideo) )
                {
                    blkg->SetBlockDuration( TimecodeFromClock(frame->duration)+(TIMECODE_SCALE/2) );
                }
            }

            if (track_info[stream_id].info.type==mttVideo)
            {
                if (frame->discardable())
                {
                    refs[0]=track_info[stream_id].refs[0];
                    refs[1]=track_info[stream_id].refs[1];
                } else {
                    if (!frame->keyframe())
                    {
                        refs[0]=BAD_TIMECODE;
                        refs[1]=track_info[stream_id].refs[1];
                    } else {
                        refs[0]=BAD_TIMECODE;
                        refs[1]=BAD_TIMECODE;
                    }
                }
                if (frame->keyframe())
                {
                    track_info[stream_id].refs[0]=BAD_TIMECODE;
                    track_info[stream_id].refs[1]=frame->timecode;
                } else {
                    if (!frame->discardable())
                    {
                        track_info[stream_id].refs[0]=track_info[stream_id].refs[1];
                        track_info[stream_id].refs[1]=frame->timecode;
                    }
                }
                for (int nr=0;nr<2;nr++)
                {
                    if (refs[nr]!=BAD_TIMECODE)
                    {
                        KaxReferenceBlock & theRef = AddNewChild<KaxReferenceBlock>(*blkg);
                        int64_t refTimecode = ScaleTimecode(TimecodeFromClock(refs[nr])+(TIMECODE_SCALE/2));
                        refTimecode -= ScaleTimecode(TimecodeFromClock(frame->timecode)+(TIMECODE_SCALE/2));
                        theRef.SetReferencedTimecode(refTimecode);
                        theRef.SetParentBlock(*blkg);
                    }
                }
            }

            CNZ(blkg->Render(File));

            if (track_info[stream_id].duration_pos)
            {
                uint64_t duration = TimecodeFromClock(frame->timecode) - track_info[stream_id].duration_time;
                if (duration < AUTO_DURATION_TIMECODE)
                {
                    OverwriteIntegerData(File,ScaleTimecode(duration),track_info[stream_id].duration_pos,track_info[stream_id].duration_size);
                }
                track_info[stream_id].duration_pos = 0;
            }

            if (frame->auto_duration())
            {
                KaxBlockDuration & myDuration = GetChild<KaxBlockDuration>(*blkg);
                track_info[stream_id].duration_pos  = myDuration.GetElementPosition() + myDuration.HeadSize();
                track_info[stream_id].duration_size = (unsigned int) myDuration.GetSize();
                track_info[stream_id].duration_time = TimecodeFromClock(frame->timecode);
            }

        } else {
            blks = new KaxSimpleBlock();
            blki = &(KaxInternalBlock&)(*blks);
            blks->SetParent(*curr_cluster);
            blks->SetKeyframe(frame->keyframe());
            blks->SetDiscardable(frame->discardable());

            for (unsigned int i=0;i<frames_count;i++)
            {
                frame=stream->PeekFrame(i);

                DataBuffer* mkv_buffer = GetDataBuffer(frame,&track_info[stream_id]);
                CNZ(blks->AddFrame( * (tracks[stream_id]) , TimecodeFromClock(frame->timecode)+(TIMECODE_SCALE/2) , *mkv_buffer , all_same ? LACING_FIXED : LACING_EBML ));

                track_info[stream_id].frame_count++;
            }
            CNZ(blks->Render(File));
        }

        if ( (track_info[stream_id].info.type==mttVideo) && 
            frame->cluster_start() && 
            (!cue_cluster) &&
            ((frame_timecode-cue_timecode)>270000000ll) )
        {
            KaxCuePoint *cp = & AddNewChild<KaxCuePoint>(AllCues);
            cp->PositionSet(*blki,blkg,TIMECODE_SCALE);
            cue_timecode = frame_timecode;
            cue_cluster = true;
        }

        delete blks;
        delete blkg;

        for (unsigned int i=0;i<frames_count;i++)
        {
            stream->PopFrame();
        }
    }
    FinishCluster(curr_cluster,&File,&FileSegment);

    // update total duration
    GetChild<EbmlFloat,KaxDuration>(MyInfos) = (double) ScaleTimecode(TimecodeFromClock(max_duration));
    GetChild<KaxDuration>(MyInfos).OverwriteData(File,true);

    CNZ(AllCues.Render(File));
    UpdateSeekEntry(seek_cues,File,AllCues,FileSegment);

    Chapters.Finalize(File,seek_chap,max_duration);

    // delete empty tracks
    for (unsigned int i=0;i<Input->MkvGetStreamCount();i++)
    {
        if (track_info[i].frame_count>0) continue;
        VoidElement(tracks[i],File);
        my_world()->uc_emptytrack(Input,i,&track_info[i].info);
    }

    // end

    // Set the correct size for the segment.
    CNZ(FileSegment.ForceSize(File.getFilePointer() - ( FileSegment.GetElementPosition() + FileSegment.HeadSize() ) ));
    CNZ(FileSegment.OverwriteHead(File));
}

static void FinishCluster(KaxCluster *cluster,IOCallback *File,KaxSegment *Segment)
{
    // add position info 
    GetChild<EbmlUInteger,KaxClusterPosition>(cluster) =  
        cluster->GetElementPosition() - ( Segment->GetElementPosition() + Segment->HeadSize() );
    GetChild<KaxClusterPosition>(*cluster).Render(*File);

    // correct size
    CNZ(cluster->ForceSize(File->getFilePointer() - ( cluster->GetElementPosition() + cluster->HeadSize() ) ));
    CNZ(cluster->OverwriteHead(*File));
}

extern "C"
bool __cdecl MkvCreateFile(IMkvWriteTarget* Output,IMkvTrack *Input,const char *WritingApp,IMkvTitleInfo* TitleInfo,MkvFormatInfo* FormatInfo) throw()
{
    CEbmlWrite  wrt(Output);
    try 
    {
        MkvCreateFileInternal(wrt,Input,TitleInfo,FormatInfo,WritingApp);
        return true;
    } catch(std::exception &Ex)
    {
        // no memory allocations here
        if (Ex.what()[0]!='$')
        {
            char tstr[512];
            strcpy(tstr,"Exception: ");
            strncat(tstr,Ex.what(),sizeof(tstr)-1);
            tstr[sizeof(tstr)-1]=0;
            lgpl_trace(tstr);
        }
    } catch(...)
    {
        lgpl_trace("Exception: unknown");
    }
    return false;
}

