C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c)
지난 글에 이어,
C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제
; https://www.sysnet.pe.kr/2/0/12898
이번에는 비디오 파일을 디코딩 해보겠습니다. 이번에도 역시 "
FFmpeg - Examples"에 있는 예제 중 "decode_video.c"를 포팅할 것입니다.
FFmpeg - Examples
; https://ffmpeg.org/doxygen/trunk/examples.html
decode_video.c
; https://ffmpeg.org/doxygen/trunk/decode_video_8c-example.html
그런데, 비디오 파일의 포맷이 MPEG1VIDEO라고 되어 있는데요,
/* find the MPEG-1 video decoder */
codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);
그래서 이전 글에서 MPEG1 비디오 포맷으로의 변환을 설명한 것입니다. ^^
ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
; https://www.sysnet.pe.kr/2/0/12923
아무튼, 이렇게 해서 포팅한 C# 코드의 전문은 다음과 같습니다.
using FFmpeg.AutoGen;
using FFmpeg.AutoGen.Example;
using System;
using System.IO;
using System.Text;
namespace FFmpegApp1
{
internal class Program
{
const int INBUF_SIZE = 4096;
static void Main(string[] args)
{
FFmpegBinariesHelper.RegisterFFmpegBinaries();
string outputPath = @"c:\temp\output";
video_decode_example(@"D:\video_sample\SampleVideo_1280x720_30mb.mpeg", AVCodecID.AV_CODEC_ID_MPEG1VIDEO, outputPath);
}
static unsafe void video_decode_example(string filename, AVCodecID codec_id, string outfileDirPath)
{
AVCodec* _pCodec = null;
AVCodecParserContext* _parser = null;
AVCodecContext* _pCodecContext = null;
AVFrame* frame = null;
AVPacket* pkt = null;
byte[] inbuf = new byte[INBUF_SIZE + ffmpeg.AV_INPUT_BUFFER_PADDING_SIZE];
int ret = 0;
using BinaryReader inputFile = new BinaryReader(new FileStream(filename, FileMode.Open));
do
{
pkt = ffmpeg.av_packet_alloc();
if (pkt == null)
{
break;
}
/* find the MPEG-1 video decoder */
Console.WriteLine($"Decode video file {filename}");
_pCodec = ffmpeg.avcodec_find_decoder(codec_id);
if (_pCodec == null)
{
Console.WriteLine($"Codec not found: {codec_id}");
break;
}
_parser = ffmpeg.av_parser_init((int)_pCodec->id);
_pCodecContext = ffmpeg.avcodec_alloc_context3(_pCodec);
if (_pCodecContext == null)
{
Console.WriteLine($"Could not allocate video codec context: {codec_id}");
break;
}
/* open it */
if (ffmpeg.avcodec_open2(_pCodecContext, _pCodec, null) < 0)
{
Console.WriteLine("Could not open codec");
break;
}
frame = ffmpeg.av_frame_alloc();
if (frame == null)
{
Console.WriteLine("Could not allocate video frame");
break;
}
bool parse_succeed = true;
while (parse_succeed)
{
int data_size = inputFile.Read(inbuf, 0, INBUF_SIZE);
if (data_size == 0)
{
break;
}
fixed(byte *ptr = inbuf)
{
byte* data = ptr;
while (data_size > 0)
{
ret = ffmpeg.av_parser_parse2(_parser, _pCodecContext,
&pkt->data, &pkt->size, data, data_size, ffmpeg.AV_NOPTS_VALUE, ffmpeg.AV_NOPTS_VALUE, 0);
if (ret < 0)
{
break;
}
data += ret;
data_size -= ret;
if (pkt->size != 0)
{
parse_succeed = decode(_pCodecContext, frame, pkt, outfileDirPath);
if (parse_succeed == false)
{
break;
}
}
}
}
}
// flush the decoder
decode(_pCodecContext, frame, null, outfileDirPath);
} while (false);
if (_parser != null)
{
ffmpeg.av_parser_close(_parser);
}
if (_pCodecContext != null)
{
ffmpeg.avcodec_free_context(&_pCodecContext);
}
if (frame != null)
{
ffmpeg.av_frame_free(&frame);
}
if (pkt != null)
{
ffmpeg.av_packet_free(&pkt);
}
}
private static unsafe bool decode(AVCodecContext* pCodecContext, AVFrame* frame, AVPacket* pkt, string outfileDirPath)
{
int ret = ffmpeg.avcodec_send_packet(pCodecContext, pkt);
if (ret < 0)
{
Console.WriteLine("Error sending a packet for decoding");
return false;
}
while (ret >= 0)
{
ret = ffmpeg.avcodec_receive_frame(pCodecContext, frame);
if (ret == ffmpeg.AVERROR(ffmpeg.EAGAIN) || ret == ffmpeg.AVERROR_EOF)
{
return true;
}
else if (ret < 0)
{
Console.WriteLine("Error during decoding");
return false;
}
Console.WriteLine($"saving frame {pCodecContext->frame_number}");
string outputFile = Path.Combine(outfileDirPath, "noname_" + pCodecContext->frame_number + ".pgm");
pgm_save(frame->data[0], frame->linesize[0], frame->width, frame->height, outputFile);
}
return true;
}
// ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법
// ; https://www.sysnet.pe.kr/2/0/12912
private static unsafe void pgm_save(byte* buf, int wrap, int xsize, int ysize, string filename)
{
using FileStream fs = new FileStream(filename, FileMode.Create);
byte [] header = Encoding.ASCII.GetBytes($"P5\n{xsize} {ysize}\n255\n");
fs.Write(header);
// C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법
// ; https://www.sysnet.pe.kr/2/0/12913
for (int i = 0; i < ysize; i ++)
{
byte* ptr = buf + (i * wrap);
ReadOnlySpan<byte> pos = new Span<byte>(ptr, xsize);
fs.Write(pos);
}
}
}
}
그런데, 문제가 있습니다. MPEG1Video 파일로
실제 테스트를 해보니 출력된 PGM 파일이 모두 다음과 같이 깨져 나옵니다.
혹시나, C# 포팅의 문제가 있나 싶어서 C 언어를 그대로 실행해 봤지만 역시나 결과는 똑같았습니다.
(
첨부 파일은 decode_video.c 파일의 C#과 Visual C++로 포팅한 프로젝트 파일을 포함합니다.)
(
이 글의 소스 코드는 github에 올려져 있습니다.)
그렇긴 한데, 약간 이상한 면이 있습니다.
av_parser_parse2와 같은 함수를 호출하는데 여기에 딱히 gray 변환 같은 옵션을 주는 부분은 없습니다. 기본 디코딩이 gray가 아니라면 해당 MPEG1 파일이 컬러 영상이므로 그것을 그대로 (gray 포맷의) pgm 파일로 쓰는 것이 맞나...라는 의심이 생깁니다.
(2022-02-07 업데이트: 어차피 mpeg1video 코덱이 YUV420P 포맷의 프레임을 생성하기 때문에 Y 채널의 값을 pgm으로 저장하면 흑백으로 나오는 것이 맞습니다.)
결국, 뭔가 저 코드를 위한 gray 처리된 MPEG41Video가 있는 것인지, 아니면 저 코드 자체가 잘못된 것인지 판단이 안 됩니다. (혹시 아시는 분은 덧글 부탁드립니다. ^^)
(2022-02-09 업데이트) 이 글의 소스 코드(결국 decode_video.c)를 테스트하기 위해서는 아래의 글에 설명한 방법에 따라 생성한 동영상을 마련해야 합니다.
ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/12960
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]