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)
14005정성태8/21/2025379오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/2025414오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/2025530닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
14002정성태8/20/2025663오류 유형: 980. C# - appsettings.json 파일의 설정값이 적용 안 된다면?
14001정성태8/19/20251267닷넷: 2356. .NET SDK 10 - 단일 소스 코드 파일을 빌드/실행하는 기능을 "dotnet" 명령어에 추가
14000정성태8/18/20251085오류 유형: 979. ERROR: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory
13999정성태8/15/20251399닷넷: 2355. C# 14 - (8) null 조건부 연산자 개선 - 대입문에도 사용 가능파일 다운로드1
13998정성태8/14/20251239닷넷: 2354. C# 14 - (7) 확장 메서드에 정적 메서드와 속성 지원을 위한 전용 구문 추가파일 다운로드1
13997정성태8/14/20251368Linux: 120. docker 컨테이너로 매핑된 볼륨에 컨테이너 측의 사용자 ID를 유지하면서 복사하는 방법
13996정성태8/13/2025899오류 유형: 978. Unable to find the requested .Net Framework Data Provider.
13995정성태8/13/2025922개발 환경 구성: 754. Visual C++ - 리눅스 빌드를 위한 Ubuntu 18 docker 컨테이너 설정
13994정성태8/12/2025861오류 유형: 977. SQL Server - User, group, or role '...' already exists in the current database. (Microsoft SQL Server, Error: 15023)
13993정성태8/11/20251297오류 유형: 976. Microsoft.ML.OnnxRuntimeGenAI 패키지 사용 시 "cublasLt64_12.dll" which is missing. (Error 126: "The specified module could not be found.") 오류
13992정성태8/11/20251502닷넷: 2353. C# - Foundry Local을 이용한 gpt-oss-20b 모델 사용파일 다운로드1
13991정성태8/9/20251387오류 유형: 975. winget - Foundry Local 패키지 업데이트가 안 되는 문제
13990정성태8/8/20251025Windows: 283. Time zone 설정이 없는 Windows Server 2025
13989정성태8/8/20251504닷넷: 2352. C# - Windows S-mode 환경인지 체크하는 방법파일 다운로드1
13988정성태8/8/20251651오류 유형: 974. 비주얼 스튜디오 업데이트 시 잠김 파일 경고 - Visual Studio Standard Collector Service 150 (VSStandardCollectorService150)
13987정성태8/7/20251280닷넷: 2351. C# 14 - (6) event와 생성자에도 partial 메서드 적용파일 다운로드1
13986정성태8/6/20251326닷넷: 2350. C# 14 - (5) 람다 매개 변수에 접근자가 있는 경우에도 타입 생략 가능파일 다운로드1
13985정성태8/6/20251842오류 유형: 973. "wsl --install" 명령어 수행 시 "The server name or address could not be resolved"
13984정성태8/6/20251512Windows: 282. 윈도우 운영체제에 추가된 ssh 서버(Win32-OpenSSH)
13983정성태8/4/20251732오류 유형: 972. Microsoft.Data.SqlClient 6.1.0 버전부터 .NET 8 이상만 지원
13982정성태8/2/20252017개발 환경 구성: 753. CentOS 7 컨테이너 내에서 openssh 서버 호스팅
13981정성태8/1/20251698오류 유형: 971. CentOS 7에서 yum 사용 시 "Could not resolve host: mirrorlist.centos.org; Unknown error"
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...