#include <QTime>
#include "converter.h"
#include "loadershell.h"

using namespace std;

QString Converter::m_outputName;
QFile Converter::fileOutput;

Converter::Converter(QObject *parent) : QThread(parent)
{
    m_bytesTotal = 0;
    m_bytesReceived = 0;
    hasAudio = false;
    hasVideo = false;
    bufferData = nullptr;
    bufferData_input = nullptr;
    avio_ctx = nullptr;
    avio_ctx_input = nullptr;
    fmt_ctx = nullptr;
    ofmt_ctx = nullptr;

    streamAudio = nullptr;
    out_stream_audio = nullptr;
    decoderAudio_ctx = nullptr;
    encoderAudio_ctx = nullptr;
    decoderAudio = nullptr;
    encoderAudio = nullptr;
    frame = nullptr;
    swrContext = nullptr;
    output_audio_frame = nullptr;
    output_audio_packet = nullptr;
    audioSampleBuffer = nullptr;

    streamVideo = nullptr;
    out_stream_video = nullptr;
    decoderVideo_ctx = nullptr;
    encoderVideo_ctx = nullptr;
    decoderVideo = nullptr;
    encoderVideo = nullptr;

    audio_stream_index = -1;
    video_stream_index = -1;
    output_audio_stream_index = -1;
    output_video_stream_index = -1;

    m_handle = Q_NULLPTR;
    m_bytesTotal = 0;
    m_bytesReceived = 0;
    m_downloadProgress = 0.0f;

    connect(this, &Converter::finished, &LoaderShell::get(), &LoaderShell::convertFinished);
    connect(this, &Converter::finished, this, &QObject::deleteLater);
}

void Converter::setTorrentHandle(TorrentHandle *value) {
    if(m_handle != value) {
        m_handle = value;
        if(m_handle) {
            setBytesTotal(m_handle->bytesTotal());
        }
    }
}

void Converter::run()
{
    if(!m_handle) {
        qDebug() << "Error: Converter::run handle is NULL";
        return;
    }
    if(m_inputName.isEmpty()) return;
    if(m_outputName.isEmpty()) return;
    while(false == QFileInfo::exists(m_inputName) ||
          m_downloadProgress < 0.02f ||
          !m_handle->firstLastBlocksFinsihed())
    {
        sleep(5);
    }

    qDebug() << "Converter wait m_downloadProgress="<<m_downloadProgress
             << "file::exists(" << m_inputName
             << ")=" << QFileInfo::exists(m_inputName);

//    QTime time;
//    time.start();

    logFile.open("log.txt");
    int ret = 0;

    qDebug() << "inputName="<<m_inputName;
    qDebug() << "m_outputName="<<m_outputName;

    if (open(m_inputName.toStdString().c_str()) != 0 ||
        open_destination (m_outputName.toStdString().c_str()) != 0)
    {
        return;
    }

    logFile << "\n"<< "open files end";

    transcode();
    logFile << "\n"<< "transcode end";

    writeBuffer(bufferData);


    avformat_close_input(&fmt_ctx);
    avformat_free_context(ofmt_ctx);

    //close file
    fileOutput.close();


//    av_freep(&stream_mapping);

    logFile << "\n"<< "close end";
//    qDebug() << "time.elapsed(ms) = "<< time.elapsed();
//    qDebug() << "time.elapsed = "<< QTime::fromMSecsSinceStartOfDay(time.elapsed());

    qDebug() << "\n"<< "close end";
}


bool Converter::writeBuffer(BufferData *bufferData)
{
    if(!bufferData) {
        qDebug()<< "writeBuffer bufferData is NULL";
        return false;
    }

//    qDebug() << "isOpen ? "<< fileOutput.isOpen();
    if(!fileOutput.isOpen()) {
        fileOutput.setFileName(m_outputName);
        if( !fileOutput.open(QIODevice::WriteOnly | QIODevice::Truncate) ) {
            return -1;
        }
    }

    LoaderShell::get().sendData(bufferData->data, bufferData->fullsize);
    fileOutput.write(bufferData->data);
    bufferData->writeSize = 0;
    bufferData->data.clear();

    qDebug()<<"FILE SIZE = " << fileOutput.size()/1024/1024;
    return true;
}


int Converter::read_packet_to_buffer(void *opaque, uint8_t *buf, int buf_size)
{
        qDebug() << "read_packet_to_buffer buf_size"<<buf_size;
        BufferData *bufData = static_cast<BufferData*>(opaque);

        if(!bufData) {
            qDebug()<< "Error bufferData NULL";
            return buf_size;
        }
        bufData->fullsize += buf_size;
        qDebug()<<"read fullsize="<<bufData->fullsize/1024/1024 << "Mb";

        bufData->data.append((const char*)buf, buf_size);
        return buf_size;
}

int Converter::write_packet_to_buffer(void *opaque, uint8_t *buf, int buf_size)
{
//    qDebug() << "write_packet_to_buffer buf_size"<<buf_size;
    BufferData *bufData = static_cast<BufferData*>(opaque);

    if(!bufData) {
        qDebug()<< "Error bufferData NULL";
        return buf_size;
    }
    bufData->fullsize += buf_size;
    bufData->writeSize += buf_size;
//    qDebug()<<"write fullsize="<<bufData->fullsize/1024/1024 << "Mb";
    //    bufferData->stream << "write: "<<buf_size <<" full: " << bufferData->fullsize << endl;

    bufData->data.append((const char*)buf, buf_size);
    qDebug() << "writeBuffer = "<<QByteArray((const char*)buf, buf_size).toHex();


//    bufferData->stream << "write: "<<buf_size <<" full: " << bufferData->data.size() << endl;

    if(bufData->writeSize >= 1024*1024) {
        qDebug() << "writeFIle";
        writeBuffer(bufData);
    }

    return buf_size;
}


void Converter::createBufferInput(const char* input_filename)
{
    //---------------------- BUFFER -------------------------
    qDebug() << "createBufferInput "<<input_filename;
    uint8_t* buffer = nullptr;
    uint8_t* avio_ctx_buffer = nullptr;
    size_t buffer_size;
    size_t avio_ctx_buffer_size = 4096;
    /* fill opaque structure used by the AVIOContext write callback */

    av_file_map(input_filename, &buffer, &buffer_size, 0, NULL);
    qDebug() << "createBufferInput av_file_map";

    avio_ctx_buffer = (uint8_t*)av_malloc(avio_ctx_buffer_size);
    if (!avio_ctx_buffer) return;

    if(bufferData_input) delete bufferData_input;
    bufferData_input = new BufferData();
    avio_ctx_input = avio_alloc_context(avio_ctx_buffer, avio_ctx_buffer_size,
                                        1, bufferData_input,
                                        &Converter::read_packet_to_buffer,
                                        NULL, NULL);
    //------------------------------------------------------
}

void Converter::createBuffer()
{
    //---------------------- BUFFER -------------------------
    uint8_t *avio_ctx_buffer = nullptr;
    const size_t avio_ctx_buffer_size = 4096;
    /* fill opaque structure used by the AVIOContext write callback */
    avio_ctx_buffer = (uint8_t*)av_malloc(avio_ctx_buffer_size);
    if (!avio_ctx_buffer) return;

    if(bufferData) delete bufferData;
    bufferData = new BufferData();
    qDebug()<<"byteArray =" << &bufferData;
    avio_ctx = avio_alloc_context(avio_ctx_buffer, avio_ctx_buffer_size,
                                  1, bufferData, NULL,
                                  &Converter::write_packet_to_buffer, NULL);
    //------------------------------------------------------
}

void Converter::createSWR()
{
    if(!hasAudio) return;
    swrContext = swr_alloc_set_opts(nullptr,
                                    encoderAudio_ctx->channel_layout,
                                    encoderAudio_ctx->sample_fmt,
                                    encoderAudio_ctx->sample_rate,
                                    decoderAudio_ctx->channel_layout,
                                    decoderAudio_ctx->sample_fmt,
                                    decoderAudio_ctx->sample_rate,
                                    0, nullptr );

//    swrContext = swr_alloc();
//    if (!swrContext) {
//        logFile << "\n"<<"Could not allocate resampler context";
//    }
//    //in
//    av_opt_set_int(swrContext, "in_channel_count", decoderAudio_ctx->channels, 0);
//    av_opt_set_int(swrContext, "in_sample_rate", decoderAudio_ctx->sample_rate, 0);
//    av_opt_set_sample_fmt(swrContext, "in_sample_fmt", decoderAudio_ctx->sample_fmt, 0);
//    //out
//    av_opt_set_int(swrContext, "out_channel_count", encoderAudio_ctx->channels, 0);
//    av_opt_set_int(swrContext, "out_sample_rate", encoderAudio_ctx->sample_rate, 0);
//    av_opt_set_sample_fmt(swrContext, "out_sample_fmt", encoderAudio_ctx->sample_fmt, 0);

//    char err[AV_ERROR_MAX_STRING_SIZE] = { 0 };
    int res = 0;
    if ((res = swr_init(swrContext)) < 0) {
        logFile << "\n"<<"Audio Error: Unable to swr_init for capture, error ="<<res;
        return;
    }

    // Create a tempory audio frame to write the resampled data to.
    output_audio_frame = av_frame_alloc();
    output_audio_frame->pts             = 0;
    output_audio_frame->nb_samples      = encoderAudio_ctx->sample_rate;
    output_audio_frame->channels        = encoderAudio_ctx->channels;
    output_audio_frame->channel_layout  = encoderAudio_ctx->channel_layout;
    output_audio_frame->format          = encoderAudio_ctx->sample_fmt;
    output_audio_frame->sample_rate     = encoderAudio_ctx->sample_rate;    
    output_audio_packet = av_packet_alloc();

    if(av_frame_get_buffer(output_audio_frame, 0) < 0)
        qDebug("Could not allocate audio frame data.");


    audioSampleBuffer = av_audio_fifo_alloc(encoderAudio_ctx->sample_fmt,
                                            encoderAudio_ctx->channels,
                                            encoderAudio_ctx->frame_size);
}

/**
 *  Open video source and setup for demuxing and transcoding.
 *  Returns non-zero on error.
 */
int Converter::open(const char* source)
{
    int ret = 0;

    //ожидание скачивания 2%
    while(!QFileInfo::exists(source) && m_downloadProgress < 0.02) {
        sleep(5);
    }

    //проверка на открытие - если данных недостатончно может не открыться
    while(avformat_open_input (&fmt_ctx, source, NULL, NULL) < 0)
    {
        qDebug() << "currentdir = "<<QDir::currentPath();
        fprintf (stderr, "could not open %s\n", source);
        sleep(5);
    }

    // find stream information
    if (avformat_find_stream_info (fmt_ctx, NULL) < 0)
    {
        fprintf (stderr, "could not find stream information\n");
        return 1;
    }

    qDebug() << "fmt_ctx->duration = "<<fmt_ctx->duration;

    for (int i=0; i<fmt_ctx->nb_streams; i++)
    {
        AVStream *in_stream = fmt_ctx->streams[i];
        AVCodecParameters *in_codecpar = in_stream->codecpar;

        if (in_codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
        {
            if(streamAudio) continue;
            streamAudio       = fmt_ctx->streams[i];
            decoderAudio_ctx  = streamAudio->codec;
            decoderAudio      = avcodec_find_decoder(streamAudio->codec->codec_id);
            audio_stream_index = i;

            if (!decoderAudio) {
                qDebug("could not find audio decoder");
                return -1;
            }

            // open codec
            if ((ret = avcodec_open2 (decoderAudio_ctx, decoderAudio, NULL)) < 0) {
                qDebug("failed to open audio codec");
                return ret;
            }
        }
        else if (in_codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            // get decode
            if(streamVideo) continue;
            streamVideo       = fmt_ctx->streams[i];
            decoderVideo_ctx  = streamVideo->codec;
            decoderVideo      = avcodec_find_decoder(decoderVideo_ctx->codec_id);

            video_stream_index = i;

            qDebug()<<"\n stream = "<<streamVideo;
            qDebug()<<"decoder_ctx = "<<decoderVideo_ctx;
            qDebug()<<"decoder " <<decoderVideo;

            if (!decoderVideo) {
                qDebug("could not find audio decoder");
                return -1;
            }

            // open codec
            if ((ret = avcodec_open2 (decoderVideo_ctx, decoderVideo, NULL)) < 0) {
                qDebug("failed to open video codec");
                return ret;
            }
        }
    }

//    createBufferInput(source);
    if(avio_ctx_input) fmt_ctx->pb = avio_ctx_input;

    // dump information to stderr
    av_dump_format (fmt_ctx, 0, source, 0);

    // allocate frame
    frame = av_frame_alloc ();
    if (!frame)
    {
        fprintf (stderr, "failed to allocate frame\n");
        return 1;
    }

    // init packet struct
    av_init_packet (&packet);
    packet.size = 0;
    packet.data = NULL;

    return 0;
}

bool Converter::createAudioEncoder()
{
    encoderAudio = avcodec_find_encoder(AV_CODEC_ID_OPUS);
    if (!encoderAudio) qDebug("ERROR: could not create avcodec_find_encoder(AV_CODEC_ID_OPUS)");

    encoderAudio_ctx = avcodec_alloc_context3(encoderAudio);
    if(!encoderAudio_ctx) return false;

    out_stream_audio = avformat_new_stream (ofmt_ctx, encoderAudio);
    output_audio_stream_index = out_stream_audio->index;

//    if(decoderAudio_ctx->channels && !decoderAudio_ctx->channel_layout) {
//        decoderAudio_ctx->channel_layout = av_get_default_channel_layout(decoderAudio_ctx->channels);
//    }

    //opus fmt[0] = AV_SAMPLE_FMT_S16
    //opus fmt[1] = AV_SAMPLE_FMT_FLT
    encoderAudio_ctx->sample_fmt = encoderAudio->sample_fmts[0];
    encoderAudio_ctx->bit_rate = decoderAudio_ctx->bit_rate;
    encoderAudio_ctx->channel_layout = AV_CH_LAYOUT_STEREO;
    encoderAudio_ctx->channels = av_get_channel_layout_nb_channels(encoderAudio_ctx->channel_layout);
    encoderAudio_ctx->sample_rate = 48000;

    qDebug() << "decoderAudio_ctx->bit_rate =" << decoderAudio_ctx->bit_rate;
    qDebug() << "decoderAudio_ctx->sample_fmt =" << decoderAudio_ctx->sample_fmt;
    qDebug() << "decoderAudio_ctx->channel_layout =" << decoderAudio_ctx->channel_layout;
    qDebug() << "decoderAudio_ctx->channels =" << decoderAudio_ctx->channels;
    qDebug() << "decoderAudio_ctx->frame_size =" << decoderAudio_ctx->frame_size;

    qDebug() << "encoderAudio->bit_rate =" << encoderAudio_ctx->bit_rate;
    qDebug() << "encoderAudio->sample_fmt =" << encoderAudio_ctx->sample_fmt;
    qDebug() << "encoderAudio->channel_layout =" << encoderAudio_ctx->channel_layout;
    qDebug() << "encoderAudio->channels =" << encoderAudio_ctx->channels;
    qDebug() << "encoderAudio->frame_size =" << encoderAudio_ctx->frame_size;



    if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
        encoderAudio_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    if (avcodec_open2 (encoderAudio_ctx, encoderAudio, nullptr) < 0)
        qDebug("could not open encoderAudio", 1);

    avcodec_parameters_from_context(out_stream_audio->codecpar, encoderAudio_ctx);
    hasAudio = true;
    return true;
}

bool Converter::createVideoEncoder()
{
    encoderVideo = avcodec_find_encoder(AV_CODEC_ID_VP8);
    encoderVideo_ctx = avcodec_alloc_context3(encoderVideo);
    qDebug()<< "encoder_ctx=" << encoderVideo_ctx;

    out_stream_video = avformat_new_stream (ofmt_ctx, encoderVideo);
    if (!out_stream_video) qDebug("could not add new stream", 1);

//            out_stream_video->index = AVMEDIA_TYPE_VIDEO;
    output_video_stream_index = out_stream_video->index;

//    qDebug() << "encoder->id = "<< encoderVideo->id;
//    qDebug() << "out_stream->codecpar->codec_id = "<<out_stream_video->codecpar->codec_id;

//    encoder_ctx                      = out_stream->codec;
    encoderVideo_ctx->height              = decoderVideo_ctx->height;
    encoderVideo_ctx->width               = decoderVideo_ctx->width;
    encoderVideo_ctx->time_base           = decoderVideo_ctx->time_base;
    encoderVideo_ctx->sample_aspect_ratio = decoderVideo_ctx->sample_aspect_ratio;
    encoderVideo_ctx->pix_fmt             = encoderVideo->pix_fmts[0];
    encoderVideo_ctx->bit_rate            = decoderVideo_ctx->bit_rate;


    //    -deadline realtime -cpu-used -16
    AVDictionary *opt = NULL;
//    av_dict_set(&opt, "deadline", "realtime", 0);
    av_dict_set(&opt, "b:v", "", 0);
////    av_dict_set(&opt, "c:v", "", 0); //constant bitrate
    av_dict_set(&opt, "crf", "20", 0); //0-63 - lower - better quality
    av_dict_set(&opt, "threads", "6", 0);
    av_dict_set(&opt, "cpu-used", "10", 0);


//    av_dict_set(&opt, "usetoc", "0", 0);



    if (avcodec_open2 (encoderVideo_ctx, encoderVideo, &opt) < 0)
        qDebug("could not open encoder", 1);
    av_dict_free(&opt);


    if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) {
        encoderVideo_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    }

    avcodec_parameters_from_context(out_stream_video->codecpar, encoderVideo_ctx);
    out_stream_video->time_base            = streamVideo->time_base;
    hasVideo = true;
    return true;
}

/**
 *  Open destination file for writing.
 */
int Converter::open_destination (const char* destination)
{
    avformat_alloc_output_context2 (&ofmt_ctx, NULL, NULL, destination);
    if (!ofmt_ctx) {
        qDebug("ERROR: could not open destination");
        return -1;
    }

    ofmt_ctx->duration = fmt_ctx->duration;
    ofmt_ctx->flags |= AVFMT_FLAG_NOBUFFER | AVFMT_FLAG_FLUSH_PACKETS | AVFMT_FLAG_CUSTOM_IO;

    av_dict_copy( &(ofmt_ctx->metadata), fmt_ctx->metadata, 0);
    av_dict_set( &(ofmt_ctx->metadata), "Author", "Kolomietc Vadim", 0 );

    qDebug() << "ofmt_ctx->duration = "<<ofmt_ctx->duration;


    if(video_stream_index>=0) createVideoEncoder();
    if(audio_stream_index>=0) createAudioEncoder();

    if(!hasVideo) {
        qDebug() << "Torrent haven't video so exit";
//        return -1;
    }

    av_dump_format (ofmt_ctx, 0, destination, 1);
    createBuffer();

    if(avio_ctx) {
        ofmt_ctx->pb = avio_ctx;
//        ofmt_ctx->flags |= AVFMT_FLAG_CUSTOM_IO;
    }
    else {
        if(avio_open (&ofmt_ctx->pb, destination, AVIO_FLAG_WRITE) < 0) {
            qDebug("could open file for writing");
            return -1;
        }
    }

    qDebug() << "ofmt_ctx->duration = "<<ofmt_ctx->duration;

    // Prepare resampling
    createSWR();

    if(avformat_write_header (ofmt_ctx, NULL) < 0) {
        qDebug("error writing header");
        return -1;
    }

    if(decoderAudio_ctx && encoderAudio_ctx) {
        printf("Input Code Ctx Frame size: %d\n", decoderAudio_ctx->frame_size);
        printf("Output Code Ctx Frame size: %d\n", encoderAudio_ctx->frame_size);
    }

    qDebug() << "ofmt_ctx->duration = "<<ofmt_ctx->duration;
    return 0;
}

void Converter::createStreamList() {
    //------------------------  Stream list  ----------------------------
    int *stream_mapping = NULL;
    int stream_mapping_size = 0;
    stream_mapping_size = fmt_ctx->nb_streams;
    stream_mapping = (int*)av_mallocz_array(stream_mapping_size, sizeof(*stream_mapping));
    //-------------------------------------------------------------------
}

int Converter::encode(AVFrame *enc_frame, AVMediaType type)
{
    int ret = 0;

//    qDebug() << "encode";
    if(enc_frame) {
//        logFile << "\n\n"<<"############ start encode ###########";
//        qDebug() << "\n"<<"encode frame.dts="<<enc_frame->pkt_dts <<"pts=" << enc_frame->pts;
//        logFile << "\n"<<"encode frame.nb_samples="<<enc_frame->nb_samples;
    }

    if(type == AVMEDIA_TYPE_AUDIO)
    {
        if(!hasAudio) return 0;
//        qDebug() << "\n"<<"encode audio frame.dts="<<enc_frame->pkt_dts <<"pts=" << enc_frame->pts;

    //    AVPacket *enc_pkt  = av_packet_alloc();

        if ((ret = avcodec_send_frame(encoderAudio_ctx, enc_frame)) < 0) {
//            qDebug()<< "\n"<< "Error during encoding ret" <<ret;
            return -1;
        }
        while (ret >=0) {
            av_init_packet(output_audio_packet);
            ret = avcodec_receive_packet(encoderAudio_ctx, output_audio_packet);
            if(ret < 0) break;

            output_audio_packet->stream_index = output_audio_stream_index;
            av_packet_rescale_ts(output_audio_packet, encoderAudio_ctx->time_base,
                                 out_stream_audio->time_base);

//            output_audio_packet->dts = output_audio_packet->pts;

//            logFile << "\n"<<"output_audio_packet->duration = " << output_audio_packet->duration;
//            qDebug() << "\n"<<"output_audio_packet->pts = " << output_audio_packet->pts;
//            qDebug() << "\n"<<"output_audio_packet->dts = " << output_audio_packet->dts;

            // Write packet to stream for muxing
            if(av_interleaved_write_frame(ofmt_ctx, output_audio_packet) < 0)
                qDebug("Could not write audio frame");

            av_packet_unref(output_audio_packet);
        }
    }
    else if(type == AVMEDIA_TYPE_VIDEO)
    {
        if(!hasVideo) return 0;
//        qDebug() << "\n"<<"encode video frame.dts="<<enc_frame->pkt_dts <<"pts=" << enc_frame->pts
//                 <<"pkt_pts=" << enc_frame->pkt_pts << "duration="<<enc_frame->pkt_duration;


        AVPacket enc_pkt;
        av_init_packet(&enc_pkt);
//        enc_pkt.data = NULL;
//        enc_pkt.size = 0;

//        if(enc_frame->pts == AV_NOPTS_VALUE) {
            enc_pkt.dts = enc_frame->pkt_dts;
            enc_pkt.pts = enc_frame->pkt_dts;
            enc_frame->pts = enc_frame->pkt_dts;
            enc_frame->pkt_pts = enc_frame->pkt_dts;

//        }
//        qDebug() <<"encode video pakect.dts="<<enc_pkt.dts <<"pts=" << enc_pkt.pts;

//        if(enc_pkt.pts == 0 && enc_pkt.pts != enc_frame->pkt_pts)
//            enc_pkt.pts = enc_frame->pkt_pts;
//        if(enc_pkt.dts == 0 && enc_pkt.dts != enc_frame->pkt_dts)
//            enc_pkt.dts = enc_frame->pkt_dts;


        if ((ret = avcodec_send_frame(encoderVideo_ctx, enc_frame)) < 0) {
            qDebug()<< "Error during encoding";
        }
        while (1) {
            ret = avcodec_receive_packet(encoderVideo_ctx, &enc_pkt);
            if (ret == AVERROR(EAGAIN)) break;
            else if(ret < 0) break;



    //        enc_pkt.stream_index = stream_mapping[pkt.stream_index];
//            qDebug()<<"enc_pkt.stream_index = "<<enc_pkt.stream_index;
//            AVStream *in_stream  = fmt_ctx->streams[enc_pkt.stream_index];
//            enc_pkt.stream_index = output_video_stream_index;
    //        av_packet_rescale_ts(&enc_pkt, out_stream->codec->time_base, out_stream->time_base);


            AVStream *inStream  = fmt_ctx->streams[enc_pkt.stream_index];
//            av_packet_rescale_ts(&enc_pkt, encoderVideo_ctx->time_base, out_stream_video->time_base);

            enc_pkt.pts = av_rescale_q_rnd(enc_pkt.pts,
                                           streamVideo->time_base,
                                           out_stream_video->time_base,
                                           AVRounding(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));

            enc_pkt.dts = av_rescale_q_rnd(enc_pkt.dts,
                                           streamVideo->time_base,
                                           out_stream_video->time_base,
                                           AVRounding(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));

//            enc_pkt.duration = 1;
            enc_pkt.duration = av_rescale_q(enc_pkt.duration,
                                            streamVideo->time_base,
                                            out_stream_video->time_base);

//            qDebug() << "inStream->time_base="<< streamVideo->time_base.den << streamVideo->time_base.num;
//            qDebug() << "out_stream_video->time_base="<< out_stream_video->time_base.den << out_stream_video->time_base.num;
//            qDebug() << "enc_pkt.duration="<< enc_pkt.duration;

//            qDebug() << "\n"<<"video dts=" <<enc_pkt.dts;
//            logFile << "\n"<<"video pts=" <<enc_pkt.pts;
//            enc_pkt.pos = -1;

            av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
//            av_packet_unref(&enc_pkt);
        }
    }

    return 0;
}

void Converter::flushVideo()
{
    qDebug() << "FLUSH VIDEO!!!!!!!!!!";
    if(!hasVideo) return;
    int ret = avcodec_send_packet(decoderVideo_ctx, NULL);
    if (ret < 0) {
        fprintf(stderr, "Error sending a packet for decoding\n");
        if (ret < 0) fprintf(stderr, "Error during decoding\n");

        return;
    }

    qDebug()<<"avcodec_send_packet" << ret;

    AVFrame *frame;
    while (ret >= 0) {
        if (!(frame = av_frame_alloc())) {
            qDebug() << "Error av_frame_alloc";
            return;
        }
        qDebug()<<"avcodec_receive_frame start";
        ret = avcodec_receive_frame(decoderVideo_ctx, frame);
        qDebug()<<"avcodec_receive_frame "<<ret;
        if (ret < 0) fprintf(stderr, "Error during decoding\n");
        encode(frame, AVMEDIA_TYPE_VIDEO);
        av_frame_free(&frame);
    }

//    encode(NULL, AVMEDIA_TYPE_VIDEO);
}

void Converter::flushAudio(long audio_pts)
{
    if(!hasAudio) return;
    logFile << "\n ##################### flushAudio #######################";
    int ret = 0;

    if((ret = avcodec_send_packet(decoderAudio_ctx, NULL)) < 0) {
        qDebug()<< "reading_input=false Error sending a packet for decoding ret =" << ret;
        return;
    }

    AVFrame *frame;
    frame = av_frame_alloc();
    if(!frame) {
        qDebug()<<"\n"<<"Error av_frame_alloc";
        return;
    }

    bool receiveFrame = true;
    while(receiveFrame) {
        receiveFrame = (avcodec_receive_frame(decoderAudio_ctx, frame) >= 0);
        if(swrContext) {
            output_audio_frame->nb_samples = encoderAudio_ctx->frame_size;
            int64_t delay =  swr_get_delay(swrContext, encoderAudio_ctx->sample_rate);
            qDebug() << "delay = "<<delay;
            if(delay > 0) {
                swr_convert_frame(swrContext, output_audio_frame, NULL);
                output_audio_frame->pts = audio_pts;
                audio_pts += output_audio_frame->nb_samples;
                encode(output_audio_frame, AVMEDIA_TYPE_AUDIO);
            }
        }
    }
}


/**
 *  Transcode the stream.
 *  Takes a function pointer to a store function.
 */
void Converter::transcode()
{
    long audio_pts = 0;
    int frame_count = 0;
    int ret = 0;
    // start transcoding
    qint64 fullSize = 0;

    qint64 fullDelay = 0;

    bool reading_input = true;

    while(reading_input)
    {
        if(m_handle) {
            const bool blocksFinished = m_handle->checkBlockRangeDownloaded(fmt_ctx->pb->pos, fmt_ctx->pb->buffer_size);
            if(blocksFinished == false) {
                qDebug() << "\n\n\n BLOCK NOT FINISHED WAIT BLOCK!";
                sleep(5);
                continue;
            }
        }

//        qDebug() << "check range PASSED";

//        if(fmt_ctx->pb->pos + fmt_ctx->pb->buffer_size  >= m_bytesReceived)
//        {
//            sleep(5);
//            continue;
//        }

//        qDebug() << "check bytes PASSED";



//        qDebug() << "m_bytesReceived=" << m_bytesReceived
//                 << "m_bytesTotal=" << m_bytesTotal
//                 << "pos=" << fmt_ctx->pb->pos
//                 << "buffer_size=" << fmt_ctx->pb->buffer_size;
//        qDebug() << "run m_downloadProgress="<<m_downloadProgress;

        const int readFrameResult = av_read_frame(fmt_ctx, &packet);
        reading_input =  (readFrameResult >= 0);
        if(!reading_input && m_downloadProgress < 1.0) {
            if(readFrameResult == AVERROR(EAGAIN)) qDebug() << "av_read_frame EAGAIN";
            else if(readFrameResult == AVERROR_EOF) {
                qDebug() << "av_read_frame AVERROR_EOF";
            }
            else qDebug() << "av_read_frame UNKNOWN";

            reading_input = true;
            sleep(5);
//            av_usleep(5000);
            continue;
        }

//        if(packet.size <= 0) {
//            qDebug() << "packet.size == 0";
//            reading_input = true;
//            av_packet_unref(&packet);
//            sleep(5);
//            continue;
//        }

        if(packet.stream_index >= fmt_ctx->nb_streams) {
            av_packet_unref(&packet);
            continue;
        }

        AVCodecParameters *out_codecpar = fmt_ctx->streams[packet.stream_index]->codecpar;
        if (out_codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
        {
            if(!hasAudio) continue;
            if(audio_stream_index != packet.stream_index) continue;
            if((ret = avcodec_send_packet(decoderAudio_ctx, &packet)) < 0) {
                qDebug() << "reading_input=true Error sending a audio packet for decoding ret = "<<ret;
                fprintf(stderr, "\n");
                av_packet_unref(&packet);
                continue;
            }

            AVFrame *frame = av_frame_alloc();
            if(!frame) {
                qDebug()<<"\n"<<"Error av_frame_alloc";
                av_frame_free(&frame);
                av_packet_unref(&packet);
                continue;
            }

            while ( avcodec_receive_frame(decoderAudio_ctx, frame) >= 0) {
//                qDebug() << "frame->pts =" << frame->pts;
//                qDebug() << "frame->data =" << frame->data;
//                qDebug() << "frame->format =" << frame->format;
//                qDebug() << "frame->pkt_dts =" << frame->pkt_dts;
//                qDebug() << "frame->sample_rate =" << frame->sample_rate;
//                qDebug() << "frame->nb_samples =" << frame->nb_samples;

                if(swrContext) {
                    output_audio_frame->nb_samples = encoderAudio_ctx->frame_size;
                    int64_t delay =  swr_get_delay(swrContext, encoderAudio_ctx->sample_rate);
                    swr_convert_frame(swrContext, output_audio_frame, frame);
                    output_audio_frame->pts = audio_pts;
                    audio_pts += output_audio_frame->nb_samples;

                    fullDelay += delay;
//                    logFile << "\n delay ="<< delay;
                    encode(output_audio_frame, out_codecpar->codec_type);

                    if(delay >= 960) {
                         swr_convert_frame(swrContext, output_audio_frame, NULL);
                        output_audio_frame->pts = audio_pts;
                        audio_pts += output_audio_frame->nb_samples;
                        encode(output_audio_frame, out_codecpar->codec_type);
                    }
                }
            }
            av_frame_free(&frame);
        }
        else if(out_codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            if(!hasVideo) continue;
            if(video_stream_index != packet.stream_index) continue;


//            qDebug() << "packet.duration="<< packet.duration;

            ret = avcodec_send_packet(decoderVideo_ctx, &packet);
            if (ret < 0) {
                qDebug() << "Error sending a video packet for decoding" << ret;
//                av_packet_unref(&packet);
                continue;
            }
//            qDebug() << "packet.duration="<< packet.duration;

            AVFrame *frame;
            while (ret >= 0) {
                if (!(frame = av_frame_alloc())) {
                    qDebug() << "Error av_frame_alloc";
                    return;
                }
                ret = avcodec_receive_frame(decoderVideo_ctx, frame);
                if (ret < 0) {
//                    if(ret == AVERROR(EAGAIN)) qDebug() << "Error during decoding EAGAIN";
//                    else if(ret == AVERROR_EOF) qDebug() << "Error during decoding AVERROR_EOF";
//                    else qDebug() << "Error during decoding UNKNOWN";

                    av_frame_free(&frame);
                    break;
                }
                encode(frame, out_codecpar->codec_type);
                av_frame_free(&frame);
            }

//            qDebug() << "end transcode packet";
        }
        av_packet_unref(&packet);
    }


//    flushAudio(audio_pts);
//    flushVideo();

    av_write_trailer(ofmt_ctx);
    qDebug() << "RESULT fullSize= "<< fullSize;
}
