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 저장 부분을 어떻게든 성공시켜야겠습니다. ^^
정성태

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12206정성태4/2/202018374오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015039스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015059스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202017867오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021136개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018368오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018473VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016122오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019504오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018753VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202015923오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018248.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202020969오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202017856개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202019871개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021002개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015549오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021168개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202025988Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015505오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017375오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202017940오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202019874오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202017676오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202019167.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202019450기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...