Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 8개 있습니다.)
.NET Framework: 1140. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP3 오디오 파일 인코딩/디코딩하는 예제
; https://www.sysnet.pe.kr/2/0/12939

.NET Framework: 1144. C# - ffmpeg(FFmpeg.AutoGen) AVFormatContext를 이용해 ffprobe처럼 정보 출력
; https://www.sysnet.pe.kr/2/0/12948

.NET Framework: 1145. C# - ffmpeg(FFmpeg.AutoGen) - Codec 정보 열람 및 사용 준비
; https://www.sysnet.pe.kr/2/0/12949

.NET Framework: 1148.  C# - ffmpeg(FFmpeg.AutoGen) - decoding 과정
; https://www.sysnet.pe.kr/2/0/12956

.NET Framework: 1149. C# - ffmpeg(FFmpeg.AutoGen) - 비디오 프레임 디코딩
; https://www.sysnet.pe.kr/2/0/12958

.NET Framework: 1155. C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 yuv420p + rawvideo 형식의 파일로 쓰기
; https://www.sysnet.pe.kr/2/0/12966

.NET Framework: 1156. C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 h264 형식의 파일로 쓰기
; https://www.sysnet.pe.kr/2/0/12970

.NET Framework: 1160. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 qsv 디코딩
; https://www.sysnet.pe.kr/2/0/12977




C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 yuv420p + rawvideo 형식의 파일로 쓰기

자, 이제 좀 ffmpeg를 뚝딱거리다 보니 뭔가 보이는 듯합니다. ^^

이번에는 예전에 Bitmap 파일을 읽어 동영상 파일을 만든 것처럼,

C# - OpenCvSharp.VideoWriter에 BMP 파일을 1초씩 출력하는 예제
; https://www.sysnet.pe.kr/2/0/12485

ffmpeg를 이용해 PNG 파일을 Bitmap 클래스로 읽어들여 YUV420P 포맷으로 변경 후, 지난 글에서 알게 된,

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

rawvideo 형식으로 출력해 보겠습니다. 이를 위해 우선 PNG 파일을 bitmap으로 읽고 BitmapData를 이용해 BGRA 순으로 쌓인 RGB 데이터를 가져옵니다.

string bmpFilePath = @"D:\media_sample\1922x1082_sample.png";

Image img = Bitmap.FromFile(bmpFilePath);
Bitmap bmp = new Bitmap(img);
int fps = 30;
int seconds = 5;
Rectangle imgSize = new Rectangle(0, 0, img.Width, img.Height);
BitmapData bitmapData = bmp.LockBits(imgSize, ImageLockMode.ReadOnly, bmp.PixelFormat);

Console.WriteLine(img.PixelFormat); // Format32bppArgb

AVPixelFormat srcFormat = (img.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) ? AVPixelFormat.AV_PIX_FMT_BGRA
    : AVPixelFormat.AV_PIX_FMT_BGR24;

그다음, sws_scale을 이용해 이 포맷을 YUV420P로 변환하면 됩니다. 이때, sws_scale에는 원본 및 타깃 이미지와 그것의 stride 정보를 전달해야 하는데요,

우선, 원본 이미지의 data와 linesize는 BitmapData로부터 구할 수 있으므로 다음과 같이 초기화할 수 있습니다.

byte_ptrArray4 src_data = new byte_ptrArray4();
int_array4 src_linesize = new int_array4();

src_data[0] = (byte *)bitmapData.Scan0.ToPointer(); // BGRA 포맷은 단일 data[0]만 사용
src_linesize[0] = bitmapData.Stride; // data[0]의 이미지에서 한 라인에 대한 색상 정보를 담고 있는 바이트 크기

포맷 변환을 해서 YUV 데이터를 담을 데이터도 위와 같은 식으로 초기화할 수 있는데요, 하지만 실수할 수 있으므로 직접 초기화하기보다는 ffmpeg 라이브러리에서 제공하는 함수를 사용해 공간을 할당받는 것도 가능합니다.

byte_ptrArray4 dst_data = new byte_ptrArray4();
int_array4 dst_linesize = new int_array4();
AVPixelFormat dst_pix_fmt = AVPixelFormat.AV_PIX_FMT_YUV420P;

if ((ret = ffmpeg.av_image_alloc(ref dst_data, ref dst_linesize, img.Width, img.Height, dst_pix_fmt, 1)) < 0)
{
    Console.WriteLine("Could not allocate destination image");
    break;
}

int dst_bufsize = ret; // == img.Width * img.Height * 3 / 2, YUV420P 12bpp

위와 같이 av_image_alloc에 AV_PIX_FMT_YUV420P 포맷으로 Width, Height에 해당하는 정보를 전달하면 알아서 dst_data[0], dst_data[1], dst_data[2]에 메모리 할당을 하고, 그것의 dst_linesize[0], dst_linesize[1], dst_linesize[2]도 값을 채워서 반환해줍니다.

자, 그럼 준비가 되었군요. 이제 sws_scale을 이용해 다음과 같이 RGB에서 YUV로 변환을 할 수 있습니다.

SwsContext* sws_ctx = ffmpeg.sws_getContext(img.Width, img.Height, srcFormat, 
                                            img.Width, img.Height, dst_pix_fmt, 
                                            ffmpeg.SWS_BILINEAR, null, null, null);

ffmpeg.sws_scale(sws_ctx, src_data, src_linesize, 0, img.Height, dst_data, dst_linesize);

그럼, dst_data에는 변환된 YUV420P 이미지 데이터가 쌓이고, 이 버퍼의 크기를 그대로 파일에 쓰면,

ReadOnlySpan<byte> buffer = new ReadOnlySpan<byte>(dst_data[0], dst_bufsize);
fs.Write(buffer);

ffplay가 재생할 수 있는 rawvideo 형식의 파일이 생성됩니다.

참고로, rawvideo의 경우 딱히 출력 파일에 fps를 기록할 수 있는 헤더 데이터가 없습니다. 하지만, ffplay의 fps 기본값이 25이기 때문에 다음과 같은 식으로 25fps씩 5번 파일로 저장하면,

int fps = 25;
int seconds = 5;

for (int i = 0; i < fps * seconds; i++)
{
    ret = ffmpeg.sws_scale(sws_ctx, src_data, src_linesize, 0, img.Height, dst_data, dst_linesize);

    if (ret < 0)
    {
        Console.WriteLine("sws_scale failed");
        break;
    }

    ReadOnlySpan<byte> buffer = new ReadOnlySpan<byte>(dst_data[0], dst_bufsize);
    fs.Write(buffer);
}

5초 분량의 재생 시간을 갖는 rawvideo 동영상이 만들어집니다.




그나저나 align 값에 대해 알아볼까요? ^^ 가령, 아래의 코드에서 1로 주고 있는데,

if ((ret = ffmpeg.av_image_alloc(ref dst_data, ref dst_linesize, img.Width, img.Height, dst_pix_fmt, 1)) < 0)
{
    Console.WriteLine("Could not allocate destination image");
    break;
}

그럼 모든 이미지에 대해 dst_linesize[0] == (이미지의 width) 값이 나옵니다. 하지만 만약 1922x1082 이미지에 대해 align 값을 바꿔보면,

align == 1
		dst_linesize[0]	1922
		dst_linesize[1]	961	
		dst_linesize[2]	961	

align == 8
		dst_linesize[0]	1928
		dst_linesize[1]	968	
		dst_linesize[2]	968	
align == 16
		dst_linesize[0]	1936
		dst_linesize[1]	976	
		dst_linesize[2]	976	
align == 32
		dst_linesize[0]	1952
		dst_linesize[1]	992	
		dst_linesize[2]	992	

이렇게 값이 나옵니다. 즉, 1922 크기가 8, 16, 32에 대해 정확히 나눠떨어지지 않기 때문에 1922 크기가 나오지 않는 것입니다. 그런데 재미있는 것은, 저렇게 한 경우 sws_scale 함수가 실패하지는 않습니다. 대신 출력된 최종 파일을 ffplay로 재생하면 이미지가 모두 깨진 채로 나오는 정도의 차이만 있습니다.

그러니까, 속도를 높이기 위해 32나 64 정도로 나눠떨어지는지 테스트를 하고는, 그렇지 않은 경우 그냥 1을 주면 됩니다.

실제로 Width == 1922와 같은 이미지인 경우 sws_scale 함수를 실행하면 다음과 같은 경고가 떨어집니다.

[swscaler @ 000002533A660000] Warning: data is not aligned! This can lead to a speed loss

인코딩 속도가 떨어질 수 있다는 것 같은데 어쩔 수 없습니다. 입력 이미지를 1920과 같은 잘 정렬된 크기의 것으로 맞춰주는 것이 좋습니다.

어쨌든, 예제를 실행해 생성된 dat 파일을 다음과 같은 식의 ffplay로 열면 PNG 이미지가 5초 동안 재생되는 것을 확인할 수 있습니다.

D:\media_sample> ffplay -framerate 25 -autoexit -f rawvideo -pixel_format yuv420p -video_size 1922x1082 c:\temp\output\bmp2yuv420p.dat
...[생략]...
[rawvideo @ 00000235C4F7C400] Estimating duration from bitrate, this may be inaccurate
Input #0, rawvideo, from 'c:\temp\output\bmp2yuv420p.dat':
  Duration: 00:00:05.00, start: 0.000000, bitrate: 623881 kb/s
  Stream #0:0: Video: rawvideo (I420 / 0x30323449), yuv420p, 1922x1082, 623881 kb/s, 25 tbr, 25 tbn, 25 tbc
   4.94 M-V:  0.001 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0

(첨부 파일은 이 글의 예제 코드를 포함합니다.)





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







[최초 등록일: ]
[최종 수정일: 2/14/2022]

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

비밀번호

댓글 작성자
 




... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
12031정성태10/7/201916341오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201923148.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201924009제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201918904.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/201914727오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201920137.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201918381제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201920314.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201920807.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
12022정성태9/12/201924787개발 환경 구성: 458. C# 8.0 (Preview) 신규 문법을 위한 개발 환경 구성 [3]
12021정성태9/12/201940598도서: 시작하세요! C# 8.0 프로그래밍 [4]
12020정성태9/11/201923768VC++: 134. SYSTEMTIME 값 기준으로 특정 시간이 지났는지를 판단하는 함수
12019정성태9/11/201917319Linux: 23. .NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항
12018정성태9/11/201916076오류 유형: 567. IIS - Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. (D:\lowSite4\web.config line 11)
12017정성태9/11/201919945오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
12016정성태9/5/201919922오류 유형: 565. git fetch - warning: 'C:\ProgramData/Git/config' has a dubious owner: '(unknown)'.
12015정성태9/3/201925249개발 환경 구성: 457. 윈도우 응용 프로그램의 Socket 연결 시 time-out 시간 제어
12014정성태9/3/201918976개발 환경 구성: 456. 명령행에서 AWS, Azure 등의 원격 저장소에 파일 관리하는 방법 - cyberduck/duck 소개
12013정성태8/28/201921894개발 환경 구성: 455. 윈도우에서 (테스트) 인증서 파일 만드는 방법 [3]
12012정성태8/28/201926507.NET Framework: 859. C# - HttpListener를 이용한 HTTPS 통신 방법
12011정성태8/27/201926096사물인터넷: 57. C# - Rapsberry Pi Zero W와 PC 간 Bluetooth 통신 예제 코드파일 다운로드1
12010정성태8/27/201918994VS.NET IDE: 138. VSIX - DTE.ItemOperations.NewFile 메서드에서 템플릿 이름을 다국어로 설정하는 방법
12009정성태8/26/201919837.NET Framework: 858. C#/Windows - Clipboard(Ctrl+C, Ctrl+V)가 동작하지 않는다면?파일 다운로드1
12008정성태8/26/201919555.NET Framework: 857. UWP 앱에서 SQL Server 데이터베이스 연결 방법
12007정성태8/24/201918161.NET Framework: 856. .NET Framework 버전을 올렸을 때 오류가 발생할 수 있는 상황
12006정성태8/23/201921589디버깅 기술: 129. guidgen - Encountered an improper argument. 오류 해결 방법 (및 windbg 분석) [1]
... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...