Debian Codegraph @

src/audio/castleinternalsoundfile.pas

raw
1 {
2 Copyright 2003-2019 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Load sound files in various formats. }
17 unit CastleInternalSoundFile;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes,
24 CastleUtils, CastleTimeUtils, CastleSoundBase, CastleInternalVorbisFile;
25
26 type
27 ESoundFormatNotSupportedByOpenAL = class(ESoundFileError)
28 end deprecated 'do not use, this is not raised by anything anymore';
29
30 ESoundFormatAlreadyRegistered = class(Exception);
31
32 TSoundFile = class
33 strict private
34 FUrl: String;
35 DataStream: TMemoryStream;
36 FDataFormat: TSoundDataFormat;
37 FFrequency: Cardinal;
38 FDuration: TFloatTime;
39 public
40 { Load a sound data from a given URL.
41
42 @raises(ESoundFileError If loading of this sound file failed.
43
44 E.g. in case of decoding problems
45 (e.g. we do not have vorbisfile / tremolo to decompress OggVorbis,
46 or the OggVorbis stream is invalid.)
47
48 Also if reading from the underlying stream failed
49 (e.g. stream ended prematurely).
50 )
51 }
52 constructor Create(const AUrl: String);
53 destructor Destroy; override;
54
55 { URL from which we loaded this sound file. }
56 property Url: String read FUrl;
57
58 { Sound data, according to DataFormat.
59 Contents of Data are readonly. }
60 function Data: Pointer;
61 { Bytes allocated for @link(Data). }
62 function DataSize: Cardinal;
63 property DataFormat: TSoundDataFormat read FDataFormat;
64 property Frequency: Cardinal read FFrequency;
65
66 { Duration in seconds. Returns -1 if not known. }
67 property Duration: TFloatTime read FDuration;
68
69 { Convert sound data to ensure it is 16bit (DataFormat is sfMono16 or sfStereo16,
70 not sfMono8 or sfStereo8). }
71 procedure ConvertTo16bit;
72 end;
73
74 TStreamedSoundFile = class
75 strict private
76 FUrl: String;
77 CompressedStream, DecompressedStream: TStream;
78 FDataFormat: TSoundDataFormat;
79 FFrequency: Cardinal;
80 FDuration: TFloatTime;
81 public
82 { Load a sound from a given URL.
83
84 @raises(ESoundFileError If loading of this sound file failed.
85 E.g. in case of decoding problems
86 (e.g. we do not have vorbisfile / tremolo to decompress OggVorbis,
87 or the OggVorbis stream is invalid.)
88
89 Also when reading from the underlying stream failed
90 (e.g. strean ended prematurely).
91 )
92 }
93 constructor Create(const AUrl: String);
94 destructor Destroy; override;
95
96 { URL from which we loaded this sound file. }
97 property Url: String read FUrl;
98
99 property DataFormat: TSoundDataFormat read FDataFormat;
100 property Frequency: Cardinal read FFrequency;
101 property Duration: TFloatTime read FDuration;
102
103 { Returns read size. }
104 function Read(var Buffer; const BufferSize: LongInt): LongInt;
105 { Rewind streamed sound file, this is necessary for looping. }
106 procedure Rewind;
107 end;
108
109 var
110 { Show in the log loading of sounds. }
111 LogSoundLoading: Boolean;
112
113 type
114 { Read (decompress) a sound file from given Stream.
115 Returns a stream with uncompressed sound data in format described
116 by DataFormat. }
117 TSoundReadEvent = function (
118 const Url: String; const Stream: TStream;
119 out DataFormat: TSoundDataFormat; out Frequency: Cardinal;
120 out Duration: TFloatTime): TStream
121 of object;
122
123 { Register sound format. }
124 procedure RegisterSoundFormat(const MimeType: String;
125 const SoundReader: TSoundReadEvent);
126
127 implementation
128
129 uses Generics.Collections,
130 CastleStringUtils, CastleInternalVorbisDecoder,
131 CastleLog, CastleDownload, CastleUriUtils, CastleClassUtils;
132
133 const
134 SampleSize: array [TSoundDataFormat] of Cardinal = (1, 2, 2, 4);
135
136 { Registering sound formats - declare interface ------------------------------ }
137
138 type
139 TRegisteredSoundFormat = class
140 MimeType: String;
141 ReadEvent: TSoundReadEvent;
142 end;
143
144 TRegisteredSoundFormats = class({$ifdef FPC}specialize{$endif} TObjectList<TRegisteredSoundFormat>)
145 { @nil if not found. }
146 function Find(const MimeType: String): TRegisteredSoundFormat;
147
148 procedure Add(const MimeType: String;
149 const ReadEvent: TSoundReadEvent); reintroduce;
150 end;
151
152 function RegisteredSoundFormats: TRegisteredSoundFormats; forward;
153
154 { TSoundFile ----------------------------------------------------------------- }
155
156 constructor TSoundFile.Create(const AUrl: String);
157
158 { Call ReadEvent and put complete uncompressed data in DataStream. }
159 procedure DecodeStream(const CompressedStream: TStream;
160 const ReadEvent: TSoundReadEvent);
161 const
162 { Noone uses OggVorbis with small files, so it's sensible to make
163 this buffer at least 1 MB. Above this, increasing BufferSize doesn't
164 seem to make loading OggVorbis faster. }
165 BufferSize = 1000 * 1000;
166 var
167 DecodingStream: TStream;
168 begin
169 DecodingStream := ReadEvent(AUrl, CompressedStream, FDataFormat, FFrequency, FDuration);
170 if DecodingStream is TMemoryStream then
171 DataStream := TMemoryStream(DecodingStream)
172 else
173 try
174 DataStream := TMemoryStream.Create;
175 ReadGrowingStream(DecodingStream, DataStream, true, BufferSize);
176 finally FreeAndNil(DecodingStream) end;
177 end;
178
179 procedure CheckCorrectness;
180 begin
181 if DataSize mod SampleSize[DataFormat] <> 0 then
182 raise ESoundFileError.CreateFmt('Invalid size for the sound file "%s": %d is not a multiple of sample size (%d)', [
183 UriDisplay(Url),
184 DataSize,
185 SampleSize[DataFormat]
186 ]);
187 if DataSize = 0 then
188 raise ESoundFileError.CreateFmt('Invalid size for the sound file "%s": size cannot be zero', [
189 UriDisplay(Url)
190 ]);
191 end;
192
193 const
194 DurationSuggestStreaming = 10.0;
195 var
196 CompressedStream: TStream;
197 MimeType: string;
198 TimeStart: TCastleProfilerTime;
199 F: TRegisteredSoundFormat;
200 begin
201 inherited Create;
202 FUrl := AUrl;
203
204 TimeStart := Profiler.Start('Loading "' + UriDisplay(AUrl) + '" (TSoundFile)');
205 try
206 try
207 { Use soForceMemoryStream as file readers may need seeking }
208 CompressedStream := Download(AUrl, [soForceMemoryStream], MimeType);
209 try
210 F := RegisteredSoundFormats.Find(MimeType);
211 if F = nil then
212 raise ESoundFileError.CreateFmt('Not recognized (not supported) sound file format: %s for file "%s"', [
213 MimeType,
214 UriDisplay(AUrl)
215 ]);
216
217 DecodeStream(CompressedStream, F.ReadEvent);
218 finally FreeAndNil(CompressedStream) end;
219
220 CheckCorrectness;
221
222 if LogSoundLoading then
223 begin
224 WritelnLog('Sound', 'Loaded "%s": %s, %s, size: %d, frequency: %d, duration: %f', [
225 UriDisplay(AUrl),
226 MimeType,
227 DataFormatToStr(DataFormat),
228 DataSize,
229 Frequency,
230 Duration
231 ]);
232 end;
233 if Duration > DurationSuggestStreaming then
234 WritelnLog('Sound', 'Consider using streaming when loading long sound file "%s" (duration %f)', [
235 UriDisplay(AUrl),
236 Duration
237 ]);
238 except
239 { May be raised by Download in case opening the underlying stream failed. }
240 on E: EFOpenError do
241 { Reraise as ESoundFileError, and add URL to exception message }
242 raise ESoundFileError.Create('Error while opening URL "' + UriDisplay(AUrl) + '": ' + E.Message);
243
244 on E: EStreamError do
245 { Reraise as ESoundFileError, and add URL to exception message }
246 raise ESoundFileError.Create('Error while reading URL "' + UriDisplay(AUrl) + '": ' + E.Message);
247 end;
248
249 finally Profiler.Stop(TimeStart) end;
250 end;
251
252 destructor TSoundFile.Destroy;
253 begin
254 FreeAndNil(DataStream);
255 inherited;
256 end;
257
258 function TSoundFile.Data: Pointer;
259 begin
260 Result := DataStream.Memory;
261 end;
262
263 function TSoundFile.DataSize: Cardinal;
264 begin
265 Result := DataStream.Size;
266 end;
267
268 procedure TSoundFile.ConvertTo16bit;
269 var
270 PSource: PByte;
271 // To unsigned 16-bit:
272 //PDest: PWord;
273 // To signed 16-bit:
274 PDest: PSmallInt;
275 NewDataStream: TMemoryStream;
276 begin
277 if DataFormat in [sfMono8, sfStereo8] then
278 begin
279 WritelnWarning('Sound', 'Converting to 16-bit "%s".', [UriDisplay(Url)]);
280
281 { create NewDataStream with 16-bit samples }
282 NewDataStream := TMemoryStream.Create;
283 NewDataStream.Size := DataSize * 2;
284 PSource := Data;
285 PDest := NewDataStream.Memory;
286 while PtrUInt(PSource) < PtrUInt(Data) + DataSize do
287 begin
288 // To unsigned 16-bit:
289 // PDest^ := Word(PSource^) shl 8;
290 // To signed 16-bit:
291 PDest^ := (SmallInt(PSource^) - 128) shl 8;
292 Inc(PSource);
293 Inc(PDest);
294 end;
295
296 { update fields }
297 FreeAndNil(DataStream);
298 DataStream := NewDataStream;
299 case DataFormat of
300 sfMono8 : FDataFormat := sfMono16;
301 sfStereo8: FDataFormat := sfStereo16;
302 else ;
303 end;
304 end;
305 end;
306
307 { TStreamedSoundFile --------------------------------------------------------- }
308
309 constructor TStreamedSoundFile.Create(const AUrl: String);
310 var
311 MimeType: string;
312 TimeStart: TCastleProfilerTime;
313 F: TRegisteredSoundFormat;
314 begin
315 inherited Create;
316 FUrl := AUrl;
317
318 TimeStart := Profiler.Start('Loading "' + UriDisplay(AUrl) + '" (TStreamedSoundFile)');
319 try
320 try
321 { Use soForceMemoryStream as file readers may need seeking }
322 CompressedStream := Download(AUrl, [soForceMemoryStream], MimeType);
323
324 F := RegisteredSoundFormats.Find(MimeType);
325 if F = nil then
326 raise ESoundFileError.CreateFmt('Not recognized (not supported) sound file format: %s for file "%s"', [
327 MimeType,
328 UriDisplay(AUrl)
329 ]);
330
331 DecompressedStream := F.ReadEvent(AUrl, CompressedStream, FDataFormat, FFrequency, FDuration);
332
333 if LogSoundLoading then
334 begin
335 WritelnLog('Sound', 'Loaded "%s": %s, %s, frequency: %d, duration: %f', [
336 UriDisplay(AUrl),
337 MimeType,
338 DataFormatToStr(DataFormat),
339 Frequency,
340 Duration
341 ]);
342 end;
343 except
344 { May be raised by Download in case opening the underlying stream failed. }
345 on E: EFOpenError do
346 begin
347 { Reraise as ESoundFileError, and add URL to exception message }
348 raise ESoundFileError.Create('Error while opening URL "' + UriDisplay(AUrl) + '": ' + E.Message);
349 end;
350
351 on E: EStreamError do
352 begin
353 { Reraise as ESoundFileError, and add URL to exception message }
354 raise ESoundFileError.Create('Error while reading URL "' + UriDisplay(AUrl) + '": ' + E.Message);
355 end;
356 end;
357 finally
358 Profiler.Stop(TimeStart)
359 end;
360 end;
361
362 destructor TStreamedSoundFile.Destroy;
363 begin
364 FreeAndNil(DecompressedStream);
365 FreeAndNil(CompressedStream);
366 inherited;
367 end;
368
369 function TStreamedSoundFile.Read(var Buffer; const BufferSize: LongInt): LongInt;
370 begin
371 Result := DecompressedStream.Read(Buffer, BufferSize);
372 end;
373
374 procedure TStreamedSoundFile.Rewind;
375 begin
376 DecompressedStream.Position := 0;
377 end;
378
379 { TWAVReader ------------------------------------------------------------ }
380
381 type
382 EWavLoadError = class(ESoundFileError);
383
384 TWAVReader = class
385 class function Read(const Url: String; const Stream: TStream;
386 out DataFormat: TSoundDataFormat; out Frequency: Cardinal;
387 out Duration: TFloatTime): TStream;
388 end;
389
390 class function TWAVReader.Read(const Url: String; const Stream: TStream;
391 out DataFormat: TSoundDataFormat; out Frequency: Cardinal;
392 out Duration: TFloatTime): TStream;
393
394 { WAV file reader. Written mostly based on
395 http://www.technology.niagarac.on.ca/courses/comp630/WavFileFormat.html
396 and looking at alutLoadWAVFile implementation.
397 See also http://www.sonicspot.com/guide/wavefiles.html , this seems
398 a little more updated. }
399
400 type
401 TID = array [0..3] of AnsiChar;
402
403 function IdCompare(const id: TID; const s: AnsiString): boolean;
404 begin
405 Result := (Length(s) = 4) and (id[0] = s[1]) and (id[1] = s[2])
406 and (id[2] = s[3]) and (id[3] = s[4]);
407 end;
408
409 type
410 TWavChunkHeader = packed record
411 ID: TID;
412 Len: UInt32; {< This *doesn't* include SizeOf(TWavChunkHeader) itself. }
413 end;
414
415 { The whole WAV file is just one RIFF chunk. }
416 TWavRiffChunk = packed record
417 Header: TWavChunkHeader; {< Header.rID = 'RIFF' }
418 wID: TID; {< Indicates RIFF type. In this case it must be 'WAVE' }
419 { More chunks follow. Format and Data chunks are mandatory and
420 Format _must_ be before Data. }
421 end;
422
423 { WAV format description.
424
425 Note that this must be preceded by the TWavChunkHeader
426 in a stream, with Header.ID = 'fmt ' }
427 TWavFormatChunk = packed record
428 { 1 means PCM, but other values are also possible }
429 FormatTag: Word;
430 { 1 channel means mono, 2 = stereo. Theoretically other values
431 are probably possible? }
432 Channels: Word;
433 SamplesPerSec: UInt32;
434 AvgBytesPerSec: UInt32;
435 BlockAlign: Word;
436 BitsPerSample: Word;
437 end;
438
439 var
440 Riff: TWavRiffChunk;
441 Format: TWavFormatChunk;
442 Header: TWavChunkHeader;
443 begin
444 Stream.ReadBuffer(Riff, SizeOf(Riff));
445 if not (IdCompare(Riff.Header.ID, 'RIFF') and IdCompare(Riff.wID, 'WAVE')) then
446 raise EWavLoadError.Create('WAV file must start with RIFF....WAVE signature');
447
448 { Workaround for buggy WAV files generated by OpenAL waveout device,
449 see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=435754
450 gstreamer crashes on them, some other programs handle them.
451
452 They contain fmt and data sections OK, but Riff.Header.Len is too large.
453 So at the end, we stand at the end of the file but
454 Stream.Position < Int64(Riff.Header.Len + SizeOf(TWavChunkHeader))
455 says we can read another chunk.
456 In general, these are invalid WAV files, but let's handle them... }
457 if Riff.Header.Len = Stream.Size then
458 begin
459 Riff.Header.Len := Riff.Header.Len - SizeOf(TWavChunkHeader);
460 WritelnWarning('WAV', 'Invalid WAV file: Riff.Header.Len equals Stream.Size, but it should be <= Stream.Size - SizeOf(TWavChunkHeader). Reading anyway.');
461 end;
462
463 Result := nil;
464
465 while Stream.Position < Int64(Riff.Header.Len + SizeOf(TWavChunkHeader)) do
466 begin
467 Stream.ReadBuffer(Header, SizeOf(Header));
468
469 {
470 Writeln('Got chunk "',
471 SReadableForm(Header.ID[0] + Header.ID[1] + Header.ID[2] + Header.ID[3]) +
472 '", length ', Header.Len,
473 ', remaining stream size ', Stream.Size - Stream.Position);
474 }
475
476 if IdCompare(Header.ID, 'fmt ') then
477 begin
478 Stream.ReadBuffer(Format, SizeOf(Format));
479 if Format.FormatTag <> 1 then
480 raise EWavLoadError.CreateFmt('Not supported format of "%s". Only uncompressed (PCM) WAV files are supported. Convert WAV files to uncompressed e.g. using Audacity or Sox.', [
481 UriDisplay(Url)
482 ]);
483 { calculate DataFormat }
484 case Format.Channels of
485 1:case Format.BitsPerSample of
486 8 : DataFormat := sfMono8;
487 16: DataFormat := sfMono16;
488 else raise EWavLoadError.CreateFmt('Invalid WAV file %s: Only 8 or 16-bit encodings are supported', [Url]);
489 end;
490 2:case Format.BitsPerSample of
491 8 : DataFormat := sfStereo8;
492 16: DataFormat := sfStereo16;
493 else raise EWavLoadError.CreateFmt('Invalid WAV file %s: Only 8 or 16-bit encodings are supported', [Url]);
494 end;
495 else raise EWavLoadError.CreateFmt('Invalid WAV file %s: Only 1 or 2 channels are supported', [Url]);
496 end;
497 { calculate Frequency }
498 Frequency := Format.SamplesPerSec;
499 { There may be some additional stuff here in format chunk.
500 The meaning depends on FormatTag value.
501 http://www.sonicspot.com/guide/wavefiles.html
502 says they can only happen for compressed WAV data, but I have examples
503 of files created (probably) by Windows 95 wav recorder that
504 are uncompressed and still have some data here
505 (szklane_lasy/sounds/cantDoIt.wav). So be prepared always for some data here. }
506 Stream.Seek(Header.Len - SizeOf(Format), soFromCurrent);
507 end else
508
509 if IdCompare(Header.ID, 'data') then
510 begin
511 { calculate Result }
512 if Result <> nil then
513 raise EWavLoadError.Create('WAV file must not contain multiple data chunks');
514 Result := TMemoryStream.Create;
515 Result.Size := Header.Len;
516 Stream.ReadBuffer(TMemoryStream(Result).Memory^, Header.Len);
517 end else
518
519 begin
520 { skip any unknown chunks }
521 Stream.Seek(Header.Len, soFromCurrent);
522 end;
523
524 { all RIFF chunks are 2-byte-aligned, and DataSize doesn't include this padding,
525 according to http://www.sonicspot.com/guide/wavefiles.html
526 We have to account for it, and skip this padding (otherwise we would get
527 nonsense header next, that is cut off by eof and/or has wild Header.Len).
528 Testcase with szklane_lasy/sounds/cantDoIt.wav. }
529 if Odd(Header.Len) then
530 Stream.Seek(1, soFromCurrent);
531 end;
532
533 if Result = nil then
534 raise EWavLoadError.Create('WAV file has no data chunk');
535
536 if (Frequency = 0) or (Result.Size = 0) then
537 raise EWavLoadError.Create('WAV file has Frequency or DataSize equal zero');
538 Duration := Result.Size / (Frequency * SampleSize[DataFormat]);
539 end;
540
541 { Registering sound formats -------------------------------------------------- }
542
543 function TRegisteredSoundFormats.Find(const MimeType: String): TRegisteredSoundFormat;
544 begin
545 for Result in Self do
546 if Result.MimeType = MimeType then
547 Exit;
548 Result := nil;
549 end;
550
551 procedure TRegisteredSoundFormats.Add(const MimeType: String;
552 const ReadEvent: TSoundReadEvent);
553 var
554 F: TRegisteredSoundFormat;
555 begin
556 if Find(MimeType) <> nil then
557 raise ESoundFormatAlreadyRegistered.CreateFmt('Sound format "%s" is already registered', [MimeType]);
558 F := TRegisteredSoundFormat.Create;
559 F.MimeType := MimeType;
560 F.ReadEvent := ReadEvent;
561 inherited Add(F);
562 end;
563
564 var
565 FRegisteredSoundFormats: TRegisteredSoundFormats;
566
567 function RegisteredSoundFormats: TRegisteredSoundFormats;
568 begin
569 { initialize FRegisteredSoundFormats on-demand }
570 if FRegisteredSoundFormats = nil then
571 begin
572 FRegisteredSoundFormats := TRegisteredSoundFormats.Create(true);
573 // register default formats, handled in this unit
574 { WAV has 2 popular MIME types,
575 see https://stackoverflow.com/questions/44891157/why-wav-format-doesnt-have-same-mimetype-in-different-browsers }
576 FRegisteredSoundFormats.Add('audio/x-wav',
577 {$ifdef FPC}@{$endif}TWAVReader{$ifdef FPC}(nil){$endif}.Read);
578 FRegisteredSoundFormats.Add('audio/wav',
579 {$ifdef FPC}@{$endif}TWAVReader{$ifdef FPC}(nil){$endif}.Read);
580 end;
581 Result := FRegisteredSoundFormats;
582 end;
583
584 procedure RegisterSoundFormat(const MimeType: String;
585 const SoundReader: TSoundReadEvent);
586 begin
587 RegisteredSoundFormats.Add(MimeType, SoundReader);
588 end;
589
590 {$ifndef FPC}initialization{$endif}
591
592 finalization
593 FreeAndNil(FRegisteredSoundFormats);
594 end.