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

비밀번호

댓글 작성자
 




... 121  122  123  124  125  126  127  128  129  130  131  [132]  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1755정성태9/22/201434200오류 유형: 241. Unity Web Player를 설치해도 여전히 설치하라는 화면이 나오는 경우 [4]
1754정성태9/22/201424538VC++: 80. 내 컴퓨터에서 C++ AMP 코드가 실행이 될까요? [1]
1753정성태9/22/201420569오류 유형: 240. Lync로 세미나 참여 시 소리만 들리지 않는 경우 [1]
1752정성태9/21/201441019Windows: 100. 윈도우 8 - RDP 연결을 이용해 VNC처럼 사용자 로그온 화면을 공유하는 방법 [5]
1751정성태9/20/201438901.NET Framework: 464. 프로세스 간 통신 시 소켓 필요 없이 간단하게 Pipe를 열어 통신하는 방법 [1]파일 다운로드1
1750정성태9/20/201423818.NET Framework: 463. PInvoke 호출을 이용한 비동기 파일 작업파일 다운로드1
1749정성태9/20/201423719.NET Framework: 462. 커널 객체를 위한 null DACL 생성 방법파일 다운로드1
1748정성태9/19/201425362개발 환경 구성: 238. [Synergy] 여러 컴퓨터에서 키보드, 마우스 공유
1747정성태9/19/201428366오류 유형: 239. psexec 실행 오류 - The system cannot find the file specified.
1746정성태9/18/201426021.NET Framework: 461. .NET EXE 파일을 닷넷 프레임워크 버전에 상관없이 실행할 수 있을까요? - 두 번째 이야기 [6]파일 다운로드1
1745정성태9/17/201422989개발 환경 구성: 237. 리눅스 Integration Services 버전 업그레이드 하는 방법 [1]
1744정성태9/17/201430987.NET Framework: 460. GetTickCount / GetTickCount64와 0x7FFE0000 주솟값 [4]파일 다운로드1
1743정성태9/16/201420956오류 유형: 238. 설치 오류 - Failed to get size of pseudo bundle
1742정성태8/27/201426926개발 환경 구성: 236. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 [2]
1741정성태8/26/201421304.NET Framework: 459. GetModuleHandleEx로 알아보는 .NET 메서드의 DLL 모듈 관계파일 다운로드1
1740정성태8/25/201432474.NET Framework: 458. 닷넷 GC가 순환 참조를 해제할 수 있을까요? [2]파일 다운로드1
1739정성태8/24/201426472.NET Framework: 457. 교착상태(Dead-lock) 해결 방법 - Lock Leveling [2]파일 다운로드1
1738정성태8/23/201422023.NET Framework: 456. C# - CAS를 이용한 Lock 래퍼 클래스파일 다운로드1
1737정성태8/20/201419691VS.NET IDE: 93. Visual Studio 2013 동기화 문제
1736정성태8/19/201425552VC++: 79. [부연] CAS Lock 알고리즘은 과연 빠른가? [2]파일 다운로드1
1735정성태8/19/201418134.NET Framework: 455. 닷넷 사용자 정의 예외 클래스의 최소 구현 코드 - 두 번째 이야기
1734정성태8/13/201419785오류 유형: 237. Windows Media Player cannot access the file. The file might be in use, you might not have access to the computer where the file is stored, or your proxy settings might not be correct.
1733정성태8/13/201426269.NET Framework: 454. EmptyWorkingSet Win32 API를 사용하는 C# 예제파일 다운로드1
1732정성태8/13/201434411Windows: 99. INetCache 폴더가 다르게 보이는 이유
1731정성태8/11/201426989개발 환경 구성: 235. 점(.)으로 시작하는 파일명을 탐색기에서 만드는 방법
1730정성태8/11/201422083개발 환경 구성: 234. Royal TS의 터미널(Terminal) 연결에서 한글이 깨지는 현상 해결 방법
... 121  122  123  124  125  126  127  128  129  130  131  [132]  133  134  135  ...