Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 24개 있습니다.)
.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c)
; https://www.sysnet.pe.kr/2/0/12898

.NET Framework: 1134. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c)
; https://www.sysnet.pe.kr/2/0/12924

.NET Framework: 1135. C# - ffmpeg(FFmpeg.AutoGen)로 하드웨어 가속기를 이용한 비디오 디코딩 예제(hw_decode.c)
; https://www.sysnet.pe.kr/2/0/12932

.NET Framework: 1136. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP2 오디오 파일 디코딩 예제(decode_audio.c)
; https://www.sysnet.pe.kr/2/0/12933

.NET Framework: 1137. ffmpeg의 파일 해시 예제(ffhash.c)를 C#으로 포팅
; https://www.sysnet.pe.kr/2/0/12935

.NET Framework: 1138. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 멀티미디어 파일의 메타데이터를 보여주는 예제(metadata.c)
; https://www.sysnet.pe.kr/2/0/12936

.NET Framework: 1139. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 오디오(mp2) 인코딩하는 예제(encode_audio.c)
; https://www.sysnet.pe.kr/2/0/12937

.NET Framework: 1147. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 오디오 필터링 예제(filtering_audio.c)
; https://www.sysnet.pe.kr/2/0/12951

.NET Framework: 1148. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 오디오 필터 예제(filter_audio.c)
; https://www.sysnet.pe.kr/2/0/12952

.NET Framework: 1150. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/12959

개발 환경 구성: 637. ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/12960

.NET Framework: 1151. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 프레임의 크기 및 포맷 변경 예제(scaling_video.c)
; https://www.sysnet.pe.kr/2/0/12961

.NET Framework: 1153. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 avio_reading.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/12964

.NET Framework: 1157. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 muxing.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/12971

.NET Framework: 1159. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 qsvdec.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/12975

.NET Framework: 1161. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 resampling_audio.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/12978

.NET Framework: 1166. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 filtering_video.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/12984

.NET Framework: 1169. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 demuxing_decoding.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/12987

.NET Framework: 1170. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcode_aac.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/12991

.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/13002

.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/13006

.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/13023

.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/13025

.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드
; https://www.sysnet.pe.kr/2/0/13026




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 파일이 모두 다음과 같이 깨져 나옵니다.

mpeg1video_to_pgm_1.png

혹시나, 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




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/13/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-01-17 11시04분
[이승준] 생각하시는부분이 맞습니다.
ffmpeg.exe의 경우 출력 포맷에 따라 기본적인 인코딩이나 컬러포맷변경을 자동으로 합니다.
저장하기 전에 컬러포맷을 pgm에 맞도록 해줘야 합니다.
ffmpeg 샘플 소스에 보면 videofilter 관련 소스가 있을 겁니다.
그걸 이용해서 변경을 해 주셔야 합니다. 또는 opencv를 이용해서 변경하시는방법도 있고요.

마지막으로 아마도 디코더 출력 컬러포맷이 yuv420일겁니다. y전체 데이터 + uv 전체 데이터 이런식일건데요.
저장을 y만 하면 됩니다. 크기는 width * heght 입니다.
[guest]
2022-01-17 11시23분
@이승준 설명 감사합니다. 그렇게 확인해 주시는 것과 부가 설명만 해도 ffmpeg 초보들에게는 큰 힘이 됩니다. ^^

그나저나, 그럼 애당초 decode_video.c의 예제에서 pgm_save를 저렇게 공개하면... 저같은 초보들은 헤맬 수밖에 없을 듯합니다. 암튼, 말씀해 주신 내용을 기반으로 pgm 저장 부분을 어떻게든 성공시켜야겠습니다. ^^
정성태

1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13475정성태12/7/20232279닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232326닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232155C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232183Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232484닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232193닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232176닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232171오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232376닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232111개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232233닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232144오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232210오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232258닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232225닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232207닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232212닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232164VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232459닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232339닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232683닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232218오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232296닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232431닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232254닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...