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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11049정성태9/24/201620913오류 유형: 357. 윈도우 백업 시 오류 - 0x81000037
11048정성태9/24/201621898VC++: 100. 전역 변수 유형별 실행 파일 크기 차이점
11047정성태9/21/201625750기타: 61. algospot.com - 양자화(Quantization) 문제 [2]파일 다운로드1
11046정성태9/15/201627358개발 환경 구성: 298. Windows 10 - bash 실행 시 시작 디렉터리 자동 변경
11045정성태9/15/201620053Windows: 119. Windows 10 - bash 명령어 창을 실행했는데 바로 닫히는 경우
11044정성태9/15/201620300VS.NET IDE: 112. Visual Studio 확장 - 편집 화면 내에서 링크를 누르면 외부 웹 브라우저에서 열기
11043정성태9/15/201621711.NET Framework: 606. .NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법 [1]파일 다운로드1
11042정성태9/14/201619867오류 유형: 356. Unknown custom metadata item kind: 6
11041정성태9/10/201619348.NET Framework: 605. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
11040정성태9/10/201626654.NET Framework: 604. C# Windows Forms - Drag & Drop 예제 코드 [2]파일 다운로드1
11039정성태9/9/201623160오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201624988VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201628239.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201624730개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201620374오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201624417개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201622252오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201621462개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201617717오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201620267VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201627395.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201621491오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201622557.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201623529Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201622220개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621527오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...