Search code examples
c#.net-coreffmpegsharpffmpeg

How to convert from .h264 to .ts using FFmpeg wrapper for C#/.NET?


Context

I'm using FFMpegCore in my .NET Core API project that receives a .h264 file (sent in a binary format that is received and converted into a byte array) to be converted to a .ts.

I want to convert a .h264 stream into a .ts output stream using FFmpeg.

Current Approach

(...)

byte[] body;
using ( var ms = new MemoryStream() )
{
    await request.Body.CopyToAsync( ms ); // read sent .h264 data
    body = ms.ToArray();
}

var outputStream = new MemoryStream();

// FFMpegCore
await FFMpegArguments
                .FromPipeInput( new StreamPipeSource( new MemoryStream( body ) ) )
                .OutputToPipe( new StreamPipeSink( outputStream ), options => options
                .ForceFormat( VideoType.MpegTs ) )
                .ProcessAsynchronously();

// view converted ts file
await File.WriteAllBytesAsync( "output.ts", outputStream.ToArray() );

(...)

Problem

I'm not getting a working .ts file. What I'm a doing wrong? Could you please give some hint or help me with this? Even if you have other FFmpeg wrappers that you consider more suitable for this problem.

Notes:

  • I don't have the physical location of the files since this will receive the content of the files over HTTP. So, I will only have the byte array meaning that I need to use the input stream to convert to another format.
  • FFmpeg command used to test the conversion from .h264 to .ts (using files): ffmpeg -i file.h264 -an -vcodec copy -f mpegts output.ts

Solution

  • Missing the following argument: .WithVideoCodec( "h264" ) on FFMpegArguments.

    (...)
    
    byte[] body;
    using ( var ms = new MemoryStream() )
    {
        await request.Body.CopyToAsync( ms ); // read sent .h264 data
        body = ms.ToArray();
    }
    
    var outputStream = new MemoryStream();
    
    // FFMpegCore
    await FFMpegArguments
                    .FromPipeInput( new StreamPipeSource( new MemoryStream( body ) ) )
                    .OutputToPipe( new StreamPipeSink( outputStream ), options => options
                    .WithVideoCodec( "h264" ) // added this argument
                    .ForceFormat( "mpegts" ) ) // or VideoType.MpegTs
                    .ProcessAsynchronously();
    
    // view converted ts file
    await File.WriteAllBytesAsync( "output.ts", outputStream.ToArray() );
    
    (...)