playermanager.cpp 16.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/***************************************************************************
    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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <kdebug.h>
17
#include <klocale.h>
18 19

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

22 23
#include <math.h>

24
#include "artsplayer.h"
25
#include "akodeplayer.h"
26
#include "gstreamerplayer.h"
27
#include "playermanager.h"
28
#include "playlistinterface.h"
29
#include "slideraction.h"
30
#include "statuslabel.h"
31
#include "actioncollection.h"
32
#include "collectionlist.h"
Michael Pyne's avatar
Michael Pyne committed
33
#include "coverinfo.h"
34
#include "tag.h"
35

36 37
#include "config.h"

38
using namespace ActionCollection;
39 40 41

PlayerManager *PlayerManager::m_instance = 0;

Stephan Kulow's avatar
Stephan Kulow committed
42
enum PlayerManagerStatus { StatusStopped = -1, StatusPaused = 1, StatusPlaying = 2 };
43

44 45 46 47
////////////////////////////////////////////////////////////////////////////////
// helper functions
////////////////////////////////////////////////////////////////////////////////

48
enum SoundSystem { ArtsBackend = 0, GStreamerBackend = 1, AkodeBackend = 2 };
49 50 51 52 53 54

static Player *createPlayer(int system = ArtsBackend)
{

    Player *p = 0;
    switch(system) {
55
#ifdef HAVE_AKODE
56 57 58
    case AkodeBackend:
        p = new aKodePlayer;
        break;
59
#endif
60
#if HAVE_ARTS
61 62 63
    case ArtsBackend:
        p = new ArtsPlayer;
        break;
64
#endif
65
#if HAVE_GSTREAMER
66 67 68
    case GStreamerBackend:
        p = new GStreamerPlayer;
        break;
69
#endif 
70
    default:
71
#if HAVE_ARTS
72
        p = new ArtsPlayer;
İsmail Dönmez's avatar
 
İsmail Dönmez committed
73
#elif HAVE_GSTREAMER
74
        p = new GStreamerPlayer;
75
#else
İsmail Dönmez's avatar
 
İsmail Dönmez committed
76
        p = new aKodePlayer;
77
#endif
78 79
        break;
    }
80 81 82
    return p;
}

83 84 85 86 87
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////

PlayerManager::PlayerManager() :
Scott Wheeler's avatar
Scott Wheeler committed
88
    Player(),
89
    m_sliderAction(0),
90
    m_playlistInterface(0),
91
    m_statusLabel(0),
92 93
    m_player(0),
    m_timer(0),
94 95
    m_noSeek(false),
    m_muted(false)
96
{
Michael Pyne's avatar
Michael Pyne committed
97 98 99 100 101
// 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();
102 103 104 105
}

PlayerManager::~PlayerManager()
{
106
    delete m_player;
107 108 109 110 111 112 113 114 115 116 117 118 119
}

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

PlayerManager *PlayerManager::instance() // static
{
    if(!m_instance)
        m_instance = new PlayerManager;
    return m_instance;
}

120 121
bool PlayerManager::playing() const
{
122
    if(!player())
123 124
        return false;

125
    return player()->playing();
126 127 128 129
}

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

133
    return player()->paused();
134 135 136 137
}

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

141
    return player()->volume();
142 143
}

144 145 146
int PlayerManager::status() const
{
    if(!player())
147
        return StatusStopped;
148 149

    if(player()->paused())
150
        return StatusPaused;
151 152

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

155 156 157
    return 0;
}

Scott Wheeler's avatar
Scott Wheeler committed
158
int PlayerManager::totalTime() const
159
{
160
    if(!player())
161 162
        return 0;

163
    return player()->totalTime();
164 165
}

Scott Wheeler's avatar
Scott Wheeler committed
166
int PlayerManager::currentTime() const
167
{
168
    if(!player())
169 170
        return 0;

171
    return player()->currentTime();
172 173 174 175
}

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

179
    return player()->position();
180 181
}

182 183 184 185 186 187 188
QStringList PlayerManager::trackProperties()
{
    return FileHandle::properties();
}

QString PlayerManager::trackProperty(const QString &property) const
{
Michael Pyne's avatar
Michael Pyne committed
189
    if(!playing() && !paused())
190 191 192 193 194
        return QString::null;

    return m_file.property(property);
}

Michael Pyne's avatar
Michael Pyne committed
195 196 197 198 199 200 201 202 203 204 205 206 207
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();
}

208 209 210 211 212
FileHandle PlayerManager::playingFile() const
{
    return m_file;
}

213 214 215 216 217
QString PlayerManager::playingString() const
{
    if(!playing())
        return QString::null;

218 219 220 221 222
    QString str = m_file.tag()->artist() + " - " + m_file.tag()->title();
    if(m_file.tag()->artist().isEmpty())
        str = m_file.tag()->title();

    return str;
223 224
}

225
void PlayerManager::setPlaylistInterface(PlaylistInterface *interface)
226 227 228 229
{
    m_playlistInterface = interface;
}

230 231 232 233 234
void PlayerManager::setStatusLabel(StatusLabel *label)
{
    m_statusLabel = label;
}

235 236 237 238 239
KSelectAction *PlayerManager::playerSelectAction(QObject *parent) // static
{
    KSelectAction *action = 0;
    action = new KSelectAction(i18n("&Output To"), 0, parent, "outputSelect");
    QStringList l;
240 241 242 243 244 245

#if HAVE_ARTS
    l.append(i18n("aRts"));
#endif
#if HAVE_GSTREAMER
    l.append(i18n("GStreamer"));
246
#endif
247 248
#ifdef HAVE_AKODE
    l.append(i18n("aKode"));
249
#endif
250

251
    action->setItems(l);
252 253 254
    return action;
}

255 256 257 258
////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////

259
void PlayerManager::play(const FileHandle &file)
260
{
261
    if(!player() || !m_playlistInterface)
262 263
        return;

264 265
    if(file.isNull()) {
        if(player()->paused())
266
            player()->play();
267
        else if(player()->playing()) {
268 269
            if(m_sliderAction->trackPositionSlider())
                m_sliderAction->trackPositionSlider()->setValue(0);
270
            player()->seekPosition(0);
271
        }
272
        else {
273
            m_playlistInterface->playNext();
274
            m_file = m_playlistInterface->currentFile();
275

276
            if(!m_file.isNull())
277
                player()->play(m_file);
278
        }
279
    }
280
    else {
281
        m_file = file;
282
        player()->play(file);
283
    }
284

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

287
    if(!player()->playing()) {
288 289 290
        stop();
        return;
    }
291

292 293 294
    action("pause")->setEnabled(true);
    action("stop")->setEnabled(true);
    action("forward")->setEnabled(true);
295 296
    if(action<KToggleAction>("albumRandomPlay")->isChecked())
        action("forwardAlbum")->setEnabled(true);
297
    action("back")->setEnabled(true);
298

299 300
    if(m_sliderAction->trackPositionSlider())
        m_sliderAction->trackPositionSlider()->setEnabled(true);
301 302

    m_timer->start(m_pollInterval);
303 304

    emit signalPlay();
305 306
}

307 308 309 310 311 312 313 314 315
void PlayerManager::play(const QString &file)
{
    CollectionListItem *item = CollectionList::instance()->lookup(file);
    if(item) {
        Playlist::setPlaying(item);
        play(item->file());
    }
}

Scott Wheeler's avatar
Scott Wheeler committed
316 317 318 319 320
void PlayerManager::play()
{
    play(FileHandle::null());
}

321 322
void PlayerManager::pause()
{
323
    if(!player())
324 325
        return;

326 327 328 329 330 331
    if(player()->paused()) {
        play();
        return;
    }

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

    player()->pause();
335 336

    emit signalPause();
337 338 339 340
}

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

344 345
    m_timer->stop();

346 347 348 349
    action("pause")->setEnabled(false);
    action("stop")->setEnabled(false);
    action("back")->setEnabled(false);
    action("forward")->setEnabled(false);
350
    action("forwardAlbum")->setEnabled(false);
351

352 353 354 355
    if(m_sliderAction->trackPositionSlider()) {
        m_sliderAction->trackPositionSlider()->setValue(0);
        m_sliderAction->trackPositionSlider()->setEnabled(false);
    }
356 357

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

360 361
    m_file = FileHandle::null();

362
    emit signalStop();
363 364
}

Laurent Montel's avatar
Laurent Montel committed
365
void PlayerManager::setVolume(float volume)
366
{
367
    if(!player())
368 369
        return;

370
    player()->setVolume(volume);
371 372
}

Scott Wheeler's avatar
Scott Wheeler committed
373
void PlayerManager::seek(int seekTime)
374
{
375
    if(!player())
376
        return;
377

378
    player()->seek(seekTime);
379 380
}

381
void PlayerManager::seekPosition(int position)
382
{
383 384 385 386
    if(!player())
        return;

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

389 390
    slotUpdateTime(position);
    player()->seekPosition(position);
391 392 393

    if(m_sliderAction->trackPositionSlider())
        m_sliderAction->trackPositionSlider()->setValue(position);
394 395 396 397
}

void PlayerManager::seekForward()
{
398
    seekPosition(kMin(SliderAction::maxPosition, position() + 10));
399 400 401 402
}

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

406 407
void PlayerManager::playPause()
{
408
    playing() ? action("pause")->activate() : action("play")->activate();
409 410
}

411 412
void PlayerManager::forward()
{
413 414
    m_playlistInterface->playNext();
    FileHandle file = m_playlistInterface->currentFile();
415

416 417 418 419 420 421 422 423
    if(!file.isNull())
        play(file);
    else
        stop();
}

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

427 428 429 430 431 432
    if(!file.isNull())
        play(file);
    else
        stop();
}

433 434
void PlayerManager::volumeUp()
{
435
    if(!player() || !m_sliderAction || !m_sliderAction->volumeSlider())
436
        return;
437

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

    slotSetVolume(volume);
442
    m_sliderAction->volumeSlider()->setVolume(volume);
443 444 445 446
}

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

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

    slotSetVolume(volume);
454
    m_sliderAction->volumeSlider()->setVolume(volume);
455 456 457 458
}

void PlayerManager::mute()
{
459
    if(!player() || !m_sliderAction || !m_sliderAction->volumeSlider())
460 461 462 463 464 465
        return;

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

466 467 468
////////////////////////////////////////////////////////////////////////////////
// private slots
////////////////////////////////////////////////////////////////////////////////
469

470
void PlayerManager::slotPollPlay()
471
{
472
    if(!player() || !m_playlistInterface)
473
        return;
474

475
    m_noSeek = true;
476

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

480 481
        m_playlistInterface->playNext();
        FileHandle nextFile = m_playlistInterface->currentFile();
482
        if(!nextFile.isNull())
483
            play(nextFile);
484 485
        else
            stop();
486 487
    }
    else if(!m_sliderAction->dragging()) {
488 489
        if(m_sliderAction->trackPositionSlider())
            m_sliderAction->trackPositionSlider()->setValue(player()->position());
490

491 492 493 494
        if(m_statusLabel) {
            m_statusLabel->setItemTotalTime(player()->totalTime());
            m_statusLabel->setItemCurrentTime(player()->currentTime());
        }
495
    }
496

497 498 499 500 501 502 503 504
    // 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())
505 506
    {
        int maxV = m_sliderAction->volumeSlider()->maxValue();
507
        float v = sqrt(sqrt(volume())); // Cancel out exponential scaling
508 509 510 511 512

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

514 515 516 517
    // 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.
518

519 520 521
    if(player()->playing() &&
       player()->totalTime() > 0 &&
       float(player()->totalTime() - player()->currentTime()) < m_pollInterval * 2)
522 523 524
    {
        m_timer->changeInterval(50);
    }
525

526
    m_noSeek = false;
527 528
}

529
void PlayerManager::slotSetOutput(const QString &system)
530 531
{
    stop();
532 533 534 535 536 537
    setOutput(system);
    setup();
}

void PlayerManager::setOutput(const QString &system)
{
538
    delete m_player;
539
    if(system == i18n("aRts"))
540
        m_player = createPlayer(ArtsBackend);
541
    else if(system == i18n("GStreamer"))
542
        m_player = createPlayer(GStreamerBackend);
543
    else if(system == i18n("aKode"))
544
        m_player = createPlayer(AkodeBackend);
545 546 547 548
}

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

551
    if(m_sliderAction->volumeSlider())
552 553 554 555 556 557 558 559 560 561 562 563
        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
564 565 566 567 568 569 570
}

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

571
    float positionFraction = float(position) / SliderAction::maxPosition;
572
    float totalTime = float(player()->totalTime());
Scott Wheeler's avatar
Scott Wheeler committed
573
    int seekTime = int(positionFraction * totalTime + 0.5); // "+0.5" for rounding
574 575 576 577

    m_statusLabel->setItemCurrentTime(seekTime);
}

578 579 580 581
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

582 583 584 585 586 587 588 589
Player *PlayerManager::player() const
{
    if(!m_player)
        instance()->setup();

    return m_player;
}

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

594 595 596
    if(!action("pause") ||
       !action("stop") ||
       !action("back") ||
597
       !action("forwardAlbum") ||
598 599
       !action("forward") ||
       !action("trackPositionAction"))
600 601 602 603 604
    {
        kdWarning(65432) << k_funcinfo << "Could not find all of the required actions." << endl;
        return;
    }

605 606
    // initialize action states

607 608 609 610
    action("pause")->setEnabled(false);
    action("stop")->setEnabled(false);
    action("back")->setEnabled(false);
    action("forward")->setEnabled(false);
611
    action("forwardAlbum")->setEnabled(false);
612

613 614
    // setup sliders

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

617 618 619 620
    connect(m_sliderAction, SIGNAL(signalPositionChanged(int)),
            this, SLOT(seekPosition(int)));
    connect(m_sliderAction->trackPositionSlider(), SIGNAL(valueChanged(int)),
            this, SLOT(slotUpdateTime(int)));
621
    connect(m_sliderAction, SIGNAL(signalVolumeChanged(int)),
622 623
            this, SLOT(slotSetVolume(int)));

624
    // Call this method manually to avoid warnings.
625

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

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

635 636 637 638 639 640 641 642 643
    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
644 645 646

    m_player->setVolume(volume);

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

Michael Pyne's avatar
Michael Pyne committed
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
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);
}

670
#include "playermanager.moc"
671 672

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