Fixed crash with empty playlist~
[someplayer] / src / player / player.cpp
1 /*
2  * SomePlayer - An alternate music player for Maemo 5
3  * Copyright (C) 2010 Nikolay (somebody) Tischenko <niktischenko@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  */
19
20 #include "player.h"
21 #include <phonon/MediaSource>
22 #include <phonon/Effect>
23 #include <phonon/BackendCapabilities>
24 #include <phonon/EffectParameter>
25 #include "../config.h"
26 #include <QTime>
27 #include <QTimer>
28
29 using namespace SomePlayer::Playback;
30 using namespace SomePlayer::DataObjects;
31 using namespace SomePlayer::Storage;
32
33 int Randomizer::next() {
34         int res = 0;
35         if (_rand.count() == 0) {
36                 _shuffle();
37                 res = next();
38         } else {
39                 res = _rand.takeFirst();
40         }
41         return res;
42 }
43
44 void Randomizer::setPlaylist(QList<int> pl) {
45         _playlist = pl;
46         _shuffle();
47         _last = -1;
48 }
49
50 void Randomizer::_shuffle() {
51         _rand.clear();
52         // Fisher-Yates algorithm:
53         _rand = _playlist;
54         int cnt = _playlist.count();
55         int j = 0;
56         int tmp = 0;
57         for (int i = cnt-1; i > 0; i--) {
58                 j = qrand() % (i+1);
59                 tmp = _rand[i];
60                 _rand[i] = _rand[j];
61                 _rand[j] = tmp;
62         }
63         if (cnt > 1 && _last == _rand[0]) {
64                 _rand.removeAt(0);
65                 _rand.insert(qrand() % (cnt-1) + 1, _last);
66         }
67         if (!_rand.isEmpty())
68                 _last = _rand.last();
69         else _last = -1;
70 }
71
72 void Randomizer::removeId(int id) {
73         _rand.removeOne(id);
74 }
75
76 Player::Player(QObject *parent) :
77     QObject(parent)
78 {
79         _player = new Phonon::MediaObject(this);
80         _output = new Phonon::AudioOutput(Phonon::MusicCategory, this);
81         _player->setTickInterval(1000);
82         _equalizer = NULL;
83         _equalizer_enabled = false;
84         connect(_player, SIGNAL(stateChanged(Phonon::State,Phonon::State)), this, SLOT(_stateChanged(Phonon::State,Phonon::State)));
85         connect(_player, SIGNAL(tick(qint64)), this, SLOT(_tick(qint64)));
86         connect(_player, SIGNAL(finished()), this, SLOT(next()));
87         _path = Phonon::createPath(_player, _output);
88         QList<Phonon::EffectDescription> effects = Phonon::BackendCapabilities::availableAudioEffects();
89         foreach (Phonon::EffectDescription desc, effects) {
90                 if (desc.name() == "equalizer-10bands") {
91                         _equalizer = new Phonon::Effect(desc, this);
92                         Config config;
93                         if (config.getValue("equalizer/equalizer").toString() == "enabled") {
94                                 for (int i = 0; i < 10; i++) {
95                                         QVariant var = config.getValue(QString("equalizer/band%1").arg(i));
96                                         setEqualizerValue(i, var.toDouble());
97                                 }
98                                 enableEqualizer();
99                         } else if (config.getValue("equalizer/equalizer") == "") {
100                                 for (int i = 0; i < 10; i++) {
101                                         config.setValue(QString("equalizer/band%1").arg(i), 0);
102                                 }
103                         }
104                 }
105         }
106         int seed = QTime::currentTime().msec();
107         qsrand(seed);
108         _random = _config.getValue("playback/random").toBool();
109         _repeat = (RepeatRule) _config.getValue("playback/repeat").toInt();
110         _current = -1;
111 }
112
113 void Player::setTrackId(int id) {
114         if (_random) {
115                 _randomizer.removeId(id);
116         }
117         _current = id;
118         if (!_history.isEmpty() && _history.top() != _current || _history.isEmpty()) {
119                 _history.push(_current);
120         }
121         _track = _playlist.tracks().at(_current);
122         _set_source();
123         _state = PLAYER_LOADING;
124         emit stateChanged(_state);
125 }
126
127 void Player::toggle() {
128         if (_state == PLAYER_PLAYING) { // pause
129                 _player->pause();
130                 _state = PLAYER_PAUSED;
131                 emit stateChanged(_state);
132         } else { //play
133                 play();
134         }
135 }
136
137 void Player::stop() {
138         _player->stop();
139         _state = PLAYER_STOPPED;
140         emit stateChanged(_state);
141 }
142
143 void Player::next() {
144         int count = _playlist.tracks().count();
145         if (count == 0) {
146                 stop(); // empty playlist
147                 return;
148         }
149         if (_repeat == REPEAT_ONE) {
150                 _set_source();
151                 play();
152                 return;
153         }
154         _history.push(_current % count);
155         if (!_queue.isEmpty()) {
156                 _current = _queue.dequeue();
157         } else if (!_prev_history.isEmpty()) {
158                 _current = _prev_history.pop();
159         } else {
160                 if (_random) {
161                         _current = _randomizer.next();
162                 } else {
163                         _current = _current + 1;
164                 }
165         }
166         if (_random && _history.count() >= count && _repeat == REPEAT_NO||
167                 _repeat == REPEAT_NO && _current >= count) {
168                 _history.clear();
169                 stop();
170         } else {
171                 _current %= count;
172                 _track = _playlist.tracks().at(_current);
173                 _set_source();
174                 play();
175         }
176 }
177
178 void Player::_set_source() {
179         _player->setCurrentSource(Phonon::MediaSource(_track.source()));
180         emit trackChanged(_track);
181 }
182
183 void Player::prev() {
184         if (_history.count() > 0) {
185                 _prev_history.push(_current);
186                 _current = _history.pop();
187                 _track = _playlist.tracks().at(_current);
188         }
189         _set_source();
190         play();
191 }
192
193 void Player::_stateChanged(Phonon::State newState, Phonon::State /*oldState*/) {
194         switch (newState) {
195         case Phonon::PlayingState:
196                 _state = PLAYER_PLAYING;
197                 emit stateChanged(_state);
198                 break;
199         case Phonon::ErrorState:
200                 play(); // force
201                 break;
202         default:
203                 break;
204         }
205 }
206
207 void Player::_tick(qint64 ticks) {
208         int done = ticks/1000;
209         int all = _track.metadata().length();
210         emit tick(done, all);
211         if (done+2 == all) {
212                 _track.setCount(_track.count()+1);
213                 emit trackDone(_track);
214         }
215 }
216
217 void Player::setPlaylist(Playlist playlist) {
218         _playlist = playlist;
219         _history.clear();
220         _prev_history.clear();
221         _queue.clear();
222         QList<int> ids;
223         int count = playlist.tracks().count();
224         for (int i = 0; i < count; i++) {
225                 ids.append(i);
226         }
227         _randomizer.setPlaylist(ids);
228 }
229
230 void Player::seek(int s) {
231         _player->seek(s*1000);
232         if (s >= _track.metadata().length()) {
233                 next();
234         }
235 }
236
237 void Player::play() {
238         if (_playlist.tracks().isEmpty())
239                 return;
240         _state = PLAYER_PLAYING;
241         emit stateChanged(_state);
242         if (_current == -1) {
243                 _current = 0;
244                 _track = _playlist.tracks().at(0);
245                 _set_source();
246         }
247         _player->play();
248 }
249
250 void Player::enqueue(int id) {
251         _queue.enqueue(id);
252 }
253
254 void Player::toggleRandom() {
255         _random = !_random;
256         _config.setValue("playback/random", _random);
257 }
258
259 void Player::toggleRepeat() {
260         if (_repeat == REPEAT_NO) {
261                 _repeat = REPEAT_ALL;
262         } else if (_repeat == REPEAT_ALL) {
263                 _repeat = REPEAT_ONE;
264         } else if (_repeat == REPEAT_ONE) {
265                 _repeat = REPEAT_NO;
266         }
267         _config.setValue("playback/repeat", _repeat);
268 }
269
270 void Player::equalizerValue(int band, double *val) {
271         if (_equalizer == NULL) {
272                 *val = 0;
273                 return;
274         }
275         if (band < 0 || band > 9) {
276                 *val = -24;
277                 return;
278         }
279         if (_equalizer_enabled) {
280                 QList<Phonon::EffectParameter> plist = _equalizer->parameters();
281                 QVariant var = _equalizer->parameterValue(plist[band]);
282                 *val = var.toDouble();
283         }
284 }
285
286 void Player::enableEqualizer() {
287         if (_equalizer == NULL)
288                 return;
289         _equalizer_enabled = true;
290         _path.insertEffect(_equalizer);
291         Config config;
292         config.setValue("equalizer/equalizer", "enabled");
293 }
294
295 void Player::disableEqualizer() {
296         if (_equalizer == NULL)
297                 return;
298         _equalizer_enabled = false;
299         _path.removeEffect(_equalizer);
300         Config config;
301         config.setValue("equalizer/equalizer", "disabled");
302 }
303
304 void Player::setEqualizerValue(int band, double value) {
305         if (_equalizer == NULL)
306                 return;
307         if (band < 0 || band > 9 || value < -24 || value > 12) {
308                 return;
309         }
310         QList<Phonon::EffectParameter> plist = _equalizer->parameters();
311         _equalizer->setParameterValue(plist[band], QVariant::fromValue(value));
312         Config config;
313         config.setValue(QString("equalizer/band%1").arg(band), value);
314 }
315
316 QString Player::artist() {
317         if (_current < 0)
318                 return "";
319         return _playlist.tracks().at(_current).metadata().artist();
320 }
321
322 QString Player::album() {
323         if (_current < 0)
324                 return "";
325         return _playlist.tracks().at(_current).metadata().album();
326 }
327
328 QString Player::title() {
329         if (_current < 0)
330                 return "";
331         return _playlist.tracks().at(_current).metadata().title();
332 }