summaryrefslogtreecommitdiffstats
path: root/juk/playermanager.cpp
blob: b60c7af518b2c1be382bfa8cb7644589e6823e12 (plain)
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
/***************************************************************************
    begin                : Sat Feb 14 2004
    copyright            : (C) 2004 by Scott Wheeler
    email                : wheeler@kde.org
***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

/**
 * Note to those who work here.  The preprocessor variables HAVE_ARTS and HAVE_GSTREAMER
 * are ::ALWAYS DEFINED::.  You can't use #ifdef to see if they're present, you should just
 * use #if.
 *
 * However, HAVE_AKODE is #define'd if present, and undefined if not present.
 * - mpyne
 */

#include <kdebug.h>
#include <klocale.h>

#include <qslider.h>
#include <qtimer.h>

#include <math.h>

#include "artsplayer.h"
#include "akodeplayer.h"
#include "gstreamerplayer.h"
#include "playermanager.h"
#include "playlistinterface.h"
#include "slideraction.h"
#include "statuslabel.h"
#include "actioncollection.h"
#include "collectionlist.h"
#include "coverinfo.h"
#include "tag.h"

#include "config.h"

using namespace ActionCollection;

enum PlayerManagerStatus { StatusStopped = -1, StatusPaused = 1, StatusPlaying = 2 };

////////////////////////////////////////////////////////////////////////////////
// helper functions
////////////////////////////////////////////////////////////////////////////////

enum SoundSystem { ArtsBackend = 0, GStreamerBackend = 1, AkodeBackend = 2 };

static Player *createPlayer(int system = ArtsBackend)
{

    Player *p = 0;
    switch(system) {
#ifdef HAVE_AKODE
    case AkodeBackend:
        p = new aKodePlayer;
        break;
#endif
#if HAVE_ARTS
    case ArtsBackend:
        p = new ArtsPlayer;
        break;
#endif
#if HAVE_GSTREAMER
    case GStreamerBackend:
        p = new GStreamerPlayer;
        break;
#endif 
    default:
#if HAVE_ARTS
        p = new ArtsPlayer;
#elif HAVE_GSTREAMER
        p = new GStreamerPlayer;
#else
        p = new aKodePlayer;
#endif
        break;
    }
    return p;
}

////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////

PlayerManager::PlayerManager() :
    Player(),
    m_sliderAction(0),
    m_playlistInterface(0),
    m_statusLabel(0),
    m_player(0),
    m_timer(0),
    m_noSeek(false),
    m_muted(false),
    m_setup(false)
{
// This class is the first thing constructed during program startup, and
// therefore has no access to the widgets needed by the setup() method.
// Since the setup() method will be called indirectly by the player() method
// later, just disable it here. -- mpyne
//    setup();
}

PlayerManager::~PlayerManager()
{
    delete m_player;
}

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

PlayerManager *PlayerManager::instance() // static
{
    static PlayerManager manager;
    return &manager;
}

bool PlayerManager::playing() const
{
    if(!player())
        return false;

    return player()->playing();
}

bool PlayerManager::paused() const
{
    if(!player())
        return false;

    return player()->paused();
}

float PlayerManager::volume() const
{
    if(!player())
        return 0;

    return player()->volume();
}

int PlayerManager::status() const
{
    if(!player())
        return StatusStopped;

    if(player()->paused())
        return StatusPaused;

    if(player()->playing())
        return StatusPlaying;

    return 0;
}

int PlayerManager::totalTime() const
{
    if(!player())
        return 0;

    return player()->totalTime();
}

int PlayerManager::currentTime() const
{
    if(!player())
        return 0;

    return player()->currentTime();
}

int PlayerManager::position() const
{
    if(!player())
        return 0;

    return player()->position();
}

QStringList PlayerManager::trackProperties()
{
    return FileHandle::properties();
}

QString PlayerManager::trackProperty(const QString &property) const
{
    if(!playing() && !paused())
        return QString::null;

    return m_file.property(property);
}

QPixmap PlayerManager::trackCover(const QString &size) const
{
    if(!playing() && !paused())
        return QPixmap();

    if(size.lower() == "small")
        return m_file.coverInfo()->pixmap(CoverInfo::Thumbnail);
    if(size.lower() == "large")
        return m_file.coverInfo()->pixmap(CoverInfo::FullSize);

    return QPixmap();
}

FileHandle PlayerManager::playingFile() const
{
    return m_file;
}

QString PlayerManager::playingString() const
{
    if(!playing())
        return QString::null;

    QString str = m_file.tag()->artist() + " - " + m_file.tag()->title();
    if(m_file.tag()->artist().isEmpty())
        str = m_file.tag()->title();

    return str;
}

void PlayerManager::setPlaylistInterface(PlaylistInterface *interface)
{
    m_playlistInterface = interface;
}

void PlayerManager::setStatusLabel(StatusLabel *label)
{
    m_statusLabel = label;
}

KSelectAction *PlayerManager::playerSelectAction(QObject *parent) // static
{
    KSelectAction *action = 0;
    action = new KSelectAction(i18n("&Output To"), 0, parent, "outputSelect");
    QStringList l;

#if HAVE_ARTS
    l << i18n("aRts");
#endif
#if HAVE_GSTREAMER
    l << i18n("GStreamer");
#endif
#ifdef HAVE_AKODE
    l << i18n("aKode");
#endif

    if(l.isEmpty()) {
        kdError(65432) << "Your JuK seems to have no output backend possibilities.\n";
        l << i18n("aKode"); // Looks like akode is the default backend.
    }

    action->setItems(l);
    return action;
}

////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////

void PlayerManager::play(const FileHandle &file)
{
    if(!player() || !m_playlistInterface)
        return;

    if(file.isNull()) {
        if(player()->paused())
            player()->play();
        else if(player()->playing()) {
            if(m_sliderAction->trackPositionSlider())
                m_sliderAction->trackPositionSlider()->setValue(0);
            player()->seekPosition(0);
        }
        else {
            m_playlistInterface->playNext();
            m_file = m_playlistInterface->currentFile();

            if(!m_file.isNull())
                player()->play(m_file);
        }
    }
    else {
        m_file = file;
        player()->play(file);
    }

    // Make sure that the player() actually starts before doing anything.

    if(!player()->playing()) {
        kdWarning(65432) << "Unable to play " << file.absFilePath() << endl;
        stop();
        return;
    }

    action("pause")->setEnabled(true);
    action("stop")->setEnabled(true);
    action("forward")->setEnabled(true);
    if(action<KToggleAction>("albumRandomPlay")->isChecked())
        action("forwardAlbum")->setEnabled(true);
    action("back")->setEnabled(true);

    if(m_sliderAction->trackPositionSlider())
        m_sliderAction->trackPositionSlider()->setEnabled(true);

    m_timer->start(m_pollInterval);

    emit signalPlay();
}

void PlayerManager::play(const QString &file)
{
    CollectionListItem *item = CollectionList::instance()->lookup(file);
    if(item) {
        Playlist::setPlaying(item);
        play(item->file());
    }
}

void PlayerManager::play()
{
    play(FileHandle::null());
}

void PlayerManager::pause()
{
    if(!player())
        return;

    if(player()->paused()) {
        play();
        return;
    }

    m_timer->stop();
    action("pause")->setEnabled(false);

    player()->pause();

    emit signalPause();
}

void PlayerManager::stop()
{
    if(!player() || !m_playlistInterface)
        return;

    m_timer->stop();

    action("pause")->setEnabled(false);
    action("stop")->setEnabled(false);
    action("back")->setEnabled(false);
    action("forward")->setEnabled(false);
    action("forwardAlbum")->setEnabled(false);

    if(m_sliderAction->trackPositionSlider()) {
        m_sliderAction->trackPositionSlider()->setValue(0);
        m_sliderAction->trackPositionSlider()->setEnabled(false);
    }

    player()->stop();
    m_playlistInterface->stop();

    m_file = FileHandle::null();

    emit signalStop();
}

void PlayerManager::setVolume(float volume)
{
    if(!player())
        return;

    player()->setVolume(volume);
}

void PlayerManager::seek(int seekTime)
{
    if(!player())
        return;

    player()->seek(seekTime);
}

void PlayerManager::seekPosition(int position)
{
    if(!player())
        return;

    if(!player()->playing() || m_noSeek)
        return;

    slotUpdateTime(position);
    player()->seekPosition(position);

    if(m_sliderAction->trackPositionSlider())
        m_sliderAction->trackPositionSlider()->setValue(position);
}

void PlayerManager::seekForward()
{
    seekPosition(kMin(SliderAction::maxPosition, position() + 10));
}

void PlayerManager::seekBack()
{
    seekPosition(kMax(SliderAction::minPosition, position() - 10));
}

void PlayerManager::playPause()
{
    playing() ? action("pause")->activate() : action("play")->activate();
}

void PlayerManager::forward()
{
    m_playlistInterface->playNext();
    FileHandle file = m_playlistInterface->currentFile();

    if(!file.isNull())
        play(file);
    else
        stop();
}

void PlayerManager::back()
{
    m_playlistInterface->playPrevious();
    FileHandle file = m_playlistInterface->currentFile();

    if(!file.isNull())
        play(file);
    else
        stop();
}

void PlayerManager::volumeUp()
{
    if(!player() || !m_sliderAction || !m_sliderAction->volumeSlider())
        return;

    int volume = m_sliderAction->volumeSlider()->volume() +
        m_sliderAction->volumeSlider()->maxValue() / 25; // 4% up

    slotSetVolume(volume);
    m_sliderAction->volumeSlider()->setVolume(volume);
}

void PlayerManager::volumeDown()
{
    if(!player() || !m_sliderAction || !m_sliderAction->volumeSlider())
        return;

    int volume = m_sliderAction->volumeSlider()->value() -
        m_sliderAction->volumeSlider()->maxValue() / 25; // 4% down

    slotSetVolume(volume);
    m_sliderAction->volumeSlider()->setVolume(volume);
}

void PlayerManager::mute()
{
    if(!player() || !m_sliderAction || !m_sliderAction->volumeSlider())
        return;

    slotSetVolume(m_muted ? m_sliderAction->volumeSlider()->value() : 0);
    m_muted = !m_muted;
}

////////////////////////////////////////////////////////////////////////////////
// private slots
////////////////////////////////////////////////////////////////////////////////

void PlayerManager::slotPollPlay()
{
    if(!player() || !m_playlistInterface)
        return;

    m_noSeek = true;

    if(!player()->playing()) {
        m_timer->stop();

        m_playlistInterface->playNext();
        FileHandle nextFile = m_playlistInterface->currentFile();
        if(!nextFile.isNull())
            play(nextFile);
        else
            stop();
    }
    else if(!m_sliderAction->dragging()) {
        if(m_sliderAction->trackPositionSlider())
            m_sliderAction->trackPositionSlider()->setValue(player()->position());

        if(m_statusLabel) {
            m_statusLabel->setItemTotalTime(player()->totalTime());
            m_statusLabel->setItemCurrentTime(player()->currentTime());
        }
    }

    // This call is done because when the user adds the slider to the toolbar
    // while playback is occuring the volume slider generally defaults to 0,
    // and doesn't get updated to the correct volume.  It might be better to
    // have the SliderAction class fill in the correct volume, but I'm trying
    // to avoid having it depend on PlayerManager since it may not be
    // constructed in time during startup. -mpyne

    if(!m_sliderAction->volumeDragging() && m_sliderAction->volumeSlider())
    {
        int maxV = m_sliderAction->volumeSlider()->maxValue();
        float v = sqrt(sqrt(volume())); // Cancel out exponential scaling

        m_sliderAction->volumeSlider()->blockSignals(true);
        m_sliderAction->volumeSlider()->setVolume((int)((v) * maxV));
        m_sliderAction->volumeSlider()->blockSignals(false);
    }

    // Ok, this is weird stuff, but it works pretty well.  Ordinarily we don't
    // need to check up on our playing time very often, but in the span of the
    // last interval, we want to check a lot -- to figure out that we've hit the
    // end of the song as soon as possible.

    if(player()->playing() &&
       player()->totalTime() > 0 &&
       float(player()->totalTime() - player()->currentTime()) < m_pollInterval * 2)
    {
        m_timer->changeInterval(50);
    }

    m_noSeek = false;
}

void PlayerManager::slotSetOutput(const QString &system)
{
    stop();
    setOutput(system);
    setup();
}

void PlayerManager::setOutput(const QString &system)
{
    delete m_player;
    if(system == i18n("aRts"))
        m_player = createPlayer(ArtsBackend);
    else if(system == i18n("GStreamer"))
        m_player = createPlayer(GStreamerBackend);
    else if(system == i18n("aKode"))
        m_player = createPlayer(AkodeBackend);
}

void PlayerManager::slotSetVolume(int volume)
{
    float scaledVolume;

    if(m_sliderAction->volumeSlider())
        scaledVolume = float(volume) / m_sliderAction->volumeSlider()->maxValue();
    else {
        scaledVolume = float(volume) / 100.0; // Hopefully this is accurate
        scaledVolume = kMin(1.0f, scaledVolume);
    }

    // Perform exponential scaling to counteract the fact that humans perceive
    // volume changes logarithmically.

    scaledVolume *= scaledVolume;
    scaledVolume *= scaledVolume;
    setVolume(scaledVolume); // scaledVolume ^ 4
}

void PlayerManager::slotUpdateTime(int position)
{
    if(!m_statusLabel)
        return;

    float positionFraction = float(position) / SliderAction::maxPosition;
    float totalTime = float(player()->totalTime());
    int seekTime = int(positionFraction * totalTime + 0.5); // "+0.5" for rounding

    m_statusLabel->setItemCurrentTime(seekTime);
}

////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

Player *PlayerManager::player() const
{
    if(!m_player)
        instance()->setup();

    return m_player;
}

void PlayerManager::setup()
{
    // All of the actions required by this class should be listed here.

    if(!action("pause") ||
       !action("stop") ||
       !action("back") ||
       !action("forwardAlbum") ||
       !action("forward") ||
       !action("trackPositionAction"))
    {
        kdWarning(65432) << k_funcinfo << "Could not find all of the required actions." << endl;
        return;
    }

    if(m_setup)
        return;
    m_setup = true;

    // initialize action states

    action("pause")->setEnabled(false);
    action("stop")->setEnabled(false);
    action("back")->setEnabled(false);
    action("forward")->setEnabled(false);
    action("forwardAlbum")->setEnabled(false);

    // setup sliders

    m_sliderAction = action<SliderAction>("trackPositionAction");

    connect(m_sliderAction, SIGNAL(signalPositionChanged(int)),
            this, SLOT(seekPosition(int)));
    connect(m_sliderAction->trackPositionSlider(), SIGNAL(valueChanged(int)),
            this, SLOT(slotUpdateTime(int)));
    connect(m_sliderAction, SIGNAL(signalVolumeChanged(int)),
            this, SLOT(slotSetVolume(int)));

    // Call this method manually to avoid warnings.

    KAction *outputAction = actions()->action("outputSelect");

    if(outputAction) {
        setOutput(static_cast<KSelectAction *>(outputAction)->currentText());
        connect(outputAction, SIGNAL(activated(const QString &)), this, SLOT(slotSetOutput(const QString &)));
    }
    else
        m_player = createPlayer();

    float volume;
    
    if(m_sliderAction->volumeSlider()) {
        volume = 
            float(m_sliderAction->volumeSlider()->volume()) /
            float(m_sliderAction->volumeSlider()->maxValue());
    }
    else
        volume = 1; // Assume user wants full volume

    m_player->setVolume(volume);

    m_timer = new QTimer(this, "play timer");
    connect(m_timer, SIGNAL(timeout()), this, SLOT(slotPollPlay()));
}

QString PlayerManager::randomPlayMode() const
{
    if(action<KToggleAction>("randomPlay")->isChecked())
        return "Random";
    if(action<KToggleAction>("albumRandomPlay")->isChecked())
        return "AlbumRandom";
    return "NoRandom";
}

void PlayerManager::setRandomPlayMode(const QString &randomMode)
{
    if(randomMode.lower() == "random")
        action<KToggleAction>("randomPlay")->setChecked(true);
    if(randomMode.lower() == "albumrandom")
        action<KToggleAction>("albumRandomPlay")->setChecked(true);
    if(randomMode.lower() == "norandom")
        action<KToggleAction>("disableRandomPlay")->setChecked(true);
}

#include "playermanager.moc"

// vim: set et ts=4 sw=4: