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)를 이용한 remuxing.c 예제 포팅

지난 글에 이어,

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

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

using FFmpeg.AutoGen;
using FFmpeg.AutoGen.Example;
using System;
using System.IO;

namespace remuxing
{
    internal unsafe class Program
    {
        static unsafe void log_packet(AVFormatContext* fmt_ctx, AVPacket* pkt, string tag)
        {
            AVRational* time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;

            Console.WriteLine($"{tag}: pts:{FFmpegHelper.av_ts2str(pkt->pts)} pts_time:{FFmpegHelper.av_ts2timestr(pkt->pts, time_base)}"
                + $" dts:{FFmpegHelper.av_ts2str(pkt->dts)} dts_time:{FFmpegHelper.av_ts2timestr(pkt->dts, time_base)}"
                + $" duration:{FFmpegHelper.av_ts2str(pkt->duration)} duration_time:{FFmpegHelper.av_ts2timestr(pkt->duration, time_base)}"
                + $" stream_index: {pkt->stream_index}");
        }

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

            AVOutputFormat* ofmt = null;
            AVFormatContext* ifmt_ctx = null;
            AVFormatContext* ofmt_ctx = null;
            AVPacket* pkt = null;
            string in_filename, out_filename;
            int ret, i;
            int stream_index = 0;
            int* stream_mapping = null;
            int stream_mapping_size = 0;

            string dirPath = Path.GetDirectoryName(typeof(Program).Assembly.Location) ?? "";
            string filename = "sample-10s.mp4";
            in_filename = Path.Combine(dirPath, "..", "..", "..", "Samples", filename);
            out_filename = Path.Combine(dirPath, Path.ChangeExtension(filename, "mkv"));

            pkt = ffmpeg.av_packet_alloc();
            if (pkt == null)
            {
                Console.WriteLine("Could not allocate AVPacket");
                return 1;
            }

            if ((ret = ffmpeg.avformat_open_input(&ifmt_ctx, in_filename, null, null)) < 0)
            {
                Console.WriteLine($"Could not open input fiel '{in_filename}'");
                goto end;
            }

            if ((ret = ffmpeg.avformat_find_stream_info(ifmt_ctx, null)) < 0)
            {
                Console.WriteLine("Failed to retrieve input stream information");
                goto end;
            }

            ffmpeg.av_dump_format(ifmt_ctx, 0, in_filename, 0);

            ffmpeg.avformat_alloc_output_context2(&ofmt_ctx, null, null, out_filename);
            if (ofmt_ctx == null)
            {
                Console.WriteLine("Could not create output context");
                ret = ffmpeg.AVERROR_UNKNOWN;
                goto end;
            }

            stream_mapping_size = (int)ifmt_ctx->nb_streams;
            stream_mapping = (int *)ffmpeg.av_calloc((ulong)stream_mapping_size, 4);
            if (stream_mapping == null)
            {
                ret = ffmpeg.AVERROR(ffmpeg.ENOMEM);
                goto end;
            }

            ofmt = ofmt_ctx->oformat;

            for (i = 0; i < ifmt_ctx->nb_streams; i ++)
            {
                AVStream* out_stream;
                AVStream* in_stream = ifmt_ctx->streams[i];
                AVCodecParameters* in_codecpar = in_stream->codecpar;

                if (in_codecpar->codec_type != AVMediaType.AVMEDIA_TYPE_AUDIO &&
                    in_codecpar->codec_type != AVMediaType.AVMEDIA_TYPE_VIDEO &&
                    in_codecpar->codec_type != AVMediaType.AVMEDIA_TYPE_SUBTITLE)
                {
                    stream_mapping[i] = -1;
                    continue;
                }

                stream_mapping[i] = stream_index++;

                out_stream = ffmpeg.avformat_new_stream(ofmt_ctx, null);
                if (out_stream == null)
                {
                    Console.WriteLine("Failed allocating output stream");
                    ret = ffmpeg.AVERROR_UNKNOWN;
                    goto end;
                }

                ret = ffmpeg.avcodec_parameters_copy(out_stream->codecpar, in_codecpar);
                if (ret < 0)
                {
                    Console.WriteLine("Failed to copy codec parameters");
                    goto end;
                }

                out_stream->codecpar->codec_tag = 0;
            }

            ffmpeg.av_dump_format(ofmt_ctx, 0, out_filename, 1);

            if ((ofmt->flags & ffmpeg.AVFMT_NOFILE) == 0)
            {
                ret = ffmpeg.avio_open(&ofmt_ctx->pb, out_filename, ffmpeg.AVIO_FLAG_WRITE);
                if (ret < 0)
                {
                    Console.WriteLine($"Could not open output file '{out_filename}");
                    goto end;
                }
            }

            ret = ffmpeg.avformat_write_header(ofmt_ctx, null);
            if (ret < 0)
            {
                Console.WriteLine("Error occurred when opening output file");
                goto end;
            }

            while (true)
            {
                AVStream* in_stream;
                AVStream* out_stream;

                ret = ffmpeg.av_read_frame(ifmt_ctx, pkt);
                if (ret < 0)
                {
                    break;
                }

                in_stream = ifmt_ctx->streams[pkt->stream_index];
                if (pkt->stream_index >= stream_mapping_size || stream_mapping[pkt->stream_index] < 0)
                {
                    ffmpeg.av_packet_unref(pkt);
                    continue;
                }

                pkt->stream_index = stream_mapping[pkt->stream_index];
                out_stream = ofmt_ctx->streams[pkt->stream_index];
                log_packet(ifmt_ctx, pkt, "in");

                ffmpeg.av_packet_rescale_ts(pkt, in_stream->time_base, out_stream->time_base);
                pkt->pos = -1;
                log_packet(ofmt_ctx, pkt, "out");

                ret = ffmpeg.av_interleaved_write_frame(ofmt_ctx, pkt);
                if (ret < 0)
                {
                    Console.WriteLine("Error muxing packet");
                    break;
                }
            }

            ffmpeg.av_write_trailer(ofmt_ctx);

        end:
            ffmpeg.av_packet_free(&pkt);
            ffmpeg.avformat_close_input(&ifmt_ctx);

            if (ofmt_ctx != null && (ofmt->flags & ffmpeg.AVFMT_NOFILE) == 0)
            {
                ffmpeg.avio_closep(&ofmt_ctx->pb);
            }

            ffmpeg.avformat_free_context(ofmt_ctx);

            ffmpeg.av_freep(&stream_mapping);

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

            return 0;
        }
    }
}

몇 개의 확장자로 예제 비디오 파일을 테스트해 봤더니 avi, vob, mpeg로는 각각 다음과 같은 식의 오류가 발생했습니다.

avi: 
    H.264 bitstream malformed, no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it ('-bsf:v h264_mp4toannexb' option with ffmpeg)
    Error muxing packet
    Error occurred: Invalid data found when processing input

vob:
    [svcd @ 000001ecb820b380] VBV buffer size not set, using default size of 230KB
    If you want the mpeg file to be compliant to some specification
    Like DVD, VCD or others, make sure you set the correct buffer size
    [svcd @ 000001ecb820b380] Unsupported audio codec.Must be one of mp1, mp2, mp3, 16 - bit pcm_dvd, pcm_s16be, ac3 or dts.
    Error occurred when opening output file
    Error occurred: Invalid argument

mpeg: 
    [mpeg @ 0000020de269b380] VBV buffer size not set, using default size of 230KB
    If you want the mpeg file to be compliant to some specification
    Like DVD, VCD or others, make sure you set the correct buffer size
    [mpeg @ 0000020de269b380] Unsupported audio codec.Must be one of mp1, mp2, mp3, 16 - bit pcm_dvd, pcm_s16be, ac3 or dts.
    Error occurred when opening output file
    Error occurred: Invalid argument

에러 메시지로 보아, vob와 mpeg의 경우에는 오디오 코덱을 바꾸면 될 것도 같습니다.

반면, mkv, asf, mov, vob, flv, mp4, ts로는 다음과 같은 메시지와 함께 변경이 잘 되었습니다.

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '...[생략]...\..\..\..\Samples\sample-10s.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.44.100
  Duration: 00:00:10.24, start: 0.000000, bitrate: 4285 kb/s
  Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 4207 kb/s, 29.97 fps, 29.97 tbr, 30k tbn (default)
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
  Stream #0:1[0x2](eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 121 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
      vendor_id       : [0][0][0][0]
Output #0, mov, to '...[생략]...\sample-10s.mov':
  Stream #0:0: Video: h264 (High), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], q=2-31, 4207 kb/s
  Stream #0:1: Audio: aac (LC), 44100 Hz, stereo, fltp, 121 kb/s
in: pts:0 pts_time:NOPTS dts:-2002 dts_time:-0.0667333 duration:1001 duration_time:0.0333667 stream_index: 0
out: pts:0 pts_time:NOPTS dts:-6006 dts_time:-0.0667333 duration:3003 duration_time:0.0333667 stream_index: 0
in: pts:4004 pts_time:0.133467 dts:-1001 dts_time:-0.0333667 duration:1001 duration_time:0.0333667 stream_index: 0
out: pts:12012 pts_time:0.133467 dts:-3003 dts_time:-0.0333667 duration:3003 duration_time:0.0333667 stream_index: 0
...[생략]...
out: pts:448512 pts_time:10.1703 dts:448512 dts_time:10.1703 duration:1024 duration_time:0.02322 stream_index: 1
in: pts:449536 pts_time:10.1936 dts:449536 dts_time:10.1936 duration:990 duration_time:0.022449 stream_index: 1
out: pts:449536 pts_time:10.1936 dts:449536 dts_time:10.1936 duration:990 duration_time:0.022449 stream_index: 1

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

참고로, 다음의 글에 있는 소스 코드도 함께 보시면 좀 더 친숙할 것입니다. ^^

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

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




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







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

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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13221정성태1/19/20234162Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234313오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20233872Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233795VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234389디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234653디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236158Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235728.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235269오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235028기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235112웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234132Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234028Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20233961.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224270.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224474.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224871.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224152.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224285.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224661기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225286오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224161오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224449개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224325.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224267.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
13196정성태12/16/20224397.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...