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

... 121  122  123  124  125  126  127  128  129  [130]  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1805정성태11/5/201421876.NET Framework: 476. Visual Studio에서 Mono용 Profiler 개발 [3]파일 다운로드1
1804정성태11/5/201428116.NET Framework: 475. ETW(Event Tracing for Windows)를 C#에서 사용하는 방법 [9]파일 다운로드1
1803정성태11/4/201420219오류 유형: 261. Windows Server Backup 오류 - Error in backup of E:\$Extend\$RmMetadata\$TxfLog
1802정성태11/4/201422207오류 유형: 260. 이벤트 로그 - Windows Error Reporting / AEAPPINVW8
1801정성태11/4/201427436오류 유형: 259. 이벤트 로그 - Windows Error Reporting / IPX Assertion / KorIME.exe [1]
1800정성태11/4/201418218오류 유형: 258. 이벤트 로그 - Starting a SMART disk polling operation in Automatic mode.
1799정성태11/4/201422971오류 유형: 257. 이벤트 로그 - The WMI Performance Adapter service entered the stopped state.
1798정성태11/4/201431730오류 유형: 256. 이벤트 로그 - The WinHTTP Web Proxy Auto-Discovery Service service entered the stopped state. [1]
1797정성태11/4/201417397오류 유형: 255. 이벤트 로그 - The Adobe Flash Player Update Service service entered the stopped state.
1796정성태10/30/201424441개발 환경 구성: 249. Visual Studio 2013에서 Mono 컴파일하는 방법
1795정성태10/29/201426973개발 환경 구성: 248. Lync 2013 서버 설치 방법
1794정성태10/29/201422419개발 환경 구성: 247. "Microsoft Office 365 Enterprise E3" 서비스에 대한 간략 소개
1793정성태10/27/201423038.NET Framework: 474. C# - chromiumembedded 사용 - 두 번째 이야기 [2]파일 다운로드1
1792정성태10/27/201423180.NET Framework: 473. WebClient 객체에 쿠키(Cookie)를 사용하는 방법
1791정성태10/22/201422912VC++: 83. G++ - 템플릿 클래스의 iterator 코드 사용에서 발생하는 컴파일 오류 [5]
1790정성태10/22/201418438오류 유형: 254. NETLOGON Service is paused on [... AD Server...]
1789정성태10/22/201421045오류 유형: 253. 이벤트 로그 - The client-side extension could not remove user policy settings for '...'
1788정성태10/22/201423111VC++: 82. COM 프로그래밍에서 HRESULT 타입의 S_FALSE는 실패일까요? 성공일까요? [2]
1787정성태10/22/201431289오류 유형: 252. COM 개체 등록시 0x8002801C 오류가 발생한다면?
1786정성태10/22/201432630디버깅 기술: 65. 프로세스 비정상 종료 시 "Debug Diagnostic Tool"를 이용해 덤프를 남기는 방법 [3]파일 다운로드1
1785정성태10/22/201421854오류 유형: 251. 이벤트 로그 - Load control template file /_controltemplates/TaxonomyPicker.ascx failed [1]
1784정성태10/22/201429935.NET Framework: 472. C/C++과 C# 사이의 메모리 할당/해제 방법파일 다운로드1
1783정성태10/21/201423348VC++: 81. 프로그래밍에서 borrowing의 개념
1782정성태10/21/201420083오류 유형: 250. 이벤트 로그 - Application Server job failed for service instance Microsoft.Office.Server.Search.Administration.SearchServiceInstance
1781정성태10/21/201420506디버깅 기술: 64. new/delete의 짝이 맞는 경우에도 메모리 누수가 발생한다면?
1780정성태10/15/201424157오류 유형: 249. The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID
... 121  122  123  124  125  126  127  128  129  [130]  131  132  133  134  135  ...