// JpegTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

extern "C" {
#   include "libavformat\avformat.h"
#   include "libavcodec\avcodec.h"
#   include "libavutil\avutil.h"
#   include "libavutil\frame.h"
#   include "libswscale\swscale.h"
}

#pragma comment( lib, "lib/avcodec" )
#pragma comment( lib, "lib/avfilter" )
#pragma comment( lib, "lib/avformat" )
#pragma comment( lib, "lib/avutil" )
#pragma comment( lib, "lib/swscale" )

int _tmain(int argc, _TCHAR* argv[])
{
    av_register_all();

    AVInputFormat *inputFormat = av_find_input_format("image2");

    AVFormatContext *pFC = nullptr;
    int res = avformat_open_input(&pFC, "F:\\test\\root_banner.jpg", inputFormat, nullptr);

    res = avformat_find_stream_info(pFC, nullptr);

    AVCodec *pCodec = nullptr;
    int idx = av_find_best_stream(pFC, AVMEDIA_TYPE_VIDEO, -1, -1, &pCodec, -1);

    AVStream *pStream = pFC->streams[idx];
    res = avcodec_open2(pStream->codec, pCodec, nullptr);

    AVPacket packet;
    av_read_frame(pFC, &packet);

    int gotPicture;
    AVFrame* pSrc = avcodec_alloc_frame();
    avcodec_decode_video2(pStream->codec, pSrc, &gotPicture, &packet);

    SwsContext *pSwsContext = nullptr;
    pSwsContext = sws_getCachedContext(pSwsContext,
        pSrc->width, pSrc->height,
        static_cast<PixelFormat>(pSrc->format),
        1, 60, PIX_FMT_BGRA,
        SWS_BILINEAR, nullptr, nullptr, nullptr
    );

    AVFrame* pDest = avcodec_alloc_frame();
    avpicture_alloc(reinterpret_cast<AVPicture *>(pDest), PIX_FMT_BGRA, 1, 60);
    sws_scale(pSwsContext, pSrc->data, pSrc->linesize,
        0, pSrc->height, pDest->data, pDest->linesize
    );

    av_free_packet(&packet);
    // in debug mode: HEAP[JpegTest.exe]: Heap block at 00706758 modified at 00706874 past requested size of 114
    avpicture_free(reinterpret_cast<AVPicture *>(pDest));
    av_freep(&pDest);
    av_freep(&pSrc);
    avcodec_close(pStream->codec);
    avformat_close_input(&pFC);

    return 0;
}

