playermanager.cpp 18.2 KB
Newer Older
1 2 3 4
/***************************************************************************
    begin                : Sat Feb 14 2004
    copyright            : (C) 2004 by Scott Wheeler
    email                : wheeler@kde.org
5 6 7 8

    copyright            : (C) 2007 by Matthias Kretz
    email                : kretz@kde.org

9
    copyright            : (C) 2008, 2009 by Michael Pyne
10
    email                : michael.pyne@kdemail.net
11 12 13 14 15 16 17 18 19 20 21
***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

22 23
#include "playermanager.h"

24
#include <kdebug.h>
Matthias Kretz's avatar
Matthias Kretz committed
25
#include <kmessagebox.h>
26
#include <klocale.h>
27 28 29
#include <kactioncollection.h>
#include <kselectaction.h>
#include <ktoggleaction.h>
Andreas Pakulat's avatar
Andreas Pakulat committed
30
#include <kurl.h>
31

32 33 34
#include <Phonon/AudioOutput>
#include <Phonon/MediaObject>
#include <Phonon/VolumeFaderEffect>
35

Laurent Montel's avatar
Laurent Montel committed
36
#include <QPixmap>
37 38
#include <QTimer>

39 40
#include <math.h>

41
#include "playlistinterface.h"
42
#include "playeradaptor.h"
43
#include "slideraction.h"
44
#include "statuslabel.h"
45
#include "actioncollection.h"
46
#include "collectionlist.h"
Michael Pyne's avatar
Michael Pyne committed
47
#include "coverinfo.h"
48
#include "tag.h"
49 50

using namespace ActionCollection;
51

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

54 55 56 57 58
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////

PlayerManager::PlayerManager() :
59
    QObject(),
60
    m_sliderAction(0),
61
    m_playlistInterface(0),
62
    m_statusLabel(0),
63
    m_muted(false),
64
    m_setup(false),
65
    m_crossfadeTracks(true),
66
    m_curOutputPath(0)
67
{
Michael Pyne's avatar
Michael Pyne committed
68 69 70 71 72
// 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();
Laurent Montel's avatar
Port it  
Laurent Montel committed
73
    new PlayerAdaptor( this );
74 75 76 77
}

PlayerManager::~PlayerManager()
{
78 79
    delete m_sliderAction;
    m_sliderAction = 0;
80 81 82 83 84 85
}

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

86 87
bool PlayerManager::playing() const
{
88
    if(!m_setup)
89 90
        return false;

91 92
    Phonon::State state = m_media[m_curOutputPath]->state();
    return (state == Phonon::PlayingState || state == Phonon::BufferingState);
93 94 95 96
}

bool PlayerManager::paused() const
{
97
    if(!m_setup)
98 99
        return false;

100
    return m_media[m_curOutputPath]->state() == Phonon::PausedState;
101 102 103 104
}

float PlayerManager::volume() const
{
105
    if(!m_setup)
106
        return 1.0;
107

108
    return m_output[m_curOutputPath]->volume();
109 110
}

111 112
int PlayerManager::status() const
{
113
    if(!m_setup)
114
        return StatusStopped;
115

116
    if(paused())
117
        return StatusPaused;
118

119
    if(playing())
120
        return StatusPlaying;
121

122 123 124
    return 0;
}

Scott Wheeler's avatar
Scott Wheeler committed
125
int PlayerManager::totalTime() const
126
{
127
    if(!m_setup)
128 129
        return 0;

130
    return m_media[m_curOutputPath]->totalTime() / 1000;
131 132
}

Scott Wheeler's avatar
Scott Wheeler committed
133
int PlayerManager::currentTime() const
134
{
135
    if(!m_setup)
136 137
        return 0;

138
    return m_media[m_curOutputPath]->currentTime() / 1000;
139 140
}

141 142 143 144 145 146 147
QStringList PlayerManager::trackProperties()
{
    return FileHandle::properties();
}

QString PlayerManager::trackProperty(const QString &property) const
{
Michael Pyne's avatar
Michael Pyne committed
148
    if(!playing() && !paused())
149
        return QString();
150 151 152 153

    return m_file.property(property);
}

Michael Pyne's avatar
Michael Pyne committed
154 155 156 157 158
QPixmap PlayerManager::trackCover(const QString &size) const
{
    if(!playing() && !paused())
        return QPixmap();

159
    if(size.toLower() == "small")
Michael Pyne's avatar
Michael Pyne committed
160
        return m_file.coverInfo()->pixmap(CoverInfo::Thumbnail);
161
    if(size.toLower() == "large")
Michael Pyne's avatar
Michael Pyne committed
162 163 164 165 166
        return m_file.coverInfo()->pixmap(CoverInfo::FullSize);

    return QPixmap();
}

167 168 169 170 171
FileHandle PlayerManager::playingFile() const
{
    return m_file;
}

172 173
QString PlayerManager::playingString() const
{
174
    if(!playing() || m_file.isNull())
175
        return QString();
176

177
    return m_file.tag()->playingString();
178 179
}

180
void PlayerManager::setPlaylistInterface(PlaylistInterface *interface)
181 182 183 184
{
    m_playlistInterface = interface;
}

185 186 187 188 189
void PlayerManager::setStatusLabel(StatusLabel *label)
{
    m_statusLabel = label;
}

190 191 192 193
////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////

194
void PlayerManager::play(const FileHandle &file)
195
{
196
    if(!m_setup)
197 198
        setup();

199
    if(!m_media[0] || !m_media[1] || !m_playlistInterface)
200 201
        return;

202 203 204 205
    stopCrossfade();

    // The "currently playing" media object.
    Phonon::MediaObject *mediaObject = m_media[m_curOutputPath];
206

207
    if(file.isNull()) {
208
        if(paused())
209
            mediaObject->play();
210
        else if(playing()) {
211
            mediaObject->seek(0);
212
        }
213
        else {
214
            m_playlistInterface->playNext();
215
            m_file = m_playlistInterface->currentFile();
216

217
            if(!m_file.isNull())
218
            {
219 220
                mediaObject->setCurrentSource(KUrl::fromPath(m_file.absFilePath()));
                mediaObject->play();
221 222

                emit signalItemChanged(m_file);
223
            }
224
        }
225
    }
226
    else {
227
        mediaObject->setCurrentSource(KUrl::fromPath(file.absFilePath()));
228
        mediaObject->play();
229 230 231 232 233

        if(m_file != file)
            emit signalItemChanged(file);

        m_file = file;
234
    }
235

236 237
    // Our state changed handler will perform the follow up actions necessary
    // once we actually start playing.
238 239
}

240 241 242 243 244 245 246 247 248
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
249 250 251 252 253
void PlayerManager::play()
{
    play(FileHandle::null());
}

254 255
void PlayerManager::pause()
{
256
    if(!m_setup)
257 258
        return;

259
    if(paused()) {
260 261 262 263
        play();
        return;
    }

264
    action("pause")->setEnabled(false);
265

266
    m_media[m_curOutputPath]->pause();
267 268

    emit signalPause();
269 270 271 272
}

void PlayerManager::stop()
{
273
    if(!m_setup || !m_playlistInterface)
274 275
        return;

276 277 278 279
    action("pause")->setEnabled(false);
    action("stop")->setEnabled(false);
    action("back")->setEnabled(false);
    action("forward")->setEnabled(false);
280
    action("forwardAlbum")->setEnabled(false);
281

282 283 284 285
    // Fading out playback is for chumps.
    stopCrossfade();
    m_media[0]->stop();
    m_media[1]->stop();
286 287 288 289 290

    if(!m_file.isNull()) {
        m_file = FileHandle::null();
        emit signalItemChanged(m_file);
    }
291 292
}

Laurent Montel's avatar
Laurent Montel committed
293
void PlayerManager::setVolume(float volume)
294
{
295
    if(!m_setup)
296
        setup();
297

298 299
    m_output[0]->setVolume(volume);
    m_output[1]->setVolume(volume);
300 301
}

302
void PlayerManager::seek(int seekTime)
303
{
304
    if(!m_setup || m_media[m_curOutputPath]->currentTime() == seekTime)
305
        return;
306

307 308
    kDebug() << "Stopping crossfade to seek from" << m_media[m_curOutputPath]->currentTime()
             << "to" << seekTime;
309 310
    stopCrossfade();
    m_media[m_curOutputPath]->seek(seekTime);
311 312 313 314
}

void PlayerManager::seekForward()
{
315 316 317 318 319 320
    Phonon::MediaObject *mediaObject = m_media[m_curOutputPath];
    const qint64 total = mediaObject->totalTime();
    const qint64 newtime = mediaObject->currentTime() + total / 100;

    stopCrossfade();
    mediaObject->seek(qMin(total, newtime));
321 322 323 324
}

void PlayerManager::seekBack()
{
325 326 327 328 329 330
    Phonon::MediaObject *mediaObject = m_media[m_curOutputPath];
    const qint64 total = mediaObject->totalTime();
    const qint64 newtime = mediaObject->currentTime() - total / 100;

    stopCrossfade();
    mediaObject->seek(qMax(qint64(0), newtime));
331 332
}

333 334
void PlayerManager::playPause()
{
David Faure's avatar
David Faure committed
335
    playing() ? action("pause")->trigger() : action("play")->trigger();
336 337
}

338 339
void PlayerManager::forward()
{
340 341
    m_playlistInterface->playNext();
    FileHandle file = m_playlistInterface->currentFile();
342

343 344 345 346 347 348 349 350
    if(!file.isNull())
        play(file);
    else
        stop();
}

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

354 355 356 357 358 359
    if(!file.isNull())
        play(file);
    else
        stop();
}

360 361
void PlayerManager::volumeUp()
{
362
    if(!m_setup)
363
        return;
364

365
    setVolume(volume() + 0.04); // 4% up
366 367 368 369
}

void PlayerManager::volumeDown()
{
370
    if(!m_output)
371
        return;
372

373
    setVolume(volume() - 0.04); // 4% down
374 375 376 377
}

void PlayerManager::mute()
{
378
    if(!m_setup)
379 380
        return;

381
    m_output[m_curOutputPath]->setMuted(!m_output[m_curOutputPath]->isMuted());
382 383
}

384 385 386
////////////////////////////////////////////////////////////////////////////////
// private slots
////////////////////////////////////////////////////////////////////////////////
387

388 389
void PlayerManager::slotNeedNextUrl()
{
390
    if(m_file.isNull() || !m_crossfadeTracks)
Matthias Kretz's avatar
Matthias Kretz committed
391
        return;
392

393 394
    m_playlistInterface->playNext();
    FileHandle nextFile = m_playlistInterface->currentFile();
395 396

    if(!nextFile.isNull()) {
397
        m_file = nextFile;
398
        crossfadeToFile(m_file);
399 400 401
    }
}

402 403
void PlayerManager::slotFinished()
{
404 405 406 407
    // It is possible to end up in this function if a file simply fails to play or if the
    // user moves the slider all the way to the end, therefore see if we can keep playing
    // and if we can, do so.  Otherwise, stop.  Note that this slot should
    // only be called by the currently "main" output path (i.e. not from the
408 409 410 411 412 413
    // crossfading one).  However life isn't always so nice apparently, so do some
    // sanity-checking.

    Phonon::MediaObject *mediaObject = qobject_cast<Phonon::MediaObject *>(sender());
    if(mediaObject != m_media[m_curOutputPath])
        return;
414

415 416
    m_playlistInterface->playNext();
    m_file = m_playlistInterface->currentFile();
417

418 419 420 421
    if(m_file.isNull()) {
        stop();
    }
    else {
422
        emit signalItemChanged(m_file);
423 424 425
        m_media[m_curOutputPath]->setCurrentSource(m_file.absFilePath());
        m_media[m_curOutputPath]->play();
    }
426 427
}

428 429 430 431 432
void PlayerManager::slotLength(qint64 msec)
{
    m_statusLabel->setItemTotalTime(msec / 1000);
}

433
void PlayerManager::slotTick(qint64 msec)
434
{
435
    if(!m_setup || !m_playlistInterface)
436
        return;
437

438
    if(m_statusLabel)
439
        m_statusLabel->setItemCurrentTime(msec / 1000);
440 441
}

442
void PlayerManager::slotStateChanged(Phonon::State newstate, Phonon::State oldstate)
Matthias Kretz's avatar
Matthias Kretz committed
443
{
444 445 446 447 448 449
    // Use sender() since either media object may have sent the signal.
    Phonon::MediaObject *mediaObject = qobject_cast<Phonon::MediaObject *>(sender());
    if(!mediaObject)
        return;

    // Handle errors for either media object
450
    if(newstate == Phonon::ErrorState) {
451 452 453
        QString errorMessage =
            i18nc(
              "%1 will be the /path/to/file, %2 will be some string from Phonon describing the error",
Markus Slopianka's avatar
 
Markus Slopianka committed
454 455
              "JuK is unable to play the audio file <filename>%1</filename>"
                "for the following reason: <message>%2</message>",
456
              m_file.absFilePath(),
457
              mediaObject->errorString()
458 459
            );

460
        switch(mediaObject->errorType()) {
461 462 463
            case Phonon::NoError:
                kDebug() << "received a state change to ErrorState but errorType is NoError!?";
                break;
464

Matthias Kretz's avatar
Matthias Kretz committed
465 466
            case Phonon::NormalError:
                forward();
467
                KMessageBox::information(0, errorMessage);
Matthias Kretz's avatar
Matthias Kretz committed
468
                break;
469

Matthias Kretz's avatar
Matthias Kretz committed
470 471
            case Phonon::FatalError:
                stop();
472
                KMessageBox::sorry(0, errorMessage);
Matthias Kretz's avatar
Matthias Kretz committed
473 474 475
                break;
        }
    }
476

477 478 479 480 481
    // Now bail out if we're not dealing with the currently playing media
    // object.

    if(mediaObject != m_media[m_curOutputPath])
        return;
482

483 484 485 486 487 488
    // Handle state changes for the playing media object.
    if(newstate == Phonon::StoppedState && oldstate != Phonon::LoadingState) {
        // If this occurs it should be due to a transitory shift (i.e. playing a different
        // song when one is playing now), since it didn't occur in the error handler.  Just
        // in case we really did abruptly stop, handle that case in a couple of seconds.
        QTimer::singleShot(2000, this, SLOT(slotUpdateGuiIfStopped()));
Michael Pyne's avatar
Michael Pyne committed
489
        emit signalStop();
490
    }
491 492 493 494 495 496 497 498 499 500
    else if(newstate == Phonon::PlayingState) {
        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);

        emit signalPlay();
    }
501 502
}

503 504 505 506 507 508 509 510
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

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

511 512 513
    if(!action("pause") ||
       !action("stop") ||
       !action("back") ||
514
       !action("forwardAlbum") ||
515 516
       !action("forward") ||
       !action("trackPositionAction"))
517
    {
518
        kWarning() << "Could not find all of the required actions.";
519 520 521
        return;
    }

522 523 524 525
    if(m_setup)
        return;
    m_setup = true;

526 527 528 529 530 531
    // We use two audio paths at all times to make cross fading easier (and to also easily
    // support not using cross fading with the same code).  The currently playing audio
    // path is controlled using m_curOutputPath.

    for(int i = 0; i < 2; ++i) {
        m_output[i] = new Phonon::AudioOutput(Phonon::MusicCategory, this);
532

533 534 535
        m_media[i] = new Phonon::MediaObject(this);
        m_audioPath[i] = Phonon::createPath(m_media[i], m_output[i]);
        m_media[i]->setTickInterval(200);
536
        m_media[i]->setPrefinishMark(2000);
537

538 539 540 541 542 543
        // Pre-cache a volume fader object
        m_fader[i] = new Phonon::VolumeFaderEffect(m_media[i]);
        m_audioPath[i].insertEffect(m_fader[i]);
        m_fader[i]->setVolume(1.0f);

        connect(m_media[i], SIGNAL(stateChanged(Phonon::State, Phonon::State)), SLOT(slotStateChanged(Phonon::State, Phonon::State)));
544
        connect(m_media[i], SIGNAL(prefinishMarkReached(qint32)), SLOT(slotNeedNextUrl()));
545 546 547 548
        connect(m_media[i], SIGNAL(totalTimeChanged(qint64)), SLOT(slotLength(qint64)));
        connect(m_media[i], SIGNAL(tick(qint64)), SLOT(slotTick(qint64)));
        connect(m_media[i], SIGNAL(finished()), SLOT(slotFinished()));
    }
549

550 551
    // initialize action states

552 553 554 555
    action("pause")->setEnabled(false);
    action("stop")->setEnabled(false);
    action("back")->setEnabled(false);
    action("forward")->setEnabled(false);
556
    action("forwardAlbum")->setEnabled(false);
557

558
    // setup sliders (a separate slot is used to switch as needed)
559

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

562
    if(m_sliderAction->trackPositionSlider())
563 564
        m_sliderAction->trackPositionSlider()->setMediaObject(m_media[0]);

565
    if(m_sliderAction->volumeSlider())
566
        m_sliderAction->volumeSlider()->setAudioOutput(m_output[0]);
567 568

    QDBusConnection::sessionBus().registerObject("/Player", this);
569 570 571 572 573 574
}

void PlayerManager::slotUpdateSliders()
{
    m_sliderAction->trackPositionSlider()->setMediaObject(m_media[m_curOutputPath]);
    m_sliderAction->volumeSlider()->setAudioOutput(m_output[m_curOutputPath]);
575

576 577
    disconnect(m_media[1 - m_curOutputPath], 0, this, SLOT(slotUpdateSliders()));
    connect(m_media[1 - m_curOutputPath], SIGNAL(finished()), SLOT(slotFinished()));
578 579
}

580
void PlayerManager::slotUpdateGuiIfStopped()
581
{
582 583 584
    if(m_media[0]->state() == Phonon::StoppedState && m_media[1]->state() == Phonon::StoppedState)
        stop();
}
585

586 587 588
void PlayerManager::crossfadeToFile(const FileHandle &newFile)
{
    int nextOutputPath = 1 - m_curOutputPath;
589

590 591 592
    // Don't need this anymore
    disconnect(m_media[m_curOutputPath], SIGNAL(finished()), this, 0);
    connect(m_media[nextOutputPath], SIGNAL(finished()), SLOT(slotFinished()));
593

594 595 596
    // Wait a couple of seconds and switch slider objects.  (We would simply
    // handle this when finished() is emitted but phonon-gst is buggy).
    QTimer::singleShot(2000, this, SLOT(slotUpdateSliders()));
597

598
    m_fader[nextOutputPath]->setVolume(0.0f);
599

600
    emit signalItemChanged(newFile);
601 602
    m_media[nextOutputPath]->setCurrentSource(newFile.absFilePath());
    m_media[nextOutputPath]->play();
603

604 605
    m_fader[m_curOutputPath]->setVolume(1.0f);
    m_fader[m_curOutputPath]->fadeTo(0.0f, 2000);
606

607
    m_fader[nextOutputPath]->fadeTo(1.0f, 2000);
608

609 610
    m_curOutputPath = nextOutputPath;
}
611

612 613 614 615
void PlayerManager::stopCrossfade()
{
    // According to the Phonon docs, setVolume immediately takes effect,
    // which is "good enough for government work" ;)
616

617 618 619
    // 1 - curOutputPath is the other output path...
    m_fader[m_curOutputPath]->setVolume(1.0f);
    m_fader[1 - m_curOutputPath]->setVolume(0.0f);
620

621 622 623 624 625 626 627 628
    // We don't actually need to physically stop crossfading as the playback
    // code will call ->play() when necessary anyways.  If we hit stop()
    // here instead of pause() then we will trick our stateChanged handler
    // into thinking Phonon had a spurious stop and we'll switch tracks
    // unnecessarily.  (This isn't a problem after crossfade completes due to
    // the signals being disconnected).

    m_media[1 - m_curOutputPath]->pause();
629 630
}

Michael Pyne's avatar
Michael Pyne committed
631 632 633 634 635 636 637 638 639
QString PlayerManager::randomPlayMode() const
{
    if(action<KToggleAction>("randomPlay")->isChecked())
        return "Random";
    if(action<KToggleAction>("albumRandomPlay")->isChecked())
        return "AlbumRandom";
    return "NoRandom";
}

640 641 642 643 644
void PlayerManager::setCrossfadeEnabled(bool crossfadeEnabled)
{
    m_crossfadeTracks = crossfadeEnabled;
}

Michael Pyne's avatar
Michael Pyne committed
645 646
void PlayerManager::setRandomPlayMode(const QString &randomMode)
{
647
    if(randomMode.toLower() == "random")
Michael Pyne's avatar
Michael Pyne committed
648
        action<KToggleAction>("randomPlay")->setChecked(true);
649
    if(randomMode.toLower() == "albumrandom")
Michael Pyne's avatar
Michael Pyne committed
650
        action<KToggleAction>("albumRandomPlay")->setChecked(true);
651
    if(randomMode.toLower() == "norandom")
Michael Pyne's avatar
Michael Pyne committed
652 653 654
        action<KToggleAction>("disableRandomPlay")->setChecked(true);
}

655
#include "playermanager.moc"
656

657
// vim: set et sw=4 tw=0 sta: