-
Notifications
You must be signed in to change notification settings - Fork 0
/
OggPlayerFBN.cs
430 lines (395 loc) · 13.8 KB
/
OggPlayerFBN.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//
// OggPlayer.cs
//
// Author:
// dragon@the-dragons-nest.co.uk
//
// Copyright (c) 2010 Matthew Harris
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Threading;
using OpenTK.Audio;
using OpenTK.Audio.OpenAL;
namespace DragonOgg
{
/// <summary>
/// OggPlayerFBN class (Fixed Buffer Number)
/// This class takes OggFile objects and outputs them in a threaded player
/// using OpenAL (through the OpenTK wrapper)
/// The FBN player has a fixed number of buffers - Use SetBufferInfo to configure them
/// This is useful for background playing where memory is a significant issue.
/// </summary>
public class OggPlayerFBN : OggPlayer
{
private uint[] m_Buffers;
private int m_BufferCount;
private int m_BufferSize;
// Property exposure
/// <summary>
/// The current size of each buffer block
/// Use SetBufferInfo to change this value
/// </summary>
public int BufferSize { get { return m_BufferSize; } }
/// <summary>
/// The current number of buffer blocks
/// Use SetBufferInfo to change this value
/// </summary>
public int BufferCount { get { return m_BufferCount; } }
/// <summary>
/// Constructor
/// </summary>
public OggPlayerFBN()
{
m_PlayerState = OggPlayerStatus.Waiting;
m_UpdateDelay = 10;
m_Context = new AudioContext(); // Initialise the AudioContext
m_BufferCount = 32;
m_BufferSize = 4096;
m_Buffers = new uint[m_BufferCount]; // We're using four buffers so we always have a supply of data
m_TickInterval = 1; // Default tick is every second
m_TickEnabled = false; // Tick event is disabled by default
if (!InitSource()) { throw new OggPlayerSourceException("Source initialisation failed"); }
}
/// <summary>
/// Function for configuring buffer settings
/// </summary>
/// <param name="NumberOfBuffers">
/// A <see cref="System.Int32"/>
/// </param>
/// <param name="BufferSize">
/// A <see cref="System.Int32"/>
/// </param>
public OggPlayerCommandReturn SetBufferInfo(int NumberOfBuffers, int BufferSize)
{
if (!((m_PlayerState==OggPlayerStatus.Stopped)||(m_PlayerState==OggPlayerStatus.Waiting))) { return OggPlayerCommandReturn.InvalidCommandInThisPlayerState; }
m_BufferCount = NumberOfBuffers;
m_BufferSize = BufferSize;
m_Buffers = new uint[m_BufferCount];
return OggPlayerCommandReturn.Success;
}
/// <summary>
/// Dispose of the player safely
/// </summary>
public override void Dispose ()
{
this.Playback_Stop();
AL.DeleteBuffers(m_Buffers);
if (!DestroySource()) { throw new OggPlayerSourceException("Source destruction failed"); }
if (m_Context!=null) { m_Context.Dispose(); m_Context = null; }
if (m_CurrentFile!=null) { m_CurrentFile.Dispose(); m_CurrentFile = null; }
}
/// <summary>
/// Destructor
/// </summary>
~OggPlayerFBN()
{
// Tidy up the OpenAL stuff
AL.DeleteBuffers(m_Buffers);
AL.DeleteSource(ref m_Source);
if (m_Context!=null) { m_Context.Dispose(); m_Context = null; }
if (m_CurrentFile!=null) { m_CurrentFile.Dispose(); m_CurrentFile = null; }
}
public override bool SetCurrentFile(OggFile NewFile)
{
// Check current state
if (!((m_PlayerState==OggPlayerStatus.Stopped)||(m_PlayerState==OggPlayerStatus.Waiting))) { return false; }
m_CurrentFile = NewFile;
StateChange(OggPlayerStatus.Stopped, OggPlayerStateChanger.UserRequest);
return true;
}
public override bool SetCurrentFile(string NewFilename)
{
return SetCurrentFile(new OggFile(NewFilename));
}
public override OggPlayerCommandReturn Playback_Play()
{
// We can only play if we're stopped (this should also stop us trying to play invalid files as we'll then be 'Waiting' or 'Error' rather than stopped)
if (m_PlayerState == OggPlayerStatus.Stopped)
{
// Begin buffering
StateChange(OggPlayerStatus.Buffering, OggPlayerStateChanger.UserRequest);
int usedBuffers = 0;
// Create & Populate buffers
for (int i=0;i<m_Buffers.Length;i++)
{
lock (OALLocker) {
OggBufferSegment obs = m_CurrentFile.GetBufferSegment(0);
if (obs.ReturnValue>0)
{
// Create a buffer
AL.GenBuffer(out m_Buffers[i]);
// Fill this buffer
AL.BufferData((int)m_Buffers[i], m_CurrentFile.Format, obs.Buffer, obs.ReturnValue, obs.RateHz);
usedBuffers++;
}
else if (obs.ReturnValue == 0)
{
// Probably a small file and we're at the end of it
break;
}
else
{
throw new Exception("Read error or EOF within initial buffer segment");
}
}
}
lock (OALLocker)
{
// We've filled four buffers with data, give 'em to the source
AL.SourceQueueBuffers(m_Source, usedBuffers, m_Buffers);
// Start playback
AL.SourcePlay(m_Source);
}
m_LastTick = 0;
m_LastError = ALError.NoError;
// Spawn a new player thread
StateChange(OggPlayerStatus.Playing, OggPlayerStateChanger.UserRequest);
new Thread(new ThreadStart(Player_Thread)).Start();
return OggPlayerCommandReturn.Success;
}
// If we're paused we'll be nice to the user and automatically call the Playback_UnPause function, which they should have done in the first place
else if (m_PlayerState == OggPlayerStatus.Paused)
{
Playback_UnPause();
return OggPlayerCommandReturn.Success;
}
else if (m_PlayerState == OggPlayerStatus.Waiting)
{
return OggPlayerCommandReturn.NoFile;
}
else
{
return OggPlayerCommandReturn.InvalidCommandInThisPlayerState;
}
}
// Player thread
private void Player_Thread()
{
bool Running = true; bool ReachedEOF = false; bool UnderRun = false;
while (Running)
{
// See what we're doing
if (m_PlayerState==OggPlayerStatus.Playing)
{
// Check number of buffers
int QueuedBuffers = 0;
AL.GetSource(m_Source, ALGetSourcei.BuffersQueued, out QueuedBuffers);
// EOF stuff
if (ReachedEOF)
{
// We've come to the end of the file, just see if there are any buffers left in the queue
if (QueuedBuffers>0)
{
// We want to remove the buffers, so carry on to the usual playing section
}
else
{
lock (OALLocker)
{
// End of file & all buffers played, exit.
Running = false;
// Stop the output device if it isn't already
if (AL.GetSourceState(m_Source)!=ALSourceState.Stopped) { AL.SourceStop(m_Source); }
m_CurrentFile.ResetFile(); // Reset file's internal pointer
// De-allocate all buffers
for(int i = 0; i<m_Buffers.Length; i++)
{
AL.DeleteBuffer(ref m_Buffers[i]);
}
m_Buffers = new uint[m_BufferCount];
}
// Set state stuff & return
StateChange(OggPlayerStatus.Stopped, OggPlayerStateChanger.EndOfFile);
SendMessage(OggPlayerMessageType.PlaybackEndOfFile);
return;
}
}
// If the number of buffers is greater than 0 & the source isn't playing, poke it so it does
if ((!ReachedEOF)&&(QueuedBuffers>0)&&(AL.GetError()==ALError.NoError))
{
if (AL.GetSourceState(m_Source) != ALSourceState.Playing)
{
AL.SourcePlay(m_Source);
}
}
// Check for buffer underrun
int ProcessedBuffers = 0; uint BufferRef=0;
lock (OALLocker)
{
AL.GetSource(m_Source, ALGetSourcei.BuffersProcessed, out ProcessedBuffers);
}
if (ProcessedBuffers>=m_BufferCount)
{
UnderRun = true;
SendMessage(OggPlayerMessageType.BufferUnderrun);
} else { UnderRun = false; }
// Unbuffer any processed buffers
while (ProcessedBuffers>0)
{
OggBufferSegment obs;
lock (OALLocker)
{
// For each buffer thats been processed, reload and queue a new one
AL.SourceUnqueueBuffers(m_Source, 1, ref BufferRef);
#if (DEBUG)
if (AL.GetError()!=ALError.NoError) { Console.WriteLine("SourceUnqueueBuffers: ALError: " + OggUtilities.GetEnumString(AL.GetError())); }
#endif
if (ReachedEOF) { --ProcessedBuffers; continue; } // If we're at the EOF loop to the next buffer here - we don't want to be trying to fill any more
obs = m_CurrentFile.GetBufferSegment(m_BufferSize); // Get chunk of tasty buffer data with the configured segment
}
// Check the buffer segment for errors
if (obs.ReturnValue>0)
{
lock (OALLocker)
{
// No error, queue data
AL.BufferData((int)BufferRef, m_CurrentFile.Format, obs.Buffer, obs.ReturnValue, obs.RateHz);
#if (DEBUG)
if (AL.GetError()!=ALError.NoError) { Console.WriteLine("BufferData: ALError: " + OggUtilities.GetEnumString(AL.GetError())); }
#endif
AL.SourceQueueBuffers(m_Source, 1, ref BufferRef);
#if (DEBUG)
if (AL.GetError()!=ALError.NoError) { Console.WriteLine("SourceQueueBuffers: ALError: " + OggUtilities.GetEnumString(AL.GetError())); }
#endif
}
}
else
{
if (obs.ReturnValue==0)
{
// End of file
SendMessage(OggPlayerMessageType.BufferEndOfFile);
ReachedEOF = true;
break;
}
else
{
// Something went wrong with the read
lock (OALLocker)
{
m_PlayerState = OggPlayerStatus.Error;
AL.SourceStop(m_Source);
Running = false;
}
SendMessage(OggPlayerMessageType.FileReadError);
break;
}
}
// Check for errors
m_LastError = AL.GetError();
if (m_LastError!= ALError.NoError)
{
StateChange(OggPlayerStatus.Error, OggPlayerStateChanger.Error);
lock (OALLocker) { AL.SourceStop(m_Source); }
SendMessage(OggPlayerMessageType.OpenALError, m_LastError);
Running = false;
break;
}
--ProcessedBuffers;
}
// If we under-ran, restart the player
if (UnderRun) { lock (OALLocker) { AL.SourcePlay(m_Source); } }
// Do stuff with the time values & tick event
m_PlayingOffset = m_CurrentFile.GetTime();
if (m_TickEnabled)
{
if (m_PlayingOffset>=m_LastTick+m_TickInterval)
{
m_LastTick = m_PlayingOffset;
SendTick(m_PlayingOffset, m_PlayingOffset);
}
}
}
else if (m_PlayerState==OggPlayerStatus.Seeking)
{
// Just wait for us to finish seeking
}
else if (m_PlayerState==OggPlayerStatus.Paused)
{
// Just wait for us to un-pause
}
else
{
// Some other state, abort the playback 'cos we shouldn't
// be in the Player_Thread in this case
Running = false;
}
// Allow other shizzle to execute
if (m_UpdateDelay>0) { Thread.Sleep(m_UpdateDelay); }
}
}
public override OggPlayerCommandReturn Playback_Stop()
{
if (!((m_PlayerState == OggPlayerStatus.Paused)||(m_PlayerState == OggPlayerStatus.Playing))) { return OggPlayerCommandReturn.InvalidCommandInThisPlayerState; }
// Stop the source and set the state to stop
lock (OALLocker)
{
// Stop playing
AL.SourceStop(m_Source);
// See how many buffers are queued, and unqueue them
int nBuffers;
AL.GetSource(m_Source, ALGetSourcei.BuffersQueued, out nBuffers);
if (nBuffers>0) { AL.SourceUnqueueBuffers((int)m_Source,nBuffers); }
// Reset the file object's internal location etc.
m_CurrentFile.ResetFile();
// De-allocate all buffers
for(int i = 0; i<m_Buffers.Length; i++)
{
AL.DeleteBuffer(ref m_Buffers[i]);
}
m_Buffers = new uint[m_BufferCount];
}
m_LastTick = 0;
// Set the new state
StateChange(OggPlayerStatus.Stopped, OggPlayerStateChanger.UserRequest);
return OggPlayerCommandReturn.Success;
}
public override OggPlayerCommandReturn Playback_Pause()
{
if (!(m_PlayerState == OggPlayerStatus.Playing)) { return OggPlayerCommandReturn.InvalidCommandInThisPlayerState; }
lock (OALLocker)
{
AL.SourcePause(m_Source);
}
StateChange(OggPlayerStatus.Paused, OggPlayerStateChanger.UserRequest);
return OggPlayerCommandReturn.Success;
}
public override OggPlayerCommandReturn Playback_UnPause()
{
if (!(m_PlayerState == OggPlayerStatus.Paused)) { return OggPlayerCommandReturn.InvalidCommandInThisPlayerState; }
lock (OALLocker)
{
AL.SourcePlay(m_Source);
}
StateChange(OggPlayerStatus.Playing, OggPlayerStateChanger.UserRequest);
return OggPlayerCommandReturn.Success;
}
public override OggPlayerCommandReturn Playback_Seek(float RequestedTime)
{
if (!((m_PlayerState == OggPlayerStatus.Playing)||(m_PlayerState == OggPlayerStatus.Playing))) { return OggPlayerCommandReturn.InvalidCommandInThisPlayerState; }
OggPlayerCommandReturn retVal = OggPlayerCommandReturn.Error;
StateChange(OggPlayerStatus.Seeking, OggPlayerStateChanger.UserRequest);
lock (OALLocker)
{
AL.SourcePause(m_Source);
retVal = m_CurrentFile.SeekToTime(RequestedTime);
AL.SourcePlay(m_Source);
}
m_LastTick = RequestedTime - m_TickInterval;
StateChange(OggPlayerStatus.Playing, OggPlayerStateChanger.UserRequest);
return retVal;
}
}
}