#include<iostream>
#include <fstream>
#include <string>
using namespace std;
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
}
#pragma comment(lib, "avcodec.lib")
#pragma comment(lib, "avutil.lib")
int main(int argc, char* argv[])
{
string filename = "test.h264";
ifstream ifs(filename, ios::binary);
if (!ifs) return -1;
unsigned char inbuf[4096] = { 0 };
AVCodecID codec_id = AV_CODEC_ID_H264;
auto codec = avcodec_find_decoder(codec_id);
auto c = avcodec_alloc_context3(codec);
avcodec_open2(c, NULL, NULL);
auto parser = av_parser_init(codec_id);
auto pkt = av_packet_alloc();
auto frame = av_frame_alloc();
while (!ifs.eof())
{
ifs.read((char*)inbuf, sizeof(inbuf));
int data_size = ifs.gcount();
if (data_size <= 0) break;
auto data = inbuf;
while (data_size > 0)
{
int ret = av_parser_parse2(parser, c,
&pkt->data, &pkt->size,
data, data_size,
AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
data += ret;
data_size -= ret;
if (pkt->size)
{
ret = avcodec_send_packet(c, pkt);
if (ret < 0)
{
break;
}
while (ret >= 0)
{
ret = avcodec_receive_frame(c, frame);
if (ret < 0)
break;
cout << frame->format << " " << flush;
}
}
}
}
av_packet_free(&pkt);
int ret = avcodec_send_packet(c, NULL);
while (ret >= 0)
{
ret = avcodec_receive_frame(c, frame);
if (ret < 0)
break;
cout << frame->format << "-" << flush;
}
av_parser_close(parser);
avcodec_free_context(&c);
av_frame_free(&frame);
av_packet_free(&pkt);
return 0;
}