0

When I copy a video stream from a source-file to a target-file using a SourceReader and a SinkWriter, the target file is unplayable, if the source-video has been encoded with HEVC.

I've tried to create the smallest example to reproduce my problem. Written in Delphi, but should be easy enough to understand.

Edit: The media-foundation headers necessary to compile the code can be found at https://github.com/FactoryXCode/MfPack

Steps to reproduce problem with the procedures below: Create a video showing a blue frame encoded with HEVC:

WriteBlueMovie('MyVideoFile.mp4',MFVideoFormat_HEVC);

Copy the video stream to another file:

CopyVideoStream('MyVideoFile.mp4','MyFileCopy.mp4');

MyFileCopy contains a video stream, but the media-type info is missing. As a result it cannot be played. The same works, when MFVideoFormat_H264 is used instead.

Eventually I would like to expand CopyVideoStream to a muxer, so I need to copy the video stream sample by sample.

What can I do so the output file contains the correct stream header for the video stream?

Thanks in advance.

uses
  System.SysUtils,
  WinApi.Windows,
  Winapi.ActiveX,
  VCL.Dialogs,
  // mfPack headers
  Winapi.MediaFoundationApi.MfApi,
  Winapi.MediaFoundationApi.MfUtils,
  Winapi.MediaFoundationApi.MfReadWrite,
  Winapi.MediaFoundationApi.Mfobjects,
  Winapi.MediaFoundationApi.CodecApi,
  Winapi.ActiveX.PropIdl,
  Winapi.MediaFoundationApi.MfIdl;
procedure WriteBlueMovie(const OutputFile: string; Encoder: TGUID);
var
  pSinkWriter: IMFSinkWriter;
  Count: DWord;
  attribs: IMFAttributes;
  pMediaTypeOut, pMediaTypeIn: IMFMediaType;
  VideoStream: DWord;
  Time, Duration: int64;
  pBuffer: IMFMediaBuffer;
  BufferSize: DWord;
  BlueRef: DWord;
  pData: PByte;
  pSample: IMFSample;
  i: integer;
  PCR: PDWord;
  hrCoInit: HResult;
const
  Blue: TRGBQuad = (rgbBlue: 255; rgbGreen: 0; rgbRed: 0; rgbReserved: 0);

const
  ProcName = 'WriteBlueMovie';
  //turn return of fail for HResult into exception
  procedure CheckFail(hr: HResult);
  begin
    inc(Count);
    if Failed(hr) then
    begin
      if succeeded(hrCoInit) then
        CoUninitialize;
      raise Exception.Create('Error in ' + ProcName + ' in call nr. ' +
        IntToStr(Count) + 'with error code $' + IntToHex(hr));
    end;
  end;

begin
  Count := 0;
  hrCoInit := CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
  CheckFail(hrCoInit);
  CheckFail(MFStartup(MF_VERSION));

  // Create attributes for the SinkWriter
  CheckFail(MFCreateAttributes(attribs, 4));
  CheckFail(attribs.SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS,
    UInt32(true)));
  // Enable quality based encoding
  CheckFail(attribs.SetUINT32(CODECAPI_AVEncCommonRateControlMode, 3));
  CheckFail(attribs.SetUINT32(CODECAPI_AVEncCommonQuality, 70));
  CheckFail(attribs.SetUINT32(CODECAPI_AVEncCommonQualityVsSpeed, 70));
  // Create the SinkWriter
  CheckFail(MFCreateSinkWriterFromURL(PWideChar(OutputFile), nil, attribs,
    pSinkWriter));

  // Configure the output format
  CheckFail(MFCreateMediaType(pMediaTypeOut));
  CheckFail(pMediaTypeOut.SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video));

  // !!!!!!!!!!!!!!!!!!!
  // Encoder = MFVideoFormat_H264 below will work for the copy, Encoder = MFVideoFormat_HEVC will not.
  CheckFail(pMediaTypeOut.SetGUID(MF_MT_SUBTYPE, Encoder));
  // !!!!!!!!!!!!!!!!!!

  CheckFail(pMediaTypeOut.SetUINT32(MF_MT_INTERLACE_MODE,
    MFVideoInterlace_Progressive));
  CheckFail(MFSetAttributeSize(pMediaTypeOut, MF_MT_FRAME_SIZE, 640, 480));
  CheckFail(MFSetAttributeRatio(pMediaTypeOut, MF_MT_FRAME_RATE, 30, 1));
  // force fixed frame rate
  CheckFail(MFSetAttributeRatio(pMediaTypeOut,
    MF_MT_FRAME_RATE_RANGE_MIN, 30, 1));
  CheckFail(MFSetAttributeRatio(pMediaTypeOut,
    MF_MT_FRAME_RATE_RANGE_MAX, 30, 1));
  CheckFail(MFSetAttributeRatio(pMediaTypeOut, MF_MT_PIXEL_ASPECT_RATIO, 1, 1));

  // Add stream to the sinkwriter
  CheckFail(pSinkWriter.AddStream(pMediaTypeOut, VideoStream));

  // Configure the input format
  CheckFail(MFCreateMediaType(pMediaTypeIn));
  CheckFail(pMediaTypeIn.SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video));
  CheckFail(pMediaTypeIn.SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32));
  CheckFail(pMediaTypeIn.SetUINT32(MF_MT_INTERLACE_MODE,
    MFVideoInterlace_Progressive));
  CheckFail(MFSetAttributeSize(pMediaTypeIn, MF_MT_FRAME_SIZE, 640, 480));
  CheckFail(MFSetAttributeRatio(pMediaTypeIn, MF_MT_FRAME_RATE, 30, 1));
  // force fixed frame rate
  CheckFail(MFSetAttributeRatio(pMediaTypeIn,
    MF_MT_FRAME_RATE_RANGE_MIN, 30, 1));
  CheckFail(MFSetAttributeRatio(pMediaTypeIn,
    MF_MT_FRAME_RATE_RANGE_MAX, 30, 1));
  CheckFail(MFSetAttributeRatio(pMediaTypeIn, MF_MT_PIXEL_ASPECT_RATIO, 1, 1));

  // Set the input format of the sinkwriter
  CheckFail(pSinkWriter.SetInputMediaType(VideoStream, pMediaTypeIn, nil));

  // Timing
  Time := 0;
  // Duration of one frame in units of 100 Nanoseconds
  Duration := round(1000 * 10000 / 30);

  // Create a media buffer holding one blue frame
  BufferSize := 4 * 640 * 480;
  // Is this really necessary? I think not. A typecast DWord(Blue) does the same.
  CopyRgbQuadToClrRef(Blue, BlueRef);
  CheckFail(MFCreateMemoryBuffer(BufferSize, pBuffer));
  CheckFail(pBuffer.Lock(pData, nil, nil));
  PCR := PDWord(pData);
  for i := 1 to 640 * 480 do
  begin
    PCR^ := BlueRef;
    inc(PCR);
  end;
  CheckFail(pBuffer.Unlock);
  CheckFail(pBuffer.SetCurrentLength(BufferSize));

  // write 10 seconds of video
  CheckFail(pSinkWriter.BeginWriting);
  while Time < 10 * 1000 * 10000 do
  begin
    CheckFail(MFCreateSample(pSample));
    CheckFail(pSample.AddBuffer(pBuffer));
    CheckFail(pSample.SetSampleTime(Time));
    CheckFail(pSample.SetSampleDuration(Duration));
    CheckFail(pSinkWriter.WriteSample(VideoStream, pSample));
    inc(Time, Duration);
  end;

  // Shut down
  CheckFail(pSinkWriter.Finalize);
  CheckFail(MFShutdown);
  CoUninitialize;
end;

procedure CopyVideoStream(const InputFile, OutputFile: string);
var
  Count: integer;
  pSourceReader: IMFSourceReader;
  pSinkWriter: IMFSinkWriter;
  pMediaType: IMFMediaType;
  SourceStreamIndex, SinkStreamIndex: DWord;
  Done: boolean;
  pSample: IMFSample;
  flags: DWord;
  timestamp: int64;
  hrCoInit: HResult;
const
  ProcName = 'CopyVideoStream';
  procedure CheckFail(hr: HResult);
  begin
    inc(Count);
    if Failed(hr) then
    begin
      if succeeded(hrCoInit) then
        CoUninitialize;
      raise Exception.Create('Error in ' + ProcName + ' in call nr. ' +
        IntToStr(Count) + 'with error code $' + IntToHex(hr));
    end;
  end;

begin
  Count := 0;
  hrCoInit := CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
  CheckFail(hrCoInit);
  CheckFail(MFStartup(MF_VERSION));

  // Create sourcereader for InputFile and sinkwriter for OutputFile
  CheckFail(MFCreateSourceReaderFromURL(PWideChar(InputFile), nil,
    pSourceReader));
  CheckFail(MFCreateSinkWriterFromURL(PWideChar(OutputFile), nil, nil,
    pSinkWriter));

  // Get the media type of the 1st video stream
  CheckFail(pSourceReader.GetNativeMediaType
    (MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, pMediaType));
  CheckFail(pSourceReader.SetStreamSelection
    (MF_SOURCE_READER_FIRST_VIDEO_STREAM, true));
  // Set this media type as the output format of the source reader, maybe not necessary.
  CheckFail(pSourceReader.SetCurrentMediaType
    (MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, pMediaType));

  // Create stream in sinkwriter with the exact same mediatype
  CheckFail(pSinkWriter.AddStream(pMediaType, SinkStreamIndex));
  // Set the same media type as input format, maybe not necessary;
  CheckFail(pSinkWriter.SetInputMediaType(SinkStreamIndex, pMediaType, nil));

  //For debugging check the format of pMediaType. Always returns the correct result.
  var Encoder: TGUID;
  var EncoderName: string;
  CheckFail(pMediaType.GetGUID(MF_MT_SUBTYPE, Encoder));
  if Encoder=MFVideoFormat_H264 then
  EncoderName:='H264'
  else
  if Encoder=MFVideoFormat_HEVC then
  EncoderName:='HEVC'
  else
  EncoderName:='No Codec';
  ShowMessage('SinkWriter Encoding Format: '+EncoderName);


  CheckFail(pSinkWriter.BeginWriting());
  Done := false;
  // Loop to copy samples from source to sink
  while not Done do
  begin
    CheckFail(pSourceReader.ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0,
      @SourceStreamIndex,
      // get actual index of the stream
      @flags, // get flags for this sample
      @timestamp, // get the timestamp for this sample
      @pSample) // get the actual sample
      );
    if (pSample <> nil) then
    begin
      // push the sample to the sink writer
      CheckFail(pSinkWriter.WriteSample(SinkStreamIndex, pSample));
    end
    else if ((flags and MF_SOURCE_READERF_STREAMTICK) <> 0) then
    begin
      // signal a stream tick
      CheckFail(pSinkWriter.SendStreamTick(SinkStreamIndex, timestamp));
    end;
    if ((flags and MF_SOURCE_READERF_ENDOFSTREAM) <> 0) then
    begin
      CheckFail(pSinkWriter.NotifyEndOfSegment(SinkStreamIndex));

      Done := true;
    end;
  end;

  // Shut Down
  CheckFail(pSinkWriter.Finalize);
  CheckFail(MFShutdown);
  CoUninitialize;
end;
2
  • Your "smallest example to reproduce my problem" misses all the types and/or the uses section, naming all the units hopefully everyone/every Delphi version has.
    – AmigoJack
    Jun 10 at 6:17
  • I edited my question. If this is not acceptable, I will remove the Delphi-tag. I cannot possibly include all those header files as source. Jun 10 at 9:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.