Debian Codegraph @

plugins/wdx/audioinfo/src/atl/OggVorbis.pas

raw
1 { *************************************************************************** }
2 { }
3 { Audio Tools Library }
4 { Class TOggVorbis - for manipulating with Ogg Vorbis file information }
5 { }
6 { http://mac.sourceforge.net/atl/ }
7 { e-mail: [email protected] }
8 { }
9 { Copyright (c) 2000-2002 by Jurgen Faul }
10 { Copyright (c) 2003-2005 by The MAC Team }
11 { }
12 { Version 1.9 (April 2005) by Gambit }
13 { - updated to unicode file access }
14 { }
15 { Version 1.83 (26 march 2005) by Kurtnoise }
16 { - Added multichannel support }
17 { }
18 { Version 1.82 (23 March 2005) by Gambit }
19 { - fixed nominal bitrate info (eg 192 was 193 sometimes) }
20 { }
21 { Version 1.81 (21 June 2004) by Gambit }
22 { - Added Encoder property }
23 { }
24 { Version 1.8 (13 April 2004) by Gambit }
25 { - Added Ratio property }
26 { }
27 { Version 1.7 (20 August 2003) by Madah }
28 { - Minor fix: changed FSampleRate into Integer }
29 { ... so that samplerates>65535 works. }
30 { }
31 { Version 1.6 (2 October 2002) }
32 { - Writing support for Vorbis tag }
33 { - Changed several properties }
34 { - Fixed bug with long Vorbis tag fields }
35 { }
36 { Version 1.2 (18 February 2002) }
37 { - Added property BitRateNominal }
38 { - Fixed bug with Vorbis tag fields }
39 { }
40 { Version 1.1 (21 October 2001) }
41 { - Support for UTF-8 }
42 { - Fixed bug with vendor info detection }
43 { }
44 { Version 1.0 (15 August 2001) }
45 { - File info: file size, channel mode, sample rate, duration, bit rate }
46 { - Vorbis tag: title, artist, album, track, date, genre, comment, vendor }
47 { }
48 { This library is free software; you can redistribute it and/or }
49 { modify it under the terms of the GNU Lesser General Public }
50 { License as published by the Free Software Foundation; either }
51 { version 2.1 of the License, or (at your option) any later version. }
52 { }
53 { This library is distributed in the hope that it will be useful, }
54 { but WITHOUT ANY WARRANTY; without even the implied warranty of }
55 { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU }
56 { Lesser General Public License for more details. }
57 { }
58 { You should have received a copy of the GNU Lesser General Public }
59 { License along with this library; if not, write to the Free Software }
60 { Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA }
61 { }
62 { *************************************************************************** }
63
64 unit OggVorbis;
65
66 interface
67
68 uses
69 Classes, SysUtils, DCClassesUtf8, DCOSUtils;
70
71 const
72 { Used with ChannelModeID property }
73 VORBIS_CM_MONO = 1; { Code for mono mode }
74 VORBIS_CM_STEREO = 2; { Code for stereo mode }
75 VORBIS_CM_MULTICHANNEL = 6; { Code for Multichannel Mode }
76
77 { Channel mode names }
78 VORBIS_MODE: array [0..3] of string = ('Unknown', 'Mono', 'Stereo', 'Multichannel');
79
80 type
81 TOggCodecType = (octVorbis, octOpus, octSpeex);
82
83 { Class TOggVorbis }
84 TOggVorbis = class(TObject)
85 private
86 { Private declarations }
87 FFileSize: Integer;
88 FChannelModeID: Byte;
89 FSampleRate: integer;
90 FBitRateNominal: Word;
91 FSamples: Integer;
92 FID3v2Size: Integer;
93 FTitle: string;
94 FArtist: string;
95 FAlbum: string;
96 FTrack: Word;
97 FDate: string;
98 FGenre: string;
99 FComment: string;
100 FVendor: string;
101 FCodec: String;
102 procedure FResetData;
103 function FGetChannelMode: string;
104 function FGetDuration: Double;
105 function FGetBitRate: Word;
106 function FHasID3v2: Boolean;
107 function FIsValid: Boolean;
108 function FGetRatio: Double;
109 function FGetEncoder: String;
110 public
111 { Public declarations }
112 constructor Create; { Create object }
113 destructor Destroy; override; { Destroy object }
114 function ReadFromFile(const FileName: String): Boolean; { Load data }
115 function SaveTag(const FileName: String): Boolean; { Save tag data }
116 function ClearTag(const FileName: String): Boolean; { Clear tag data }
117 property FileSize: Integer read FFileSize; { File size (bytes) }
118 property ChannelModeID: Byte read FChannelModeID; { Channel mode code }
119 property ChannelMode: string read FGetChannelMode; { Channel mode name }
120 property SampleRate: integer read FSampleRate; { Sample rate (hz) }
121 property BitRateNominal: Word read FBitRateNominal; { Nominal bit rate }
122 property Title: string read FTitle write FTitle; { Song title }
123 property Artist: string read FArtist write FArtist; { Artist name }
124 property Album: string read FAlbum write FAlbum; { Album name }
125 property Track: Word read FTrack write FTrack; { Track number }
126 property Date: string read FDate write FDate; { Year }
127 property Genre: string read FGenre write FGenre; { Genre name }
128 property Comment: string read FComment write FComment; { Comment }
129 property Vendor: string read FVendor; { Vendor string }
130 property Duration: Double read FGetDuration; { Duration (seconds) }
131 property BitRate: Word read FGetBitRate; { Average bit rate }
132 property ID3v2: Boolean read FHasID3v2; { True if ID3v2 tag exists }
133 property Valid: Boolean read FIsValid; { True if file valid }
134 property Ratio: Double read FGetRatio; { Compression ratio (%) }
135 property Encoder: String read FGetEncoder; { Encoder string }
136 property Codec: String read FCodec; { Codec string }
137 end;
138
139 implementation
140
141 const
142 { Ogg page header ID }
143 OGG_PAGE_ID = 'OggS';
144
145 { Vorbis parameter frame ID }
146 VORBIS_PARAMETERS_ID = #1 + 'vorbis';
147 OPUS_PARAMETERS_ID = 'OpusHead';
148 SPEEX_PARAMETERS_ID = 'Speex ';
149
150 { Vorbis tag frame ID }
151 VORBIS_TAG_ID = #3 + 'vorbis';
152 OPUS_TAG_ID = 'OpusTags';
153
154 { Max. number of supported comment fields }
155 VORBIS_FIELD_COUNT = 9;
156
157 { Names of supported comment fields }
158 VORBIS_FIELD: array [1..VORBIS_FIELD_COUNT] of string =
159 ('TITLE', 'ARTIST', 'ALBUM', 'TRACKNUMBER', 'DATE', 'GENRE', 'COMMENT',
160 'PERFORMER', 'DESCRIPTION');
161
162 { CRC table for checksum calculating }
163 CRC_TABLE: array [0..$FF] of Cardinal = (
164 $00000000, $04C11DB7, $09823B6E, $0D4326D9, $130476DC, $17C56B6B,
165 $1A864DB2, $1E475005, $2608EDB8, $22C9F00F, $2F8AD6D6, $2B4BCB61,
166 $350C9B64, $31CD86D3, $3C8EA00A, $384FBDBD, $4C11DB70, $48D0C6C7,
167 $4593E01E, $4152FDA9, $5F15ADAC, $5BD4B01B, $569796C2, $52568B75,
168 $6A1936C8, $6ED82B7F, $639B0DA6, $675A1011, $791D4014, $7DDC5DA3,
169 $709F7B7A, $745E66CD, $9823B6E0, $9CE2AB57, $91A18D8E, $95609039,
170 $8B27C03C, $8FE6DD8B, $82A5FB52, $8664E6E5, $BE2B5B58, $BAEA46EF,
171 $B7A96036, $B3687D81, $AD2F2D84, $A9EE3033, $A4AD16EA, $A06C0B5D,
172 $D4326D90, $D0F37027, $DDB056FE, $D9714B49, $C7361B4C, $C3F706FB,
173 $CEB42022, $CA753D95, $F23A8028, $F6FB9D9F, $FBB8BB46, $FF79A6F1,
174 $E13EF6F4, $E5FFEB43, $E8BCCD9A, $EC7DD02D, $34867077, $30476DC0,
175 $3D044B19, $39C556AE, $278206AB, $23431B1C, $2E003DC5, $2AC12072,
176 $128E9DCF, $164F8078, $1B0CA6A1, $1FCDBB16, $018AEB13, $054BF6A4,
177 $0808D07D, $0CC9CDCA, $7897AB07, $7C56B6B0, $71159069, $75D48DDE,
178 $6B93DDDB, $6F52C06C, $6211E6B5, $66D0FB02, $5E9F46BF, $5A5E5B08,
179 $571D7DD1, $53DC6066, $4D9B3063, $495A2DD4, $44190B0D, $40D816BA,
180 $ACA5C697, $A864DB20, $A527FDF9, $A1E6E04E, $BFA1B04B, $BB60ADFC,
181 $B6238B25, $B2E29692, $8AAD2B2F, $8E6C3698, $832F1041, $87EE0DF6,
182 $99A95DF3, $9D684044, $902B669D, $94EA7B2A, $E0B41DE7, $E4750050,
183 $E9362689, $EDF73B3E, $F3B06B3B, $F771768C, $FA325055, $FEF34DE2,
184 $C6BCF05F, $C27DEDE8, $CF3ECB31, $CBFFD686, $D5B88683, $D1799B34,
185 $DC3ABDED, $D8FBA05A, $690CE0EE, $6DCDFD59, $608EDB80, $644FC637,
186 $7A089632, $7EC98B85, $738AAD5C, $774BB0EB, $4F040D56, $4BC510E1,
187 $46863638, $42472B8F, $5C007B8A, $58C1663D, $558240E4, $51435D53,
188 $251D3B9E, $21DC2629, $2C9F00F0, $285E1D47, $36194D42, $32D850F5,
189 $3F9B762C, $3B5A6B9B, $0315D626, $07D4CB91, $0A97ED48, $0E56F0FF,
190 $1011A0FA, $14D0BD4D, $19939B94, $1D528623, $F12F560E, $F5EE4BB9,
191 $F8AD6D60, $FC6C70D7, $E22B20D2, $E6EA3D65, $EBA91BBC, $EF68060B,
192 $D727BBB6, $D3E6A601, $DEA580D8, $DA649D6F, $C423CD6A, $C0E2D0DD,
193 $CDA1F604, $C960EBB3, $BD3E8D7E, $B9FF90C9, $B4BCB610, $B07DABA7,
194 $AE3AFBA2, $AAFBE615, $A7B8C0CC, $A379DD7B, $9B3660C6, $9FF77D71,
195 $92B45BA8, $9675461F, $8832161A, $8CF30BAD, $81B02D74, $857130C3,
196 $5D8A9099, $594B8D2E, $5408ABF7, $50C9B640, $4E8EE645, $4A4FFBF2,
197 $470CDD2B, $43CDC09C, $7B827D21, $7F436096, $7200464F, $76C15BF8,
198 $68860BFD, $6C47164A, $61043093, $65C52D24, $119B4BE9, $155A565E,
199 $18197087, $1CD86D30, $029F3D35, $065E2082, $0B1D065B, $0FDC1BEC,
200 $3793A651, $3352BBE6, $3E119D3F, $3AD08088, $2497D08D, $2056CD3A,
201 $2D15EBE3, $29D4F654, $C5A92679, $C1683BCE, $CC2B1D17, $C8EA00A0,
202 $D6AD50A5, $D26C4D12, $DF2F6BCB, $DBEE767C, $E3A1CBC1, $E760D676,
203 $EA23F0AF, $EEE2ED18, $F0A5BD1D, $F464A0AA, $F9278673, $FDE69BC4,
204 $89B8FD09, $8D79E0BE, $803AC667, $84FBDBD0, $9ABC8BD5, $9E7D9662,
205 $933EB0BB, $97FFAD0C, $AFB010B1, $AB710D06, $A6322BDF, $A2F33668,
206 $BCB4666D, $B8757BDA, $B5365D03, $B1F740B4);
207
208 type
209 { Ogg page header }
210 OggHeader = packed record
211 ID: array [1..4] of AnsiChar; { Always "OggS" }
212 StreamVersion: Byte; { Stream structure version }
213 TypeFlag: Byte; { Header type flag }
214 AbsolutePosition: Int64; { Absolute granule position }
215 Serial: Integer; { Stream serial number }
216 PageNumber: Integer; { Page sequence number }
217 Checksum: Integer; { Page checksum }
218 Segments: Byte; { Number of page segments }
219 LacingValues: array [1..$FF] of Byte; { Lacing values - segment sizes }
220 end;
221
222 { Vorbis parameter header }
223 VorbisHeader = packed record
224 ID: array [1..7] of AnsiChar; { Always #1 + "vorbis" }
225 BitstreamVersion: array [1..4] of Byte; { Bitstream version number }
226 ChannelMode: Byte; { Number of channels }
227 SampleRate: Integer; { Sample rate (hz) }
228 BitRateMaximal: Integer; { Bit rate upper limit }
229 BitRateNominal: Integer; { Nominal bit rate }
230 BitRateMinimal: Integer; { Bit rate lower limit }
231 BlockSize: Byte; { Coded size for small and long blocks }
232 StopFlag: Byte; { Always 1 }
233 end;
234
235 // Opus parameter header
236 TOpusHeader = packed record
237 ID: array [1..8] of AnsiChar; { Always "OpusHead" }
238 BitstreamVersion: Byte; { Bitstream version number }
239 ChannelCount: Byte; { Number of channels }
240 PreSkip: Word;
241 SampleRate: LongWord; { Sample rate (hz) }
242 OutputGain: Word;
243 MappingFamily: Byte; { 0,1,255 }
244 end;
245
246 // Speex parameter header
247 TSpeexHeader = packed record
248 ID: array [1..8] of AnsiChar;
249 speex_version: array [1..20] of AnsiChar;
250 speex_version_id: Integer;
251 header_size: Integer;
252 rate: Integer;
253 mode: Integer;
254 mode_bitstream_version: Integer;
255 nb_channels: Integer;
256 bitrate: Integer;
257 frame_size: Integer;
258 vbr: Integer;
259 frames_per_packet: Integer;
260 extra_headers: Integer;
261 reserved1: Integer;
262 reserved2: Integer;
263 end;
264
265 { Vorbis tag data }
266 VorbisTag = record
267 ID: array [1..7] of AnsiChar; { Always #3 + "vorbis" }
268 Fields: Integer; { Number of tag fields }
269 FieldData: array [0..VORBIS_FIELD_COUNT] of string; { Tag field data }
270 end;
271
272 // Opus tag data
273 TOpusTags = record
274 ID: array [1..8] of AnsiChar; { Always "OpusTags" }
275 Fields: Integer; { Number of tag fields }
276 FieldData: array [0..VORBIS_FIELD_COUNT] of string; { Tag field data }
277 end;
278
279 { File data }
280 FileInfo = record
281 FPage, SPage, LPage: OggHeader; { First, second and last page }
282 CodecType: TOggCodecType;
283 Parameters: VorbisHeader; { Vorbis parameter header }
284 Tag: VorbisTag; { Vorbis tag data }
285 OpusHeader: TOpusHeader;
286 SpeexHeader: TSpeexHeader;
287 FileSize: Integer; { File size (bytes) }
288 Samples: Integer; { Total number of samples }
289 ID3v2Size: Integer; { ID3v2 tag size (bytes) }
290 SPagePos: Integer; { Position of second Ogg page }
291 TagEndPos: Integer; { Tag end position }
292 end;
293
294 { ********************* Auxiliary functions & procedures ******************** }
295
296 function GetID3v2Size(const Source: TFileStreamEx): Integer;
297 type
298 ID3v2Header = record
299 ID: array [1..3] of AnsiChar;
300 Version: Byte;
301 Revision: Byte;
302 Flags: Byte;
303 Size: array [1..4] of Byte;
304 end;
305 var
306 Header: ID3v2Header;
307 begin
308 { Get ID3v2 tag size (if exists) }
309 Result := 0;
310 Source.Seek(0, soFromBeginning);
311 Source.Read(Header, SizeOf(Header));
312 if Header.ID = 'ID3' then
313 begin
314 Result :=
315 Header.Size[1] * $200000 +
316 Header.Size[2] * $4000 +
317 Header.Size[3] * $80 +
318 Header.Size[4] + 10;
319 if Header.Flags and $10 = $10 then Inc(Result, 10);
320 if Result > Source.Size then Result := 0;
321 end;
322 end;
323
324 { --------------------------------------------------------------------------- }
325
326 procedure SetTagItem(const Data: string; var Info: FileInfo);
327 var
328 Separator, Index: Integer;
329 FieldID, FieldData: string;
330 begin
331 { Set Vorbis tag item if supported comment field found }
332 Separator := Pos('=', Data);
333 if Separator > 0 then
334 begin
335 FieldID := UpperCase(Copy(Data, 1, Separator - 1));
336 FieldData := Copy(Data, Separator + 1, Length(Data) - Length(FieldID));
337 for Index := 1 to VORBIS_FIELD_COUNT do
338 if VORBIS_FIELD[Index] = FieldID then
339 Info.Tag.FieldData[Index] := Trim(FieldData);
340 end
341 else
342 if Info.Tag.FieldData[0] = '' then Info.Tag.FieldData[0] := Data;
343 end;
344
345 { --------------------------------------------------------------------------- }
346
347 procedure ReadTag(const Source: TFileStreamEx; var Info: FileInfo);
348 var
349 Index, Size, Position: Integer;
350 Data: array [1..250] of AnsiChar;
351 begin
352 { Read Vorbis tag }
353 Index := 0;
354 repeat
355 FillChar(Data, SizeOf(Data), 0);
356 Source.Read(Size, SizeOf(Size));
357 Position := Source.Position;
358 if Size > SizeOf(Data) then Source.Read(Data, SizeOf(Data))
359 else Source.Read(Data, Size);
360 { Set Vorbis tag item }
361 SetTagItem(Trim(Data), Info);
362 Source.Seek(Position + Size, soFromBeginning);
363 if Index = 0 then Source.Read(Info.Tag.Fields, SizeOf(Info.Tag.Fields));
364 Inc(Index);
365 until Index > Info.Tag.Fields;
366 Info.TagEndPos := Source.Position;
367 end;
368
369 { --------------------------------------------------------------------------- }
370
371 function GetSamples(const Source: TFileStreamEx): Integer;
372 var
373 Index, DataIndex, Iterator: Integer;
374 Data: array [0..250] of AnsiChar;
375 Header: OggHeader;
376 begin
377 { Get total number of samples }
378 Result := 0;
379 for Index := 1 to 50 do
380 begin
381 DataIndex := Source.Size - (SizeOf(Data) - 10) * Index - 10;
382 Source.Seek(DataIndex, soFromBeginning);
383 Source.Read(Data, SizeOf(Data));
384 { Get number of PCM samples from last Ogg packet header }
385 for Iterator := SizeOf(Data) - 10 downto 0 do
386 if Data[Iterator] +
387 Data[Iterator + 1] +
388 Data[Iterator + 2] +
389 Data[Iterator + 3] = OGG_PAGE_ID then
390 begin
391 Source.Seek(DataIndex + Iterator, soFromBeginning);
392 Source.Read(Header, SizeOf(Header));
393 Result := Header.AbsolutePosition;
394 exit;
395 end;
396 end;
397 end;
398
399 { --------------------------------------------------------------------------- }
400
401 function GetInfo(const FileName: String; var Info: FileInfo): Boolean;
402 var
403 SourceFile: TFileStreamEx;
404 OpusTags: TOpusTags;
405 CodecID: array [1..8] of AnsiChar;
406 TagsID: array [1..8] of AnsiChar;
407 begin
408 { Get info from file }
409 Result := false;
410 SourceFile := nil;
411 try
412 SourceFile := TFileStreamEx.Create(FileName, fmOpenRead or fmShareDenyWrite);
413 Info.FileSize := SourceFile.Size;
414 Info.ID3v2Size := GetID3v2Size(SourceFile);
415 SourceFile.Seek(Info.ID3v2Size, soFromBeginning);
416 SourceFile.Read(Info.FPage, SizeOf(Info.FPage));
417 if Info.FPage.ID <> OGG_PAGE_ID then exit;
418
419 // Read the codec ID signature
420 SourceFile.Seek(Info.ID3v2Size + Info.FPage.Segments + 27, soFromBeginning);
421 SourceFile.Read(CodecID, SizeOf(CodecID));
422
423 // Check codec
424 if Copy(CodecID, 1, 7) = VORBIS_PARAMETERS_ID then
425 Info.CodecType:= octVorbis
426 else if CodecID = OPUS_PARAMETERS_ID then
427 Info.CodecType:= octOpus
428 else if CodecID = SPEEX_PARAMETERS_ID then
429 Info.CodecType:= octSpeex
430 else
431 Exit;
432
433 // Back to header start position
434 SourceFile.Seek(Info.ID3v2Size + Info.FPage.Segments + 27, soFromBeginning);
435 case Info.CodecType of
436 octVorbis: { Read Vorbis parameter header }
437 SourceFile.Read(Info.Parameters, SizeOf(Info.Parameters));
438 octOpus:
439 SourceFile.Read(Info.OpusHeader, SizeOf(TOpusHeader));
440 octSpeex:
441 SourceFile.Read(Info.SpeexHeader, SizeOf(TSpeexHeader));
442 end;
443
444 Info.SPagePos := SourceFile.Position;
445 SourceFile.Read(Info.SPage, SizeOf(Info.SPage));
446 SourceFile.Seek(Info.SPagePos + Info.SPage.Segments + 27, soFromBeginning);
447 SourceFile.Read(TagsID, SizeOf(TagsID));
448
449 if not (((Info.CodecType = octVorbis) and (Copy(TagsID, 1, 7) = VORBIS_TAG_ID)) or
450 ((Info.CodecType = octOpus) and (TagsID = OPUS_TAG_ID)) or
451 (Info.CodecType = octSpeex)) then Exit;
452
453 // Back to tags start position
454 SourceFile.Seek(Info.SPagePos + Info.SPage.Segments + 27, soFromBeginning);
455
456 // Speex tags block has no header, so in case of it we not read anything
457 case Info.CodecType of
458 octVorbis: { Read Vorbis parameter header }
459 SourceFile.Read(Info.Tag.ID, SizeOf(Info.Tag.ID));
460 octOpus:
461 SourceFile.Read(OpusTags.ID, SizeOf(OpusTags.ID));
462 end;
463 { Read Vorbis, Opus or Speex tags }
464 ReadTag(SourceFile, Info);
465
466 { Get total number of samples }
467 Info.Samples := GetSamples(SourceFile);
468 Result := true;
469 finally
470 SourceFile.Free;
471 end;
472 end;
473
474 { --------------------------------------------------------------------------- }
475
476 function GetTrack(const TrackString: string): Byte;
477 var
478 Index, Value, Code: Integer;
479 begin
480 { Extract track from string }
481 Index := Pos('/', TrackString);
482 if Index = 0 then Val(TrackString, Value, Code)
483 else Val(Copy(TrackString, 1, Index), Value, Code);
484 if Code = 0 then Result := Value
485 else Result := 0;
486 end;
487
488 { --------------------------------------------------------------------------- }
489
490 function BuildTag(const Info: FileInfo): TStringStream;
491 var
492 Index, Fields, Size: Integer;
493 FieldData: string;
494 begin
495 { Build Vorbis tag }
496 Result := TStringStream.Create('');
497 Fields := 0;
498 for Index := 1 to VORBIS_FIELD_COUNT do
499 if Info.Tag.FieldData[Index] <> '' then Inc(Fields);
500 { Write frame ID, vendor info and number of fields }
501 Result.Write(Info.Tag.ID, SizeOf(Info.Tag.ID));
502 Size := Length(Info.Tag.FieldData[0]);
503 Result.Write(Size, SizeOf(Size));
504 Result.WriteString(Info.Tag.FieldData[0]);
505 Result.Write(Fields, SizeOf(Fields));
506 { Write tag fields }
507 for Index := 1 to VORBIS_FIELD_COUNT do
508 if Info.Tag.FieldData[Index] <> '' then
509 begin
510 FieldData := VORBIS_FIELD[Index] +
511 '=' + Info.Tag.FieldData[Index];
512 Size := Length(FieldData);
513 Result.Write(Size, SizeOf(Size));
514 Result.WriteString(FieldData);
515 end;
516 end;
517
518 { --------------------------------------------------------------------------- }
519
520 procedure SetLacingValues(var Info: FileInfo; const NewTagSize: Integer);
521 var
522 Index, Position, Value: Integer;
523 Buffer: array [1..$FF] of Byte;
524 begin
525 { Set new lacing values for the second Ogg page }
526 Position := 1;
527 Value := 0;
528 for Index := Info.SPage.Segments downto 1 do
529 begin
530 if Info.SPage.LacingValues[Index] < $FF then
531 begin
532 Position := Index;
533 Value := 0;
534 end;
535 Inc(Value, Info.SPage.LacingValues[Index]);
536 end;
537 Value := Value + NewTagSize -
538 (Info.TagEndPos - Info.SPagePos - Info.SPage.Segments - 27);
539 { Change lacing values at the beginning }
540 for Index := 1 to Value div $FF do Buffer[Index] := $FF;
541 Buffer[(Value div $FF) + 1] := Value mod $FF;
542 if Position < Info.SPage.Segments then
543 for Index := Position + 1 to Info.SPage.Segments do
544 Buffer[Index - Position + (Value div $FF) + 1] :=
545 Info.SPage.LacingValues[Index];
546 Info.SPage.Segments := Info.SPage.Segments - Position + (Value div $FF) + 1;
547 for Index := 1 to Info.SPage.Segments do
548 Info.SPage.LacingValues[Index] := Buffer[Index];
549 end;
550
551 { --------------------------------------------------------------------------- }
552
553 procedure CalculateCRC(var CRC: Cardinal; const Data; Size: Cardinal);
554 var
555 Buffer: ^Byte;
556 Index: Cardinal;
557 begin
558 { Calculate CRC through data }
559 Buffer := Addr(Data);
560 for Index := 1 to Size do
561 begin
562 CRC := (CRC shl 8) xor CRC_TABLE[((CRC shr 24) and $FF) xor Buffer^];
563 Inc(Buffer);
564 end;
565 end;
566
567 { --------------------------------------------------------------------------- }
568
569 procedure SetCRC(const Destination: TFileStreamEx; Info: FileInfo);
570 var
571 Index: Integer;
572 Value: Cardinal;
573 Data: array [1..$FF] of Byte;
574 begin
575 { Calculate and set checksum for Vorbis tag }
576 Value := 0;
577 CalculateCRC(Value, Info.SPage, Info.SPage.Segments + 27);
578 Destination.Seek(Info.SPagePos + Info.SPage.Segments + 27, soFromBeginning);
579 for Index := 1 to Info.SPage.Segments do
580 if Info.SPage.LacingValues[Index] > 0 then
581 begin
582 Destination.Read(Data, Info.SPage.LacingValues[Index]);
583 CalculateCRC(Value, Data, Info.SPage.LacingValues[Index]);
584 end;
585 Destination.Seek(Info.SPagePos + 22, soFromBeginning);
586 Destination.Write(Value, SizeOf(Value));
587 end;
588
589 { --------------------------------------------------------------------------- }
590
591 function RebuildFile(FileName: String; Tag: TStream; Info: FileInfo): Boolean;
592 var
593 Source, Destination: TFileStreamEx;
594 BufferName: String;
595 begin
596 { Rebuild the file with the new Vorbis tag }
597 Result := false;
598 if (not mbFileExists(FileName)) or (mbFileSetReadOnly(FileName, False) <> True) then exit;
599 try
600 { Create file streams }
601 BufferName := FileName + '~';
602 Source := TFileStreamEx.Create(FileName, fmOpenRead);
603 Destination := TFileStreamEx.Create(BufferName, fmCreate);
604 { Copy data blocks }
605 Destination.CopyFrom(Source, Info.SPagePos);
606 Destination.Write(Info.SPage, Info.SPage.Segments + 27);
607 Destination.CopyFrom(Tag, 0);
608 Source.Seek(Info.TagEndPos, soFromBeginning);
609 Destination.CopyFrom(Source, Source.Size - Info.TagEndPos);
610 SetCRC(Destination, Info);
611 Source.Free;
612 Destination.Free;
613 { Replace old file and delete temporary file }
614 if (mbDeleteFile(FileName)) and (mbRenameFile(BufferName, FileName)) then
615 Result := true
616 else
617 raise Exception.Create('');
618 except
619 { Access error }
620 if mbFileExists(BufferName) then mbDeleteFile(BufferName);
621 end;
622 end;
623
624 { ********************** Private functions & procedures ********************* }
625
626 procedure TOggVorbis.FResetData;
627 begin
628 { Reset variables }
629 FFileSize := 0;
630 FChannelModeID := 0;
631 FSampleRate := 0;
632 FBitRateNominal := 0;
633 FSamples := 0;
634 FID3v2Size := 0;
635 FTitle := '';
636 FArtist := '';
637 FAlbum := '';
638 FTrack := 0;
639 FDate := '';
640 FGenre := '';
641 FComment := '';
642 FVendor := '';
643 FCodec := '';
644 end;
645
646 { --------------------------------------------------------------------------- }
647
648 function TOggVorbis.FGetChannelMode: string;
649 begin
650 if FChannelModeID > 2 then Result := VORBIS_MODE[3] else
651 Result := VORBIS_MODE[FChannelModeID];
652 end;
653
654 { --------------------------------------------------------------------------- }
655
656 function TOggVorbis.FGetDuration: Double;
657 begin
658 { Calculate duration time }
659 if FSamples > 0 then
660 if FSampleRate > 0 then
661 Result := FSamples / FSampleRate
662 else
663 Result := 0
664 else
665 if (FBitRateNominal > 0) and (FChannelModeID > 0) then
666 Result := (FFileSize - FID3v2Size) /
667 FBitRateNominal / FChannelModeID / 125 * 2
668 else
669 Result := 0;
670 end;
671
672 { --------------------------------------------------------------------------- }
673
674 function TOggVorbis.FGetBitRate: Word;
675 begin
676 { Calculate average bit rate }
677 Result := 0;
678 if FGetDuration > 0 then
679 Result := Round((FFileSize - FID3v2Size) / FGetDuration / 125);
680 end;
681
682 { --------------------------------------------------------------------------- }
683
684 function TOggVorbis.FHasID3v2: Boolean;
685 begin
686 { Check for ID3v2 tag }
687 Result := FID3v2Size > 0;
688 end;
689
690 { --------------------------------------------------------------------------- }
691
692 function TOggVorbis.FIsValid: Boolean;
693 begin
694 { Check for file correctness }
695 Result := (FChannelModeID in [VORBIS_CM_MONO, VORBIS_CM_STEREO, VORBIS_CM_MULTICHANNEL]) and
696 (FSampleRate > 0) and (FGetDuration > 0.1) and (FGetBitRate > 0);
697 end;
698
699 { ********************** Public functions & procedures ********************** }
700
701 constructor TOggVorbis.Create;
702 begin
703 { Object constructor }
704 FResetData;
705 inherited;
706 end;
707
708 { --------------------------------------------------------------------------- }
709
710 destructor TOggVorbis.Destroy;
711 begin
712 { Object destructor }
713 inherited;
714 end;
715
716 { --------------------------------------------------------------------------- }
717
718 function TOggVorbis.ReadFromFile(const FileName: String): Boolean;
719 var
720 Info: FileInfo;
721 begin
722 { Read data from file }
723 Result := false;
724 FResetData;
725 FillChar(Info, SizeOf(Info), 0);
726 if GetInfo(FileName, Info) then
727 begin
728 { Fill variables }
729 FFileSize := Info.FileSize;
730 case Info.CodecType of
731 octVorbis:
732 begin
733 FChannelModeID := Info.Parameters.ChannelMode;
734 FSampleRate := Info.Parameters.SampleRate;
735 FBitRateNominal := Info.Parameters.BitRateNominal div 1000;
736 FCodec:='Vorbis';
737 end;
738 octOpus:
739 begin
740 FChannelModeID := Info.OpusHeader.ChannelCount;
741 FSampleRate := Info.OpusHeader.SampleRate;
742 FCodec:='Opus';
743 end;
744 octSpeex:
745 begin
746 FChannelModeID := Info.SpeexHeader.nb_channels;
747 FSampleRate := Info.SpeexHeader.rate;
748 FCodec:='Speex';
749 end;
750 end;
751 FSamples := Info.Samples;
752 FID3v2Size := Info.ID3v2Size;
753 FTitle := Info.Tag.FieldData[1];
754 if Info.Tag.FieldData[2] <> '' then FArtist := Info.Tag.FieldData[2]
755 else FArtist := Info.Tag.FieldData[8];
756 FAlbum := Info.Tag.FieldData[3];
757 FTrack := GetTrack(Info.Tag.FieldData[4]);
758 FDate := Info.Tag.FieldData[5];
759 FGenre := Info.Tag.FieldData[6];
760 if Info.Tag.FieldData[7] <> '' then FComment := Info.Tag.FieldData[7]
761 else FComment := Info.Tag.FieldData[9];
762 FVendor := Info.Tag.FieldData[0];
763 Result := true;
764 end;
765 end;
766
767 { --------------------------------------------------------------------------- }
768
769 function TOggVorbis.SaveTag(const FileName: String): Boolean;
770 var
771 Info: FileInfo;
772 Tag: TStringStream;
773 begin
774 { Save Vorbis tag }
775 Result := false;
776 FillChar(Info, SizeOf(Info), 0);
777 if GetInfo(FileName, Info) then
778 begin
779 { Prepare tag data and save to file }
780 Info.Tag.FieldData[1] := Trim(FTitle);
781 Info.Tag.FieldData[2] := Trim(FArtist);
782 Info.Tag.FieldData[3] := Trim(FAlbum);
783 if FTrack > 0 then Info.Tag.FieldData[4] := IntToStr(FTrack)
784 else Info.Tag.FieldData[4] := '';
785 Info.Tag.FieldData[5] := Trim(FDate);
786 Info.Tag.FieldData[6] := Trim(FGenre);
787 Info.Tag.FieldData[7] := Trim(FComment);
788 Info.Tag.FieldData[8] := '';
789 Info.Tag.FieldData[9] := '';
790 Tag := BuildTag(Info);
791 Info.SPage.Checksum := 0;
792 SetLacingValues(Info, Tag.Size);
793 Result := RebuildFile(FileName, Tag, Info);
794 Tag.Free;
795 end;
796 end;
797
798 { --------------------------------------------------------------------------- }
799
800 function TOggVorbis.ClearTag(const FileName: String): Boolean;
801 begin
802 { Clear Vorbis tag }
803 FTitle := '';
804 FArtist := '';
805 FAlbum := '';
806 FTrack := 0;
807 FDate := '';
808 FGenre := '';
809 FComment := '';
810 Result := SaveTag(FileName);
811 end;
812
813 { --------------------------------------------------------------------------- }
814
815 function TOggVorbis.FGetRatio: Double;
816 begin
817 { Get compression ratio }
818 if FIsValid then
819 //Result := FFileSize / (FSamples * FChannelModeID * FBitsPerSample / 8 + 44) * 100
820 Result := FFileSize / (FSamples * (FChannelModeID * 16 / 8) + 44) * 100
821 else
822 Result := 0;
823 end;
824
825 { --------------------------------------------------------------------------- }
826
827 function TOggVorbis.FGetEncoder: String;
828 begin
829 if FVendor = 'Xiphophorus libVorbis I 20000508' then Result := '1.0 beta 1 or beta 2'
830 else if FVendor = 'Xiphophorus libVorbis I 20001031' then Result := '1.0 beta 3'
831 else if FVendor = 'Xiphophorus libVorbis I 20010225' then Result := '1.0 beta 4'
832 else if FVendor = 'Xiphophorus libVorbis I 20010615' then Result := '1.0 rc1'
833 else if FVendor = 'Xiphophorus libVorbis I 20010813' then Result := '1.0 rc2'
834 else if FVendor = 'Xiphophorus libVorbis I 20010816 (gtune 1)' then Result := '1.0 RC2 GT1'
835 else if FVendor = 'Xiphophorus libVorbis I 20011014 (GTune 2)' then Result := '1.0 RC2 GT2'
836 else if FVendor = 'Xiphophorus libVorbis I 20011217' then Result := '1.0 rc3'
837 else if FVendor = 'Xiphophorus libVorbis I 20011231' then Result := '1.0 rc3'
838 //prolly an earlier build of 1.0
839 //else if FVendor = 'Xiph.Org libVorbis I 20020711' then Result := '1.0'
840 else if FVendor = 'Xiph.Org libVorbis I 20020717' then Result := '1.0'
841 else if FVendor = 'Xiph.Org/Sjeng.Org libVorbis I 20020717 (GTune 3, beta 1)' then Result := '1.0 GT3b1'
842 else if FVendor = 'Xiph.Org libVorbis I 20030308' then Result := 'Post 1.0 CVS'
843 else if FVendor = 'Xiph.Org libVorbis I 20030909 (1.0.1)' then Result := '1.0.1'
844 else if FVendor = 'Xiph.Org libVorbis I 20030909' then Result := '1.0.1'
845 else if FVendor = 'Xiph.Org/Sjeng.Org libVorbis I 20030909 (GTune 3, beta 2) EXPERIMENTAL' then Result := 'Experimental GT3b2'
846 else if FVendor = 'Xiph.Org libVorbis I 20031230 (1.0.1)' then Result := 'Post 1.0.1 CVS'
847 else if FVendor = 'Xiph.Org/Sjeng.Org libVorbis I 20031230 (GTune 3, beta 2)' then Result := 'GT3b2'
848 else if FVendor = 'AO; aoTuV b2 [20040420] (based on Xiph.Org''s 1.0.1)' then Result := '1.0.1 aoTuV beta 2'
849 else if FVendor = 'Xiph.Org libVorbis I 20040629' then Result := '1.1'
850 else if FVendor = 'Xiph.Org libVorbis I 20040920' then Result := '1.1 with impulse_trigger_profile'
851 else if FVendor = 'AO; aoTuV b3 [20041120] (based on Xiph.Org''s libVorbis)' then Result := '1.1 aoTuV beta 3'
852 else Result := FVendor;
853 end;
854
855 { --------------------------------------------------------------------------- }
856
857 end.