Minor cleanups
[alure.git] / src / stream.cpp
blobc8f896ede39f2a4c9c0a73b98b8968e8d7b299eb
1 /*
2 * ALURE OpenAL utility library
3 * Copyright (c) 2009 by Chris Robinson.
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to
7 * deal in the Software without restriction, including without limitation the
8 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 * sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
24 /* Title: Streaming */
26 #include "config.h"
28 #include "main.h"
30 #include <string.h>
32 #include <memory>
34 static bool SizeIsUS = false;
36 static alureStream *InitStream(alureStream *instream, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
38 std::auto_ptr<std::istream> fstream(instream->fstream);
39 std::auto_ptr<alureStream> stream(instream);
40 ALenum format;
41 ALuint freq, blockAlign;
43 if(!stream->GetFormat(&format, &freq, &blockAlign))
45 SetError("Could not get stream format");
46 return NULL;
49 if(format == AL_NONE)
51 SetError("No valid format");
52 return NULL;
54 if(blockAlign == 0)
56 SetError("Invalid block size");
57 return NULL;
59 if(freq == 0)
61 SetError("Invalid sample rate");
62 return NULL;
65 if(SizeIsUS)
67 ALuint framesPerBlock = DetectCompressionRate(format);
68 ALuint blockSize = DetectBlockAlignment(format);
69 if(framesPerBlock == 0 || blockSize == 0)
71 SetError("Unknown compression rate");
72 return NULL;
75 alureUInt64 len64 = chunkLength;
76 len64 = len64 * freq / 1000000 / framesPerBlock * blockSize;
77 if(len64 > 0x7FFFFFFF)
79 SetError("Chunk length too large");
80 return NULL;
82 chunkLength = len64;
85 chunkLength -= chunkLength%blockAlign;
86 if(chunkLength <= 0)
88 SetError("Chunk length too small");
89 return NULL;
92 stream->dataChunk.resize(chunkLength);
94 if(numBufs > 0)
96 alGenBuffers(numBufs, bufs);
97 if(alGetError() != AL_NO_ERROR)
99 SetError("Buffer creation failed");
100 return NULL;
104 ALsizei filled;
105 for(filled = 0;filled < numBufs;filled++)
107 ALuint got = stream->GetData(&stream->dataChunk[0], stream->dataChunk.size());
108 got -= got%blockAlign;
109 if(got == 0) break;
111 alBufferData(bufs[filled], format, &stream->dataChunk[0], got, freq);
114 while(filled < numBufs)
116 alBufferData(bufs[filled], format, &stream->dataChunk[0], 0, freq);
117 filled++;
119 if(alGetError() != AL_NO_ERROR)
121 alDeleteBuffers(numBufs, bufs);
122 alGetError();
124 SetError("Buffering error");
125 return NULL;
128 fstream.release();
129 return stream.release();
133 extern "C" {
135 /* Function: alureStreamSizeIsMicroSec
137 * Specifies if the chunk size value given to the alureCreateStream functions
138 * is in bytes (default) or microseconds. Specifying the size in microseconds
139 * can help manage the time needed in between needed updates (since the format
140 * and sample rate of the stream may not be known), while specifying the size
141 * in bytes can help control memory usage.
143 * Returns:
144 * Previously set value.
146 * *Version Added*: 1.1
148 * See Also:
149 * <alureCreateStreamFromFile>, <alureCreateStreamFromMemory>,
150 * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
152 ALURE_API ALboolean ALURE_APIENTRY alureStreamSizeIsMicroSec(ALboolean useUS)
154 ALboolean old = (SizeIsUS ? AL_TRUE : AL_FALSE);
155 SizeIsUS = !!useUS;
156 return old;
159 /* Function: alureCreateStreamFromFile
161 * Opens a file and sets it up for streaming. The given chunkLength is the
162 * number of bytes, or microseconds worth of bytes if
163 * <alureStreamSizeIsMicroSec> was last called with AL_TRUE, each buffer will
164 * fill with. ALURE will optionally generate the specified number of buffer
165 * objects, fill them with the beginning of the data, then place the new IDs
166 * into the provided storage, before returning. Requires an active context.
168 * Returns:
169 * An opaque handle used to control the opened stream, or NULL on error.
171 * See Also:
172 * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromMemory>,
173 * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
175 ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromFile(const ALchar *fname, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
177 if(alGetError() != AL_NO_ERROR)
179 SetError("Existing OpenAL error");
180 return NULL;
183 if(chunkLength < 0)
185 SetError("Invalid chunk length");
186 return NULL;
189 if(numBufs < 0)
191 SetError("Invalid buffer count");
192 return NULL;
195 alureStream *stream = create_stream(fname);
196 if(!stream) return NULL;
198 return InitStream(stream, chunkLength, numBufs, bufs);
201 /* Function: alureCreateStreamFromMemory
203 * Opens a file image from memory and sets it up for streaming, similar to
204 * <alureCreateStreamFromFile>. The given data buffer can be safely deleted
205 * after calling this function. Requires an active context.
207 * Returns:
208 * An opaque handle used to control the opened stream, or NULL on error.
210 * See Also:
211 * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
212 * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback>
214 ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
216 if(alGetError() != AL_NO_ERROR)
218 SetError("Existing OpenAL error");
219 return NULL;
222 if(chunkLength < 0)
224 SetError("Invalid chunk length");
225 return NULL;
228 if(numBufs < 0)
230 SetError("Invalid buffer count");
231 return NULL;
234 if(length <= 0)
236 SetError("Invalid data length");
237 return NULL;
240 ALubyte *streamData = new ALubyte[length];
241 memcpy(streamData, fdata, length);
243 MemDataInfo memData;
244 memData.Data = streamData;
245 memData.Length = length;
246 memData.Pos = 0;
248 alureStream *stream = create_stream(memData);
249 if(!stream) return NULL;
251 stream->data = streamData;
252 return InitStream(stream, chunkLength, numBufs, bufs);
255 /* Function: alureCreateStreamFromStaticMemory
257 * Identical to <alureCreateStreamFromMemory>, except the given memory is used
258 * directly and not duplicated. As a consequence, the data buffer must remain
259 * valid while the stream is alive. Requires an active context.
261 * Returns:
262 * An opaque handle used to control the opened stream, or NULL on error.
264 * See Also:
265 * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
266 * <alureCreateStreamFromMemory>, <alureCreateStreamFromCallback>
268 ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromStaticMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
270 if(alGetError() != AL_NO_ERROR)
272 SetError("Existing OpenAL error");
273 return NULL;
276 if(chunkLength < 0)
278 SetError("Invalid chunk length");
279 return NULL;
282 if(numBufs < 0)
284 SetError("Invalid buffer count");
285 return NULL;
288 if(length <= 0)
290 SetError("Invalid data length");
291 return NULL;
294 MemDataInfo memData;
295 memData.Data = fdata;
296 memData.Length = length;
297 memData.Pos = 0;
299 alureStream *stream = create_stream(memData);
300 if(!stream) return NULL;
302 return InitStream(stream, chunkLength, numBufs, bufs);
305 /* Function: alureCreateStreamFromCallback
307 * Creates a stream using the specified callback to retrieve data. Requires an
308 * active context.
310 * Parameters:
311 * callback - This is called when more data is needed from the stream. Up to
312 * the specified number of bytes should be written to the data
313 * pointer, and the number of bytes actually written should be
314 * returned. The number of bytes written must be block aligned for
315 * the format (eg. a multiple of 4 for AL_FORMAT_STEREO16), or an
316 * OpenAL error may occur during buffering.
317 * userdata - A handle passed through to the callback.
318 * format - The format of the data the callback will be giving. The format must
319 * be valid for the context.
320 * samplerate - The sample rate (frequency) of the stream
322 * Returns:
323 * An opaque handle used to control the opened stream, or NULL on error.
325 * See Also:
326 * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>,
327 * <alureCreateStreamFromMemory>, <alureCreateStreamFromStaticMemory>
329 ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromCallback(
330 ALuint (*callback)(void *userdata, ALubyte *data, ALuint bytes),
331 void *userdata, ALenum format, ALuint samplerate,
332 ALsizei chunkLength, ALsizei numBufs, ALuint *bufs)
334 if(alGetError() != AL_NO_ERROR)
336 SetError("Existing OpenAL error");
337 return NULL;
340 if(callback == NULL)
342 SetError("Invalid callback");
343 return NULL;
346 if(chunkLength < 0)
348 SetError("Invalid chunk length");
349 return NULL;
352 if(numBufs < 0)
354 SetError("Invalid buffer count");
355 return NULL;
358 UserCallbacks newcb;
359 newcb.open_file = NULL;
360 newcb.open_mem = NULL;
361 newcb.get_fmt = NULL;
362 newcb.decode = callback;
363 newcb.rewind = NULL;
364 newcb.close = NULL;
366 alureStream *stream = create_stream(userdata, format, samplerate, newcb);
367 return InitStream(stream, chunkLength, numBufs, bufs);
370 /* Function: alureGetStreamFrequency
372 * Retrieves the frequency used for the given stream.
374 * Returns:
375 * 0 on error.
377 * *Version Added*: 1.1
379 ALURE_API ALsizei ALURE_APIENTRY alureGetStreamFrequency(alureStream *stream)
381 ALenum format;
382 ALuint rate, balign;
384 if(!alureStream::Verify(stream))
386 SetError("Invalid stream pointer");
387 return 0;
390 if(!stream->GetFormat(&format, &rate, &balign))
392 SetError("Could not get stream format");
393 return 0;
396 return rate;
399 /* Function: alureBufferDataFromStream
401 * Buffers the given buffer objects with the next chunks of data from the
402 * stream. The given buffer objects do not need to be ones given by the
403 * alureCreateStreamFrom* functions. Requires an active context.
405 * Returns:
406 * The number of buffers filled with new data, or -1 on error. If the value
407 * returned is less than the number requested, the end of the stream has been
408 * reached.
410 ALURE_API ALsizei ALURE_APIENTRY alureBufferDataFromStream(alureStream *stream, ALsizei numBufs, ALuint *bufs)
412 if(alGetError() != AL_NO_ERROR)
414 SetError("Existing OpenAL error");
415 return -1;
418 if(!alureStream::Verify(stream))
420 SetError("Invalid stream pointer");
421 return -1;
424 if(numBufs < 0)
426 SetError("Invalid buffer count");
427 return -1;
430 for(ALsizei i = 0;i < numBufs;i++)
432 if(!bufs[i] || !alIsBuffer(bufs[i]))
434 SetError("Invalid buffer ID");
435 return -1;
439 ALenum format;
440 ALuint freq, blockAlign;
442 if(!stream->GetFormat(&format, &freq, &blockAlign))
444 SetError("Could not get stream format");
445 return -1;
448 ALsizei filled;
449 for(filled = 0;filled < numBufs;filled++)
451 ALuint got = stream->GetData(&stream->dataChunk[0], stream->dataChunk.size());
452 got -= got%blockAlign;
453 if(got == 0) break;
455 alBufferData(bufs[filled], format, &stream->dataChunk[0], got, freq);
456 if(alGetError() != AL_NO_ERROR)
458 SetError("Buffer load failed");
459 return -1;
463 return filled;
466 /* Function: alureRewindStream
468 * Rewinds the stream so that the next alureBufferDataFromStream call will
469 * restart from the beginning of the audio file.
471 * Returns:
472 * AL_FALSE on error.
474 * See Also:
475 * <alureSetStreamOrder>
477 ALURE_API ALboolean ALURE_APIENTRY alureRewindStream(alureStream *stream)
479 if(!alureStream::Verify(stream))
481 SetError("Invalid stream pointer");
482 return AL_FALSE;
485 return stream->Rewind();
488 /* Function: alureSetStreamOrder
490 * Skips the module decoder to the specified order, so following buffering
491 * calls will decode from the specified order. For non-module formats, setting
492 * order 0 is identical to rewinding the stream (other orders will fail).
494 * Returns:
495 * AL_FALSE on error.
497 * *Version Added*: 1.1
499 * See Also:
500 * <alureRewindStream>
502 ALURE_API ALboolean ALURE_APIENTRY alureSetStreamOrder(alureStream *stream, ALuint order)
504 if(!alureStream::Verify(stream))
506 SetError("Invalid stream pointer");
507 return AL_FALSE;
510 return stream->SetOrder(order);
513 /* Function: alureSetStreamPatchset
515 * Specifies the patchset to use for MIDI streams. By default, the FluidSynth
516 * decoder will look for one in the FLUID_SOUNDFONT environment variable, but
517 * this can be used to change it to something different. On non-MIDI streams,
518 * this has no effect.
520 * Returns:
521 * AL_FALSE on error.
523 * *Version Added*: 1.1
525 ALURE_API ALboolean ALURE_APIENTRY alureSetStreamPatchset(alureStream *stream, const ALchar *patchset)
527 if(!alureStream::Verify(stream))
529 SetError("Invalid stream pointer");
530 return AL_FALSE;
533 return stream->SetPatchset(patchset);
536 /* Function: alureDestroyStream
538 * Closes an opened stream. For convenience, it will also delete the given
539 * buffer objects. The given buffer objects do not need to be ones given by the
540 * alureCreateStreamFrom* functions. Requires an active context.
542 * Returns:
543 * AL_FALSE on error.
545 ALURE_API ALboolean ALURE_APIENTRY alureDestroyStream(alureStream *stream, ALsizei numBufs, ALuint *bufs)
547 if(alGetError() != AL_NO_ERROR)
549 SetError("Existing OpenAL error");
550 return AL_FALSE;
553 if(numBufs < 0)
555 SetError("Invalid buffer count");
556 return AL_FALSE;
559 if(stream && !alureStream::Verify(stream))
561 SetError("Invalid stream pointer");
562 return AL_FALSE;
565 if(numBufs > 0)
567 alDeleteBuffers(numBufs, bufs);
568 if(alGetError() != AL_NO_ERROR)
570 SetError("Buffer deletion failed");
571 return AL_FALSE;
575 if(stream)
577 StopStream(stream);
578 std::istream *f = stream->fstream;
579 delete stream;
580 delete f;
582 return AL_TRUE;