unit AudioTTA;

interface

uses KOL, ATLCommon, TagID3v1, TagID3v2, TagAPE;

type TTTAAudioInfo = PAudioInfo;

function NewAudioTTA: TTTAAudioInfo;

implementation

uses ATLLib;

type
  TTTAHeader = packed record
    SignatureChunk: array[0..3] of Char;
    AudioFormat: Word;
    NumChannels: Word;
    BitsPerSample: Word;
    SampleRate: Longword;
    DataLength: Longword;
    CRC32: Longword;
  end;

type
  TAudioTTA = object(TAudioInfo)
  private
  end;


function AudioTTAReader(const AFileName: KOLstring; AudioInfo: TTTAAudioInfo): Boolean; forward;

function NewAudioTTA: TTTAAudioInfo;
begin
    New(Result, Create);
    with TAudioTTA(Result^) do begin
      TagAdd(tID3v1, NewTagID3v1);
      TagAdd(tID3v2, NewTagID3v2);
      TagAdd(tAPE, NewTagAPE);
      FAudioVendor:= aTTA;
      FExistsProps:= [apSampleRate, apBitrate, apChannels, apBits, apSamples, apDuration, apRatio];
      FReader:= AudioTTAReader;
    end;
end;

function AudioTTAReader(const AFileName: KOLstring; AudioInfo: TTTAAudioInfo): Boolean;
var SourceFile: PStream;
    Header: TTTAHeader;
    //    TagSize: Int64;
begin
    with TAudioTTA(AudioInfo^) do begin
      Result:= False;
      try
        ResetData;

        try
          SourceFile:= OpenFileRead(AFileName);

          TagInfo[tID3v2].ReadFromFile(AFileName);
          TagInfo[tID3v1].ReadFromFile(AFileName);
          TagInfo[tAPE].ReadFromFile(AFileName);
  //        TagSize:= TagInfo[tID3v1].TagSize + PTagID3v1(TagInfo[tID3v1]).Lyrics.TagSize + TagInfo[tID3v2].TagSize + TagInfo[tAPE].TagSize;

          FFileSize:= SourceFile.Size;

          if TagInfo[tID3v2].Exists then SourceFile.Seek(TagInfo[tID3v2].TagSize, spBegin);

          if (SourceFile.Read(Header, SizeOf(TTTAHeader)) <> SizeOf(TTTAHeader)) or
             (Header.SignatureChunk <> 'TTA1') then Exit;

          FFileSize:= SourceFile.Size;
          FValid:= TRUE;

          FChannels:= Header.NumChannels;
          FBits:= Header.BitsPerSample;
          FSampleRate:= Header.SampleRate;
          FSamples:= Header.DataLength;
          FBitrate:= 8 * Round(Header.DataLength  / (FSamples / FSampleRate) / 1000);
          FDuration:= Header.DataLength / Header.SampleRate;
          FRatio:= Header.DataLength / (FSamples * (FChannels * FBits / 8)) * 100;

          {$IFDEF USE_OtherAudioProps}
          OtherProps.Add('AudioFormat='+Int2Str(Header.AudioFormat));
          OtherProps.Add('CRC='+format('%u',     [Header.CRC32]));
          {$ENDIF}

          Result:= True;

        finally
          SourceFile.free;
        end;
      except
      end;
    end;
end;

end.
