Debian Codegraph @

src/audio/ogg_vorbis/castleinternalvorbisdecoder.pas

raw
1 {
2 Copyright 2010-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 { OggVorbis decoder.
17 During the initialization, this unit registers handling of OggVorbis
18 file format using RegisterSoundFormat.
19 }
20 unit CastleInternalVorbisDecoder;
21
22 {$I castleconf.inc}
23
24 interface
25
26 implementation
27
28 uses SysUtils, Classes, CTypes,
29 CastleUtils, CastleClassUtils, CastleSoundBase, CastleInternalVorbisCodec,
30 CastleInternalSoundFile, CastleInternalVorbisFile, CastleLog,
31 CastleTimeUtils;
32
33 type
34 EOggVorbisLoadError = class(ESoundFileError);
35 EOggVorbisMissingLibraryError = class(EOggVorbisLoadError);
36 EOggVorbisFileError = class(EOggVorbisLoadError);
37
38 { global routines (callbacks for ov_open_callbacks) -------------------------- }
39
40 { VorbisDecoder_ callbacks code based on Noeska code from
41 [http://www.noeska.com/doal/tutorials.aspx].
42 Heavily modified for CGE (e.g. to allow exceptions raising in case of
43 stream errors (instead of silencing these exceptions), to check (ReadCount mod
44 Size) in read_func and whence in seek_func, close does nothing). }
45
46 function VorbisDecoder_read_func(ptr: Pointer;
47 Size: TSizeT; nmemb: TSizeT; DataSource: Pointer): TSizeT; cdecl;
48 { Returns amount of items completely read successfully, returns indeterminate
49 value on error. The value of a partially read item cannot be determined. Does
50 not lead to valid feof or ferror responses, because they are not possible to
51 supply to VorbisFile }
52 var
53 ReadCount: Int64;
54 begin
55 if (size = 0) or (nmemb = 0) then
56 begin
57 Result := 0;
58 Exit;
59 end;
60
61 ReadCount := TStream(DataSource).Read(ptr^, Size * nmemb);
62 Assert(ReadCount mod Size = 0);
63 Result := ReadCount div Size;
64 end;
65
66 function VorbisDecoder_seek_func(DataSource: Pointer;
67 offset: Int64; whence: CInt): CInt; cdecl;
68 const
69 SEEK_SET = 0;
70 SEEK_CUR = 1;
71 SEEK_END = 2;
72 begin
73 try
74 case whence of
75 SEEK_CUR: TStream(DataSource).Seek(offset, soFromCurrent);
76 SEEK_END: TStream(DataSource).Seek(offset, soFromEnd);
77 SEEK_SET: TStream(DataSource).Seek(offset, soFromBeginning);
78 else raise EInternalError.CreateFmt('Invalid VorbisDecoder_seek_func ' +
79 'whence param: %d', [whence]);
80 end;
81 Result := 0;
82 except
83 { If the Stream is unseekable, vorbisfile allows us to return here -1. }
84 Result := -1;
85 end;
86 end;
87
88 function VorbisDecoder_close_func(DataSource: Pointer): CInt;
89 cdecl;
90 begin
91 Result := 0;
92 end;
93
94 function VorbisDecoder_tell_func(DataSource: Pointer): CLong;
95 cdecl;
96 begin
97 Result := TStream(DataSource).Position;
98 end;
99
100 procedure CheckVorbisFile(Err: CInt; const Event: string);
101 var
102 ErrDescription: string;
103 begin
104 { Errors list and ErrDescription values based on
105 [http://xiph.org/vorbis/doc/vorbisfile/return.html] }
106 case Err of
107 OV_FALSE: ErrDescription := 'No data available';
108 OV_HOLE: ErrDescription := 'Vorbisfile encountered missing or corrupt data in the bitstream'; {. Recovery is normally automatic and this return code is for informational purposes only. }
109 OV_EREAD: ErrDescription := 'Read error while fetching compressed data for decode';
110 OV_EFAULT: ErrDescription := 'Internal inconsistency in decode state'; {. Continuing is likely not possible. }
111 OV_EIMPL: ErrDescription := 'Feature not implemented';
112 OV_EINVAL: ErrDescription := 'Either an invalid argument, or incompletely initialized argument passed to libvorbisfile call';
113 OV_ENOTVORBIS: ErrDescription := 'The given file/data was not recognized as Ogg Vorbis data';
114 OV_EBADHEADER: ErrDescription := 'The file/data is apparently an Ogg Vorbis stream, but contains a corrupted or undecipherable header';
115 OV_EVERSION: ErrDescription := 'The bitstream format revision of the given stream is not supported';
116 OV_EBADLINK: ErrDescription := 'The given link exists in the Vorbis data stream, but is not decipherable due to garbacge or corruption';
117 OV_ENOSEEK: ErrDescription := 'The given stream is not seekable';
118 else ErrDescription := '(unknown vorbisfile error code)';
119 end;
120
121 if Err <> 0 then
122 raise EOggVorbisFileError.CreateFmt('VorbisFile error %d at "%s": %s',
123 [Err, Event, ErrDescription]);
124 end;
125
126 { TOggVorbisStream ----------------------------------------------------------- }
127
128 type
129 { Decode OggVorbis file contents.
130
131 Uses LibVorbisFile or Tremolo libraries.
132 Both are open-source libraries
133 for reading OggVorbis music from https://xiph.org/.
134 Tremolo is used on mobile devices, libvorbisfile on desktop.
135 Checks VorbisFileInitialized at the beginning, so you don't have to
136 worry about it.
137
138 Gets data from ObjectPascal TStream (like TFileStream)
139 and returns data as TStream.
140
141 All methods may raise EOggVorbisLoadError If decoding OggVorbis stream failed,
142 this may also happen if the vorbisfile / tremolo library is not available.
143 }
144 TOggVorbisStream = class(TOwnerStream)
145 strict private
146 VorbisFile: TOggVorbis_File;
147 // Is VorbisFile valid, e.g. we can call ov_clear on it.
148 VorbisFileValid: Boolean;
149 procedure OpenVorbisFile(out DataFormat: TSoundDataFormat;
150 out Frequency: Cardinal; out Duration: TFloatTime);
151 procedure CloseVorbisFile;
152 public
153 constructor Create(const ASourceStream: TStream;
154 out DataFormat: TSoundDataFormat; out Frequency: Cardinal;
155 out Duration: TFloatTime);
156 destructor Destroy; override;
157 function Read(var Buffer; BufferSize: Longint): Longint; override;
158
159 { Only supports seeking to the beginning (or seeking to current position,
160 which does nothing). }
161 function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
162
163 { Use this function to register OggVorbis handling with RegisterSoundFormat. }
164 class function ReadStream(const Url: String; const Stream: TStream;
165 out DataFormat: TSoundDataFormat; out Frequency: Cardinal;
166 out Duration: TFloatTime): TStream;
167 end;
168
169 constructor TOggVorbisStream.Create(const ASourceStream: TStream;
170 out DataFormat: TSoundDataFormat; out Frequency: Cardinal;
171 out Duration: TFloatTime);
172 begin
173 inherited Create(ASourceStream);
174 OpenVorbisFile(DataFormat, Frequency, Duration);
175 end;
176
177 destructor TOggVorbisStream.Destroy;
178 begin
179 CloseVorbisFile;
180 inherited;
181 end;
182
183 procedure TOggVorbisStream.OpenVorbisFile(
184 out DataFormat: TSoundDataFormat; out Frequency: Cardinal;
185 out Duration: TFloatTime);
186 var
187 DurationRaw: {$ifdef CASTLE_TREMOLO} Int64 {$else} Double {$endif};
188 OggInfo: Pvorbis_info;
189 Callbacks: Tov_callbacks;
190 begin
191 if not VorbisFileInitialized then
192 raise EOggVorbisMissingLibraryError.Create('Library to decode OggVorbis (LibVorbisFile on desktops, Tremolo on mobile) is not available');
193
194 Callbacks.read_func := @VorbisDecoder_read_func;
195 Callbacks.seek_func := @VorbisDecoder_seek_func;
196 Callbacks.close_func := @VorbisDecoder_close_func;
197 Callbacks.tell_func := @VorbisDecoder_tell_func;
198 CheckVorbisFile(ov_open_callbacks(Source, @VorbisFile, nil, 0, Callbacks),
199 'ov_open_callbacks');
200
201 VorbisFileValid := true; // ov_clear on VorbisFile now is valid
202
203 OggInfo := ov_info(@VorbisFile, -1);
204
205 if OggInfo^.channels = 1 then
206 DataFormat := sfMono16
207 else
208 DataFormat := sfStereo16;
209
210 Frequency := OggInfo^.rate;
211
212 DurationRaw := ov_time_total(@VorbisFile, -1);
213 if {$ifdef FPC} Int64(DurationRaw) {$else} {$ifndef CASTLE_TREMOLO}
214 Trunc(DurationRaw) {$else} DurationRaw {$endif} {$endif FPC} = OV_EINVAL then
215 begin
216 WritelnWarning('Cannot read OggVorbis duration, the requested bitstream may not be seekable');
217 DurationRaw := 0;
218 end;
219
220 {$ifdef CASTLE_TREMOLO}
221 Duration := DurationRaw / 1000;
222 {$else}
223 Duration := DurationRaw;
224 {$endif}
225 end;
226
227 procedure TOggVorbisStream.CloseVorbisFile;
228 begin
229 if VorbisFileValid then
230 begin
231 ov_clear(@VorbisFile);
232 VorbisFileValid := false;
233 end;
234 end;
235
236 function TOggVorbisStream.Read(var Buffer; BufferSize: Longint): Longint;
237 (*
238
239 This simple implementation may not fill enough space to be useful to streaming.
240 TODO: This is a valid Read implementation.
241 Higher-level music streaming should wrap it in something like ReadSensibleAmountOfData,
242 and thus be useful both for OggVorbis and other formats.
243
244 var
245 BitStream: CInt;
246 begin
247 Result := ov_read(@VorbisFile, Buffer, BufferSize,
248 { OpenAL always wants little endian ? } 0,
249 { Always give us 16 bits } 2, 1, @BitStream);
250
251 if Result < 0 then
252 CheckVorbisFile(Result, 'ov_read');
253 end;
254 *)
255
256 var
257 BitStream: CInt;
258 NowRead, TotalRead: LongInt;
259 FreeSpace: LongInt;
260 BufferPoint: PByte;
261 begin
262 BufferPoint := @Buffer;
263
264 NowRead := ov_read(@VorbisFile, Buffer, BufferSize,
265 { OpenAL always wants little endian ? } 0,
266 { Always give us 16 bits } 2, 1, @BitStream);
267
268 if NowRead < 0 then
269 CheckVorbisFile(NowRead, 'ov_read');
270
271 TotalRead := NowRead;
272 FreeSpace := BufferSize - TotalRead;
273
274 if FreeSpace > 4096 then
275 begin
276 BufferPoint := BufferPoint + TotalRead;
277
278 while FreeSpace > 4096 do
279 begin
280 NowRead := ov_read(@VorbisFile, BufferPoint^, FreeSpace,
281 { OpenAL always wants little endian ? } 0,
282 { Always give us 16 bits } 2, 1, @BitStream);
283
284 if NowRead < 0 then
285 CheckVorbisFile(NowRead, 'ov_read');
286
287 if NowRead = 0 then
288 Exit(TotalRead);
289
290 Inc(TotalRead, NowRead);
291 FreeSpace := FreeSpace - NowRead;
292 BufferPoint := BufferPoint + NowRead;
293 end;
294 end;
295
296 Result := TotalRead;
297 end;
298
299 function TOggVorbisStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
300 var
301 IgnoreDataFormat: TSoundDataFormat;
302 IgnoreFrequency: Cardinal;
303 IgnoreDuration: TFloatTime;
304 begin
305 // Seek is also used to track current position, but we don't track it
306 Result := 0;
307
308 if (Origin = soCurrent ) and (Offset = 0) then
309 { nothing needs to be done, ok }
310 Exit;
311
312 if (Origin = soBeginning) and (Offset = 0) then
313 begin
314 CloseVorbisFile;
315 Source.Position := 0;
316 OpenVorbisFile(IgnoreDataFormat, IgnoreFrequency, IgnoreDuration);
317 Exit;
318 end;
319
320 raise EStreamNotImplementedSeek.Create('TOggVorbisStream.Seek not supported for these arguments (only seeking to current or beginning position are allowed)');
321 end;
322
323 class function TOggVorbisStream.ReadStream(const Url: String; const Stream: TStream;
324 out DataFormat: TSoundDataFormat; out Frequency: Cardinal;
325 out Duration: TFloatTime): TStream;
326 begin
327 Result := TOggVorbisStream.Create(Stream, DataFormat, Frequency, Duration);
328 end;
329
330 initialization
331 RegisterSoundFormat('audio/ogg', {$ifdef FPC}@{$endif}TOggVorbisStream{$ifdef FPC}(nil){$endif}.ReadStream);
332 end.