Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

orxonox/trunk: Play Stop Rewind and Pause work perfectly: you can test this in this revision

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