unit cdrom;

interface

uses Config, Service;

const
  BX_CD_FRAMESIZE = 2048;

const
  CD_FRAMESIZE = 2048;

type
  bx_cdrom = class
    a:        integer;
    cdhandle: THandle;
    constructor Init (const s: string);
    destructor Done;
    function insert_cdrom (const dev: string): boolean;
    procedure eject_cdrom;
    function read_toc (buf: PChar; length: integer; msf: word;
      start_track: integer): boolean;
    function capacity: longword;
    procedure read_block (buf: puint8; lba: integer);
  end;

implementation

uses Windows, SysUtils;

constructor bx_cdrom.Init (const s: string);
  begin
    inherited;
    cdhandle := $FFFFFFFF;
  end;

function bx_cdrom.insert_cdrom (const dev: string): boolean;
  begin
    cdHandle := CreateFile(PChar(dev), GENERIC_READ, 0, 0, OPEN_EXISTING,
      FILE_FLAG_RANDOM_ACCESS, 0);

    if cdHandle = $FFFFFFFF then
      BX_PANIC('Не могу инициализировать привод компакт дисков!');

    Result := not (cdHandle = $FFFFFFFF);
  end;

procedure bx_cdrom.eject_cdrom;
  begin
    if cdHandle <> $FFFFFFFF then
      begin
      CloseHandle(cdHandle);
      cdHandle := $FFFFFFFF;
      end;
  end;

function bx_cdrom.read_toc (buf: PChar; length: integer; msf: word;
  start_track: integer): boolean;
  begin
    BX_INFO('read toc not implemented');
    Result := True;
  end;

function bx_cdrom.capacity: longword;
  begin
    Result := Windows.GetFileSize(cdHandle, nil);
  end;

procedure bx_cdrom.read_block (buf: puint8; lba: integer);
  var
    n: DWORD;
  begin
    SetFilePointer(cdHandle, lba * BX_CD_FRAMESIZE, nil, FILE_BEGIN);
    ReadFile(cdHandle, buf^, BX_CD_FRAMESIZE, n, nil);
  end;

destructor bx_cdrom.Done;
  begin
    if cdHandle <> $FFFFFFFF then
      begin
      CloseHandle(cdHandle);
      cdHandle := $FFFFFFFF;
      end;
  end;

end.
