unit _fmMain;

interface

uses
  RyuMPEG,
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    OpenDialog1: TOpenDialog;
    Memo1: TMemo;
    Image1: TImage;
    procedure Button1Click(Sender: TObject);
  private
    FHandle : pointer;
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  iErrorCode : integer;
  MediaInfo : TMediaInfo;
  Buffer : pointer;
  Size : integer;
  PacketType : integer;
  Position : integer;
  VideoBuffer : pointer;
begin
  Image1.Picture.Bitmap.PixelFormat := pf32bit;

  GetMem(Buffer, 16 * 1024 * 1024);

  if OpenDialog1.Execute then begin
    FHandle := openRyuMPEG(PAnsiChar(AnsiString(OpenDialog1.FileName)), iErrorCode);

    if iErrorCode <> 0 then
      raise Exception.Create('Error Message');

    getMediaInfo(FHandle, MediaInfo);

    Memo1.Lines.Add(StrPas(MediaInfo.AudioInfoString));
    Memo1.Lines.Add(StrPas(MediaInfo.VideoInfoString));

    Image1.Picture.Bitmap.Width  := MediaInfo.VideoInfo.Width;
    Image1.Picture.Bitmap.Height := MediaInfo.VideoInfo.Height;

    GetMem(VideoBuffer, MediaInfo.VideoInfo.Width * MediaInfo.VideoInfo.Height * 4);

    while true do begin
      if not readData(FHandle, Buffer, Size, PacketType, Position) then Break;
      Memo1.Lines.Add(Format('Size: %d, PacketType: %d, Position: %d', [Size, PacketType, Position]));

      if PacketType = VIDEO_PACKET then begin
        if decodeVideoData(FHandle, Buffer, Size, VideoBuffer) then begin
          BitmapUpsideDown(VideoBuffer, Image1.Picture.Bitmap);
          Image1.Repaint;
          Break;
        end;
      end;
    end;

    FreeMem(VideoBuffer);

    closeRyuMPEG(FHandle);
  end;

  FreeMem(Buffer);
end;

end.
