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

(시리즈 글이 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)를 이용한 http_multiclient.c 예제 포팅

지난 글에 이어,

C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcode_aac.c 예제 포팅
; https://www.sysnet.pe.kr/2/0/12991

이번에는 ffmpeg 예제 중 "http_multiclient.c" 파일을 FFmpeg.AutoGen으로 포팅하겠습니다.

using FFmpeg.AutoGen;
using FFmpeg.AutoGen.Example;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

namespace http_multiclient
{
    internal unsafe class Program
    {
        static void process_client(AVIOContext* client, string in_uri)
        {
            AVIOContext* input = null;
            byte* buf = stackalloc byte[1024];
            Span<byte> buffer = new(buf, 1024);
            int ret, n, reply_code;
            byte* resource = null;
            string? text = null;

            while ((ret = ffmpeg.avio_handshake(client)) > 0)
            {
                ffmpeg.av_opt_get(client, "resource", ffmpeg.AV_OPT_SEARCH_CHILDREN, &resource);
                text = Marshal.PtrToStringAnsi(new IntPtr(resource));

                if (string.IsNullOrEmpty(text) == false)
                {
                    break;
                }

                ffmpeg.av_freep(&resource);
            }

            if (ret < 0)
            {
                goto end;
            }

            ffmpeg.av_log(client, ffmpeg.AV_LOG_TRACE, $"resource=0x{new IntPtr(resource):x}\n");

            if (text != null && text[0] == '/' /* && text.Substring(1) == in_uri */)
            {
                reply_code = 200;
            }
            else
            {
                reply_code = ffmpeg.AVERROR_HTTP_NOT_FOUND;
            }

            if ((ret = ffmpeg.av_opt_set_int(client, "reply_code", reply_code, ffmpeg.AV_OPT_SEARCH_CHILDREN)) < 0)
            {
                ffmpeg.av_log(client, ffmpeg.AV_LOG_ERROR, $"Failed to set reply_code: {FFmpegHelper.av_err2str(ret)}\n");
                goto end;
            }

            ffmpeg.av_log(client, ffmpeg.AV_LOG_TRACE, $"Set reply code to {reply_code}\n");

            while ((ret = ffmpeg.avio_handshake(client)) > 0) ;

            if (ret < 0)
            {
                goto end;
            }

            Console.WriteLine("Handshake performed");

            if (reply_code != 200)
            {
                goto end;
            }

            Console.WriteLine("Opening input file");
            if ((ret = ffmpeg.avio_open2(&input, in_uri, ffmpeg.AVIO_FLAG_READ, null, null)) < 0)
            {
                ffmpeg.av_log(input, ffmpeg.AV_LOG_ERROR, $"Failed to open input: {in_uri}: {FFmpegHelper.av_err2str(ret)}\n");
                goto end;
            }

            for (; ; )
            {
                n = ffmpeg.avio_read(input, buf, buffer.Length);
                if (n < 0)
                {
                    if (n == ffmpeg.AVERROR_EOF)
                    {
                        break;
                    }

                    ffmpeg.av_log(input, ffmpeg.AV_LOG_ERROR, $"Error reading from input: {FFmpegHelper.av_err2str(n)}\n");
                    break;
                }

                ffmpeg.avio_write(client, buf, n);
                ffmpeg.avio_flush(client);
            }

        end:
            Console.WriteLine("Flushing client");
            ffmpeg.avio_flush(client);
            Console.WriteLine("Closing clinet");
            ffmpeg.avio_close(client);
            Console.WriteLine("Closing input");
            ffmpeg.avio_close(input);
            ffmpeg.av_freep(&resource);
        }

        static unsafe int Main(string[] args)
        {
            FFmpegBinariesHelper.RegisterFFmpegBinaries();

#if DEBUG
            Console.WriteLine("Current directory: " + Environment.CurrentDirectory);
            Console.WriteLine("Running in {0}-bit mode.", Environment.Is64BitProcess ? "64" : "32");
            Console.WriteLine($"FFmpeg version info: {ffmpeg.av_version_info()}");

            Console.WriteLine();
#endif

            AVDictionary* options = null;
            AVIOContext* client = null;
            AVIOContext* server = null;
            string in_uri, out_uri;
            int ret;

            ffmpeg.av_log_set_level(ffmpeg.AV_LOG_TRACE);

            out_uri = "http://127.0.0.1:15384/";

            string dirPath = Path.GetDirectoryName(typeof(Program).Assembly.Location) ?? "";
            in_uri = Path.Combine(dirPath, "..", "..", "..", "Samples", "mpeg1video_q0.m1v");

            ffmpeg.avformat_network_init();

            if ((ret = ffmpeg.av_dict_set(&options, "listen", "2", 0)) < 0)
            {
                Console.WriteLine($"Failed to set listen mode for server: {FFmpegHelper.av_err2str(ret)}");
                return ret;
            }

            if ((ret = ffmpeg.avio_open2(&server, out_uri, ffmpeg.AVIO_FLAG_WRITE, null, &options)) < 0)
            {
                Console.WriteLine($"Failed to open server: {FFmpegHelper.av_err2str(ret)}");
                return ret;
            }

            Console.WriteLine("Entering main loop");

            for (; ;)
            {
                if ((ret = ffmpeg.avio_accept(server, &client)) < 0)
                {
                    goto end;
                }

                Console.WriteLine("Accepted client, forking/thraeding process.");

                AVIOContext** pClient = &client;

                Thread t = new Thread((obj) =>
                {
                    Console.WriteLine("Client....");
                    process_client(*pClient, in_uri);
                });

                t.Start();
            }

        end:

            ffmpeg.avio_close(server);
            if (ret < 0 && ret != ffmpeg.AVERROR_EOF)
            {
                Console.WriteLine($"Some errors occurred: {FFmpegHelper.av_err2str(ret)}");
                return 1;
            }

            return 0;
        }
    }

}

원본 "http_multiclient.c" 코드는 리눅스의 fork를 이용하지만, 위의 코드는 스레드를 이용했다는 정도의 차이가 있습니다.

잘 동작하는지 테스트까지 해볼까요? ^^

이 코드는, 예제 소개에서처럼 "This example will serve a file without decoding or demuxing it over http.Multiple clients can connect and will receive the same file."이라고, 동영상 파일에 대해 어떠한 디코딩도, 디먹싱도 하지 않습니다.

그렇다면, 클라이언트 측에서 어차피 디먹싱, 디코딩을 할 것이므로 온전한 mp4 파일을 서비스하면 될 것 같은데요,

// repo에 포함한 예제 비디오 파일

in_uri = Path.Combine(dirPath, "..", "..", "..", "Samples", "sample-10s.mp4");

그런데, 이것을 GOM 플레이어로 열었더니 재생시간은 10초 정도로 정확히 나오는데 영상은 그냥 검은 화면으로 재생이 됩니다.

혹시나 싶어, 그럼 먹싱은 하지 않고 영상만 포함하고 있는 파일을,

ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/12960

// repo에 포함한 예제 비디오 파일: 컨테이너 없이 비디오 영상만 포함
in_uri = Path.Combine(dirPath, "..", "..", "..", "Samples", "mpeg1video_q0.m1v");

서비스했더니, 이번에는 GOM 플레이어에서 해당 동영상 재생이 잘 됩니다.

http_multi_clnt_1.png

또한 ffplay로도 다음과 같은 옵션으로 재생이 잘 되고.

ffplay -autoexit http://127.0.0.1:15384/

ffplay -autoexit -f mpegvideo http://127.0.0.1:15384/

다른 입력 파일도 해볼까요? 이전에 hw_decode 포팅에서,

C# - ffmpeg(FFmpeg.AutoGen)로 하드웨어 가속기를 이용한 비디오 디코딩 예제(hw_decode.c)
; https://www.sysnet.pe.kr/2/0/12932

출력한 파일은 컨테이너도 없고, raw 형식으로 NV12 포맷으로 디코딩된 데이터를 포함하고 있습니다. 이 파일로 서비스하게 되면,

// hw_decode 예제를 실행해 얻은 파일

in_uri = @"C:\ffmpeg_autogen_cs\hw_decode\bin\Debug\test.dat";

GOM 플레이어로는 이제 재생할 수 없고, ffplay에서는 다음과 같은 옵션으로 재생할 수 있습니다.

// test.dat 파일이 1920x1080 동영상이고 nv12 raw 포맷을 가지므로.

ffplay -autoexit -f rawvideo -pixel_format nv12 -video_size 1920x1080 http://127.0.0.1:15384/

(이 글의 소스 코드는 github에 올려져 있습니다.)




그런데, 재생 시간이 좀 흥미롭습니다.

테스트를 위해 (repo의 Samples 디렉터리에 포함시킨 5.00초 분량의) file_example_MP4_1920_18MG.mp4 파일을 hw_decode 예제로 출력한 test.dat 파일을 ffplay로 fps를 지정해 재생해 보면,

ffplay -autoexit -f rawvideo -framerate 30 -pixel_format nv12 -video_size 1920x1080 test.dat

4.96 ~ 4.98초 정도의 재생 시간이 나옵니다. 이것을 http_multiclient 예제를 통해 서비스하는 것을 재생해보면,

ffplay -autoexit -f rawvideo -framerate 30 -pixel_format nv12 -video_size 1920x1080 http://127.0.0.1:15384/

대략 7.77 ~ 8.10초 정도의 재생 시간이 나옵니다. 게다가, http_multiclient를 이용해 재생하는 경우에는 -framerate 옵션의 지정이 별다른 효력이 없었습니다. 즉, -framerate를 70으로 지정해도 동일하게 약 7.8초 정도의 재생 시간이 나왔습니다.

반면, (컨테이너는 없지만) 인코딩만은 시켰던 "mpeg1video_q0.m1v" 파일로 테스트하면 원래의 5.00초 정도로 재생이 잘 됩니다.




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







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

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

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241557닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241563닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241639닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241600닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241627닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241539닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241602닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241613오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241626오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241464닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241644디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241643오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241741닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241744디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242623오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241819닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241572Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241653Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241951닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241707VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241734닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241684닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242016닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...