Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/sound/ogg_player.cc @ 7308

Last change on this file since 7308 was 7308, checked in by bensch, 18 years ago

orxonox/trunk: added a mutex, that should prevent the SoundEngine from failing, when jumping around in the file

File size: 12.0 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14
15
16   -------------------------------------------------------------------
17   The source of this file comes stright from http://www.devmaster.net
18   Thanks a lot for the nice work, and the easy portability to our Project.
19*/
20
21#include <iostream>
22
23#include "ogg_player.h"
24
25#include "sound_engine.h"
26
27#include "debug.h"
28
29/**
30 * initializes an Ogg-player from a file
31 * @param fileName the file to load
32 */
33OggPlayer::OggPlayer(const std::string& fileName)
34{
35  this->setClassID(CL_SOUND_OGG_PLAYER, "OggPlayer");
36
37  this->state = OggPlayer::None;
38
39  this->source = 0;
40  this->buffers[0] = 0;
41  this->buffers[1] = 0;
42  this->musicThreadID = NULL;
43  this->musicMutex = SDL_CreateMutex();
44
45  if (!fileName.empty())
46  {
47    if (this->open(fileName))
48      this->setName(fileName);
49  }
50
51}
52
53/**
54 * @brief deletes the OggPlayer
55 */
56OggPlayer::~OggPlayer()
57{
58  this->release();
59  SDL_DestroyMutex(this->musicMutex);
60}
61
62///////////////
63// INTERFACE //
64///////////////
65/**
66 * @brief opens a file for playback
67 * @param fileName the file to open
68 */
69bool OggPlayer::open(const std::string& fileName)
70{
71  // release old Ogg-File (if loaded)
72  if (this->state & OggPlayer::FileOpened)
73    this->release();
74
75  // allocating Buffers
76  if (this->buffers[0] == 0)
77    alGenBuffers(2, this->buffers);
78  SoundEngine::checkError("Allocating Buffers", __LINE__);
79  if (this->buffers[0] != 0 && this->buffers[1] != 0)
80    state |= OggPlayer::BuffersAllocated;
81  else
82  {
83    PRINTF(2)("Unable to allocate al-Buffers\n");
84    this->release();
85    return false;
86  }
87  // allocating source
88  if (this->source == 0)
89    SoundEngine::getInstance()->popALSource(this->source);
90  if (this->source != 0)
91    state |= OggPlayer::SourceAllocated;
92  else
93  {
94    PRINTF(2)("No more Sources Availiable (maybe you should consider raising the source-count.)\n");
95    this->release();
96    return false;
97  }
98
99  // opening the FILE;
100  int result;
101  if(!(oggFile = fopen(fileName.c_str(), "rb")))
102  {
103    PRINTF(2)("Could not open Ogg file.");
104    this->release();
105    return false;
106  }
107  // reading the Stream.
108  if((result = ov_open(oggFile, &oggStream, NULL, 0)) < 0)
109  {
110    PRINTF(2)("Could not open Ogg stream. %s", getVorbisError(result));
111    fclose(oggFile);
112    this->release();
113    return false;
114  }
115  this->state |= OggPlayer::FileOpened;
116
117  // acquiring the vorbis-properties.
118  vorbisInfo = ov_info(&oggStream, -1);
119  vorbisComment = ov_comment(&oggStream, -1);
120
121  if(vorbisInfo->channels == 1)
122    format = AL_FORMAT_MONO16;
123  else
124    format = AL_FORMAT_STEREO16;
125
126  // setting the Source Properties.
127  alSource3f(source, AL_POSITION,        0.0, 0.0, 0.0);
128  alSource3f(source, AL_VELOCITY,        0.0, 0.0, 0.0);
129  alSource3f(source, AL_DIRECTION,       0.0, 0.0, 0.0);
130  alSourcef (source, AL_ROLLOFF_FACTOR,  0.0          );
131  alSourcei (source, AL_SOURCE_RELATIVE, AL_TRUE      );
132  alSourcef (source, AL_GAIN,            SoundEngine::getInstance()->getMusicVolume());
133  SoundEngine::checkError("OggPlayer::open()::SetSourceProperties", __LINE__);
134
135  // Set to State Stopped
136  this->state |= OggPlayer::Stopped;
137  return true;
138}
139
140
141/**
142 * @brief start Playing Music.
143 * @returns true on success false otherwise.
144 */
145bool OggPlayer::play()
146{
147  if (!(this->state & OggPlayer::FileOpened))
148    return false;
149
150  this->state &= ~(OggPlayer::Stopped | OggPlayer::Paused);
151
152  if (!this->playback())
153    return false;
154
155  if (this->musicThreadID == NULL)
156    return ((this->musicThreadID = SDL_CreateThread(OggPlayer::musicThread, (void*)this)) != NULL);
157  return true;
158}
159
160
161void OggPlayer::stop()
162{
163  this->state &= ~(OggPlayer::Playing | OggPlayer::Paused);
164  this->state |= OggPlayer::Stopped;
165
166  this->suspend();
167  this->rewind();
168}
169
170void OggPlayer::pause()
171{
172  this->state &= ~OggPlayer::Playing;
173
174  if (!(this->state & OggPlayer::Stopped))
175    this->state |= OggPlayer::Paused;
176
177  this->suspend();
178}
179
180/**
181 * @brief rewind to the beginning, and play (if already playing)
182 */
183void OggPlayer::rewind()
184{
185  this->jumpTo(0.0f);
186}
187
188/**
189 * @brief jump to Second timeCode in the MusicFile
190 * @param timeCode where to jump to.
191 */
192void OggPlayer::jumpTo(float timeCode)
193{
194
195  if (this->state & OggPlayer::FileOpened)
196  {
197    SDL_mutexP(this->musicMutex);
198    ov_time_seek(&this->oggStream, timeCode);
199    SDL_mutexV(this->musicMutex);
200  }
201}
202
203/**
204 * @returns the Length of the Music in Seconds
205 */
206float OggPlayer::length()
207{
208  if (this->state & OggPlayer::FileOpened)
209    return ov_time_total(&this->oggStream, -1);
210  else
211    return 0.0f;
212}
213
214
215/**
216 * @returns true if the file is playing
217 */
218bool OggPlayer::isPlaying()
219{
220  if (!(this->state & OggPlayer::FileOpened))
221    return false;
222  ALenum state;
223
224  alGetSourcei(this->source, AL_SOURCE_STATE, &state);
225
226  return (state == AL_PLAYING);
227}
228
229
230
231////////////////////////
232// INTERNAL FUNCTIONS //
233////////////////////////
234/**
235 * @brief creates a Thread for Playing back the music even if the rest of the Engine is slow
236 * @param oggPlayer the OggPlayer to play back
237 * @returns -1 on error.
238 */
239int OggPlayer::musicThread(void* oggPlayer)
240{
241  if (oggPlayer == NULL)
242    return -1;
243  OggPlayer* ogg = (OggPlayer*)oggPlayer;
244
245  PRINTF(4)("STARTIG AUDIO THREAD\n");
246  while (ogg->state & OggPlayer::Playing)
247  {
248    SDL_mutexP(ogg->musicMutex);
249    ogg->update();
250    SDL_mutexV(ogg->musicMutex);
251    SDL_Delay(1);
252  }
253  PRINTF(4)("End the AudioThread\n");
254}
255
256
257/**
258 * @brief plays back the sound
259 * @return true if running, false otherwise
260 */
261bool OggPlayer::playback()
262{
263  if (!(this->state & OggPlayer::FileOpened))
264    return false;
265
266  if(this->state & OggPlayer::Playing)
267    return true;
268  this->state |= OggPlayer::Playing;
269
270  if(!this->stream(this->buffers[0]) || !this->stream(this->buffers[1]))
271    return false;
272
273  alSourceQueueBuffers(this->source, 2, this->buffers);
274  if (DEBUG >= 3)
275    SoundEngine::checkError("OggPlayer::playback()::alSourceQueueBuffers", __LINE__);
276
277
278  alSourcePlay(this->source);
279  if (DEBUG >= 3)
280    SoundEngine::checkError("OggPlayer::playback()::alSourcePlay", __LINE__);
281  return true;
282}
283
284
285/**
286 * @brief waits for the AudioThread to be finished.
287 */
288void OggPlayer::suspend()
289{
290  if (this->musicThreadID != NULL)
291  {
292    assert (!(this->state & Playing));
293    this->printState();
294    SDL_WaitThread(this->musicThreadID, NULL);
295    this->musicThreadID = NULL;
296  }
297  if (this->state & OggPlayer::SourceAllocated)
298  {
299    alSourceStop(this->source);
300    alSourcei(this->source, AL_BUFFER, 0);
301  }
302}
303
304/**
305 * @brief updates the stream, this has to be done every few parts of a second, for sound-consistency
306 * @returns true, if the Sound is playing flawlessly
307 */
308bool OggPlayer::update()
309{
310  int processed = 0;
311  bool active = true;
312
313  alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
314  if (DEBUG >= 3)
315    SoundEngine::checkError("OggPlayer::update()::alGetSourceI", __LINE__);
316
317  while(processed--)
318  {
319    ALuint buffer;
320
321    alSourceUnqueueBuffers(source, 1, &buffer);
322    if (DEBUG >= 3)
323      SoundEngine::checkError("OggPlayer::update()::unqueue", __LINE__);
324
325    active = stream(buffer);
326
327    alSourceQueueBuffers(source, 1, &buffer);
328    if (DEBUG >= 3)
329      SoundEngine::checkError("OggPlayer::update()::queue", __LINE__);
330  }
331
332  return active;
333}
334
335/**
336 * @brief gets a new Stream from buffer
337 * @param buffer the buffer to get the stream from
338 * @return true, if everything worked as planed
339 */
340bool OggPlayer::stream(ALuint buffer)
341{
342  if (unlikely(!(this->state & Playing)))
343    return false;
344  char pcm[OGG_PLAYER_BUFFER_SIZE];
345  int  size = 0;
346  int  section;
347  int  result;
348
349  while(size < OGG_PLAYER_BUFFER_SIZE)
350  {
351    result = ov_read(&this->oggStream, pcm + size, OGG_PLAYER_BUFFER_SIZE - size, 0, 2, 1, &section);
352
353    if(result > 0)
354      size += result;
355    else if(result < 0)
356      throw getVorbisError(result);
357    else /* eof */
358      ov_time_seek(&this->oggStream, 0.0);
359  }
360
361  if(size == 0)
362    return false;
363
364  alBufferData(buffer, format, pcm, size, vorbisInfo->rate);
365  if (DEBUG >= 3)
366    SoundEngine::checkError("OggPlayer::stream()::BUFFER", __LINE__);
367
368  return true;
369}
370
371
372/**
373 * @brief releases a stream
374 */
375void OggPlayer::release()
376{
377  if (this->state & OggPlayer::SourceAllocated)
378  {
379    assert(alIsSource(this->source));
380    if (this->state & OggPlayer::Playing);
381    {
382      this->state &= ~OggPlayer::Playing;
383      // Kill the Music Thread.
384      if (this->musicThreadID != NULL)
385        this->suspend();
386
387      SoundEngine::checkError("OggPlayer::release()::alSourceStop", __LINE__);
388    }
389    empty();
390    alSourcei(this->source, AL_BUFFER, 0);
391    SoundEngine::getInstance()->pushALSource(this->source);
392    this->source = 0;
393    this->state &= ~SourceAllocated;
394  }
395  if (this->state & OggPlayer::BuffersAllocated)
396  {
397    assert (this->buffers[0] != 0 && this->buffers[1] != 0);
398    alDeleteBuffers(2, buffers);
399    SoundEngine::checkError("OggPlayer::release()::alDeleteBuffers", __LINE__);
400    this->buffers[0] = 0;
401    this->buffers[1] = 0;
402    this->state &= ~OggPlayer::BuffersAllocated;
403  }
404
405  if (this->state & OggPlayer::FileOpened)
406  {
407    ov_clear(&oggStream);
408    this->state &= ~OggPlayer::FileOpened;
409  }
410
411}
412
413
414/**
415 * @brief empties the buffers
416 */
417void OggPlayer::empty()
418{
419  int queued;
420
421  alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
422
423  while(queued--)
424  {
425    ALuint buffer;
426
427    alSourceUnqueueBuffers(source, 1, &buffer);
428    SoundEngine::checkError("OggPlayer::empty()::unqueue Buffers", __LINE__);
429  }
430}
431
432
433/////////////////////
434// DEBUG FUNCTIONS //
435/////////////////////
436/**
437 * displays some info about the ogg-file
438 */
439void OggPlayer::debug() const
440{
441  cout
442  << "version         " << vorbisInfo->version         << "\n"
443  << "channels        " << vorbisInfo->channels        << "\n"
444  << "rate (hz)       " << vorbisInfo->rate            << "\n"
445  << "bitrate upper   " << vorbisInfo->bitrate_upper   << "\n"
446  << "bitrate nominal " << vorbisInfo->bitrate_nominal << "\n"
447  << "bitrate lower   " << vorbisInfo->bitrate_lower   << "\n"
448  << "bitrate window  " << vorbisInfo->bitrate_window  << "\n"
449  << "\n"
450  << "vendor " << vorbisComment->vendor << "\n";
451
452  for(int i = 0; i < vorbisComment->comments; i++)
453    cout << "   " << vorbisComment->user_comments[i] << "\n";
454
455  cout << endl;
456}
457
458
459void OggPlayer::printState() const
460{
461  PRINTF(0)("OggPlayer is in the following States: ");
462  if (this->state & OggPlayer::FileOpened)
463    PRINT(0)("FileOpened ");
464  if (this->state & OggPlayer::SourceAllocated)
465    PRINT(0)("SourceAllocated ");
466  if (this->state & OggPlayer::BuffersAllocated)
467    PRINT(0)("BuffersAllocated ");
468  if (this->state & OggPlayer::Stopped)
469    PRINT(0)("Stopped ");
470  if (this->state & OggPlayer::Playing)
471    PRINT(0)("Playing ");
472  if (this->state & OggPlayer::Paused)
473    PRINT(0)("Paused ");
474  if (this->state & OggPlayer::Error)
475    PRINT(0)("Error ");
476  PRINT(0)("\n");
477}
478
479/**
480 * returns errors
481 * @param code the error-code
482 * @return the error as a String
483 */
484const char* OggPlayer::getVorbisError(int code)
485{
486  switch(code)
487  {
488    case OV_EREAD:
489      return ("Read from media.");
490    case OV_ENOTVORBIS:
491      return ("Not Vorbis data.");
492    case OV_EVERSION:
493      return ("Vorbis version mismatch.");
494    case OV_EBADHEADER:
495      return ("Invalid Vorbis header.");
496    case OV_EFAULT:
497      return ("Internal logic fault (bug or heap/stack corruption.");
498    default:
499      return ("Unknown Ogg error.");
500  }
501}
502
Note: See TracBrowser for help on using the repository browser.