1 /*
2 DSFML - The Simple and Fast Multimedia Library for D
3 
4 Copyright (c) 2013 - 2015 Jeremy DeHaan (dehaan.jeremiah@gmail.com)
5 
6 This software is provided 'as-is', without any express or implied warranty.
7 In no event will the authors be held liable for any damages arising from the use of this software.
8 
9 Permission is granted to anyone to use this software for any purpose, including commercial applications,
10 and to alter it and redistribute it freely, subject to the following restrictions:
11 
12 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.
13 If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
14 
15 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
16 
17 3. This notice may not be removed or altered from any source distribution
18 */
19 
20 module dsfml.audio.music;
21 
22 import core.time;
23 
24 import dsfml.system.mutex;
25 import dsfml.system.inputstream;
26 
27 import dsfml.audio.soundstream;
28 
29 
30 /++
31  + Streamed music played from an audio file.
32  + 
33  + Musics are sounds that are streamed rather than completely loaded in memory.
34  + 
35  + This is especially useful for compressed musics that usually take hundreds of MB when they are uncompressed: by streaming it instead of loading it entirely, you avoid saturating the memory and have almost no loading delay.
36  + 
37  + Apart from that, a Music has almost the same features as the SoundBuffer / Sound pair: you can play/pause/stop it, request its parameters (channels, sample rate), change the way it is played (pitch, volume, 3D position, ...), etc.
38  + 
39  + As a sound stream, a music is played in its own thread in order not to block the rest of the program. This means that you can leave the music alone after calling play(), it will manage itself very well.
40  + 
41  + See_Also: http://sfml-dev.org/documentation/2.0/classsf_1_1Music.php#details
42  + Authors: Laurent Gomila, Jeremy DeHaan
43  +/
44 class Music : SoundStream
45 {
46 	import dsfml.audio.soundfile;
47 
48 	private
49 	{
50 		SoundFile m_file;
51 		Duration m_duration;
52 		short[] m_samples;
53 		Mutex m_mutex;
54 	}
55 
56 	this()
57 	{
58 		m_file.create();
59 
60 		m_mutex = new Mutex();
61 
62 		super();
63 	}
64 
65 	/**
66 	 * Open a music from an audio file.
67 	 * 
68 	 * This function doesn't start playing the music (call play() to do so). 
69 	 * 
70 	 * Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
71 	 * 
72 	 * Params:
73 	 * 		filename =	Path of the music file to open.
74 	 * Returns: True if loading succeeded, false if it failed.
75 	 */
76 	bool openFromFile(string filename)
77 	{
78 		//stop music if already playing
79 		stop();
80 
81 		if(!m_file.openReadFromFile(filename))
82 		{
83 			return false;
84 		}
85 
86 		initialize();
87 
88 		return true;
89 	}
90 
91 	/**
92 	 * Open a music from an audio file in memory.
93 	 * 
94 	 * This function doesn't start playing the music (call play() to do so).
95 	 *
96 	 * Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
97 	 * 
98 	 * Since the music is not loaded completely but rather streamed continuously, the data must remain available as long as the music is playing (ie. you can't deallocate it right after calling this function).
99 	 * 
100 	 * Params:
101 	 * 		data =	The array of data
102 	 * Returns: True if loading succeeded, false if it failed.
103 	 */
104 	bool openFromMemory(const(void)[] data)
105 	{
106 		stop();
107 
108 		if(!m_file.openReadFromMemory(data))
109 		{
110 			return false;
111 		}
112 
113 		initialize();
114 		return true;
115 	}
116 
117 	/**
118 	 * Open a music from an audio file in memory.
119 	 * 
120 	 * This function doesn't start playing the music (call play() to do so). 
121 	 * 
122 	 * Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
123 	 * 
124 	 * Since the music is not loaded completely but rather streamed continuously, the stream must remain available as long as the music is playing (ie. you can't deallocate it right after calling this function).
125 	 * 
126 	 * Params:
127 	 * 		stream =	Source stream to read from
128 	 * Returns: True if loading succeeded, false if it failed.
129 	 */
130 	bool openFromStream(InputStream stream)
131 	{
132 		stop();
133 
134 		if(!m_file.openReadFromStream(stream))
135 		{
136 			return false;
137 		}
138 
139 		initialize();
140 
141 		return true;
142 	}
143 
144 	~this()
145 	{
146 		import dsfml.system.config;
147 		mixin(destructorOutput);
148 		stop();
149 	}
150 
151 	/// Get the total duration of the music.
152 	/// Returns: Music duration
153 	Duration getDuration()
154 	{
155 		return m_duration;
156 	}
157 
158 	protected
159 	{
160 		/**
161 		 * Request a new chunk of audio samples from the stream source.
162 		 * 
163 		 * This function fills the chunk from the next samples to read from the audio file.
164 		 * 
165 		 * Params:
166 		 * 		samples =	Array of samples to fill
167 		 * 
168 		 * Returns: True to continue playback, false to stop.
169 		 */
170 		override bool onGetData(ref const(short)[] samples)
171 		{
172 			import dsfml.system.lock;
173 
174 			Lock lock = Lock(m_mutex);
175 
176 			auto length = cast(size_t)m_file.read(m_samples);
177 			samples = m_samples[0..length];
178 
179 			return (samples.length == m_samples.length);
180 		}
181 		/**
182 		 * Change the current playing position in the stream source.
183 		 * 
184 		 * Params:
185 		 * 		timeOffset =	New playing position, from the beginning of the music
186 		 * 
187 		 * Implements SoundStream.
188 		 */
189 		override void onSeek(Duration timeOffset)
190 		{
191 			import dsfml.system.lock;
192 
193 			Lock lock = Lock(m_mutex);
194 
195 			m_file.seek(timeOffset.total!"usecs");
196 		}
197 	}
198 
199 	private
200 	{
201 		/**
202 		 * Define the audio stream parameters.
203 		 * 
204 		 * This function must be called by derived classes as soon as they know the audio settings of the stream to play. Any attempt to manipulate the stream (play(), ...) before calling this function will fail. 
205 		 * 
206 		 * It can be called multiple times if the settings of the audio stream change, but only when the stream is stopped.
207 		 * 
208 		 * Params:
209 		 * 		channelCount =	Number of channels of the stream
210 		 * 		sampleRate =	Sample rate, in samples per second
211 		 */
212 		void initialize()
213 		{
214 			size_t sampleCount = cast(size_t)m_file.getSampleCount();
215 
216 			uint channelCount = m_file.getChannelCount();
217 
218 			uint sampleRate = m_file.getSampleRate();
219 
220 			// Compute the music duration
221 			m_duration = usecs(sampleCount * 1_000_000 / sampleRate / channelCount);
222 			
223 			// Resize the internal buffer so that it can contain 1 second of audio samples
224 			m_samples.length = sampleRate * channelCount;
225 
226 			// Initialize the stream
227 			super.initialize(channelCount, sampleRate);
228 
229 		}
230 
231 	}
232 }
233 
234 unittest
235 {
236 	version(DSFML_Unittest_Audio)
237 	{
238 		import std.stdio;
239 		import dsfml.system.clock;
240 
241 		writeln("Unit test for Music Class");
242 
243 		auto music = new Music();
244 
245 		//TODO: update this for a real unit test users can run themselves.
246 		if(!music.openFromFile("res/TestMusic.ogg"))
247 		{
248 			return;
249 		}
250 
251 		auto clock = new Clock();
252 
253 		writeln("Playing music for 5 seconds");
254 
255 		music.play();
256 		while(clock.getElapsedTime().total!"seconds" < 5)
257 		{
258 			//playing music in seoarate thread while main thread is stuck here
259 		}
260 
261 		music.stop();
262 
263 
264 
265 
266 		writeln();
267 	}
268 }