summaryrefslogtreecommitdiffstats
path: root/plugins/multimedia/symbian/mmf/mediaplayer/s60videoplayersession.cpp
blob: 1cc11f66854391970d4f2def902eabb23b1ce184 (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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "s60videoplayersession.h"
#include "s60mediaplayerservice.h"
#include "s60mediaplayerutils.h"
#include "s60videowidgetcontrol.h"
#include "s60videowidgetdisplay.h"
#include "s60videowindowcontrol.h"
#include "s60videowindowdisplay.h"
#include "s60mmtrace.h"

#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
#include "s60videoeglrenderercontrol.h"
#include "s60nativewindow.h"
#endif

#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QSymbianEvent>
#include <QtGui/QWidget>

#include <coecntrl.h>
#include <coemain.h>    // For CCoeEnv
#include <w32std.h>
#include <mmf/common/mmferrors.h>
#include <mmf/common/mmfcontrollerframeworkbase.h>
#include <mmf/common/mmfvideo.h>
#include <MMFROPCustomCommandConstants.h>
#ifdef HTTP_COOKIES_ENABLED
#include <MMFSessionInfoCustomCommandConstants.h>
#endif

const QString DefaultAudioEndpoint = QLatin1String("Default");
const TUid KHelixUID = {0x101F8514};
_LIT(KSeekable, "Seekable" );
_LIT(KFalse, "0");

// Hard-coding the command to support older versions.
const TInt KMMFROPControllerEnablePausedLoadingStatus = 7;

TVideoRotation videoRotation(qreal angle)
{
    // Convert to clockwise
    angle = 360.0f - angle;
    while (angle >= 360.0f)
        angle -= 360.0f;
    TVideoRotation result = EVideoRotationNone;
    if (angle >= 45.0f && angle < 135.0f)
        result = EVideoRotationClockwise90;
    else if (angle >= 135.0f && angle < 225.0f)
        result = EVideoRotationClockwise180;
    else if (angle >= 225.0f && angle < 315.0f)
        result = EVideoRotationClockwise270;
    return result;
}

S60VideoPlayerEventHandler *S60VideoPlayerEventHandler::m_instance = 0;
QCoreApplication::EventFilter S60VideoPlayerEventHandler::m_eventFilter = 0;
QList<ApplicationFocusObserver *> S60VideoPlayerEventHandler::m_applicationFocusObservers;

S60VideoPlayerEventHandler *S60VideoPlayerEventHandler::instance()
{
    if (!m_instance)
        m_instance = new S60VideoPlayerEventHandler();
    return m_instance;
}

S60VideoPlayerEventHandler::S60VideoPlayerEventHandler()
{
    m_eventFilter = QCoreApplication::instance()->setEventFilter(filterEvent);
}

S60VideoPlayerEventHandler::~S60VideoPlayerEventHandler()
{
    QCoreApplication::instance()->setEventFilter(m_eventFilter);
}

void S60VideoPlayerEventHandler::addApplicationFocusObserver(ApplicationFocusObserver *observer)
{
    m_applicationFocusObservers.append(observer);
}

void S60VideoPlayerEventHandler::removeApplicationFocusObserver(ApplicationFocusObserver *observer)
{
    m_applicationFocusObservers.removeAt(m_applicationFocusObservers.indexOf(observer));
    if (m_applicationFocusObservers.count() == 0) {
        delete m_instance;
        m_instance = 0;
    }
}

bool S60VideoPlayerEventHandler::filterEvent(void *message, long *result)
{
    if (const QSymbianEvent *symbianEvent = reinterpret_cast<const QSymbianEvent*>(message)) {
        switch (symbianEvent->type()) {
        case QSymbianEvent::WindowServerEvent:
            {
                const TWsEvent *wsEvent = symbianEvent->windowServerEvent();
                if (EEventFocusLost == wsEvent->Type() || EEventFocusGained == wsEvent->Type()) {
                    for (QList<ApplicationFocusObserver *>::const_iterator it = m_applicationFocusObservers.constBegin();
                         it != m_applicationFocusObservers.constEnd(); ++it) {
                        if (EEventFocusLost == wsEvent->Type())
                            (*it)->applicationLostFocus();
                        else if (EEventFocusGained == wsEvent->Type())
                            (*it)->applicationGainedFocus();
                    }
                }
            }
            break;
        default:
            break;
        }
    }
    bool ret = false;
    if (m_eventFilter)
        ret = m_eventFilter(message, result);
    return ret;
}

S60VideoPlayerSession::S60VideoPlayerSession(QMediaService *service, S60MediaNetworkAccessControl *object)
    : S60MediaPlayerSession(service)
    , m_accessPointId(0)
    , m_networkAccessControl(object)
    , m_wsSession(&CCoeEnv::Static()->WsSession())
    , m_screenDevice(CCoeEnv::Static()->ScreenDevice())
    , m_service(service)
    , m_player(0)
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
    , m_nativeSurface(TSurfaceId::CreateNullId())
    , m_bufferingWaitingSurface(false)
#else
    , m_dsaActive(false)
    , m_dsaStopped(false)
#endif
    , m_videoOutputControl(0)
    , m_videoOutputDisplay(0)
    , m_displayWindow(0)
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
    , m_audioOutput(0)
#endif
    , m_audioEndpoint(DefaultAudioEndpoint)
    , m_pendingChanges(0)
    , m_backendInitiatedPause(false)
#ifdef HTTP_COOKIES_ENABLED
    , m_destinationPckg(KUidInterfaceMMFControllerSessionInfo)
#endif
{
    TRACE("S60VideoPlayerSession::S60VideoPlayerSession" << qtThisPtr());
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
    QT_TRAP_THROWING(m_player = CVideoPlayerUtility2::NewL(
        *this,
        0,
        EMdaPriorityPreferenceNone
        ));
    m_player->RegisterForVideoLoadingNotification(*this);
    m_dummyWindow = new S60NativeWindow(this);
    connect(this, SIGNAL(nativeSurfaceChanged(TSurfaceId)),
            m_dummyWindow, SLOT(setNativeSurface(TSurfaceId)));
#else
    RWindow *window = 0;
    QRect extentRect;
    QWidget *widget = QApplication::activeWindow();
    if (!widget)
        widget = QApplication::allWidgets().at(0);
    Q_ASSERT(widget);
    WId wid = widget->effectiveWinId();
    if (!wid)
        wid = widget->winId();
    window = static_cast<RWindow *>(wid->DrawableWindow());
    extentRect = QRect(widget->mapToGlobal(widget->pos()), widget->size());
    TRect clipRect = QRect2TRect(extentRect);
    const TRect desktopRect = QRect2TRect(QApplication::desktop()->screenGeometry());
    clipRect.Intersection(desktopRect);
    QT_TRAP_THROWING(m_player = CVideoPlayerUtility::NewL(
            *this,
            0,
            EMdaPriorityPreferenceNone,
            *m_wsSession,
            *m_screenDevice,
            *window,
            QRect2TRect(extentRect),
            clipRect));
    m_dsaActive = true;
    m_player->RegisterForVideoLoadingNotification(*this);
#endif // VIDEOOUTPUT_GRAPHICS_SURFACES
    S60VideoPlayerEventHandler::instance()->addApplicationFocusObserver(this);
}

S60VideoPlayerSession::~S60VideoPlayerSession()
{
    TRACE("S60VideoPlayerSession::~S60VideoPlayerSession" << qtThisPtr());
    S60VideoPlayerEventHandler::instance()->removeApplicationFocusObserver(this);
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
    if (m_audioOutput)
        m_audioOutput->UnregisterObserver(*this);
    delete m_audioOutput;
#endif
    m_player->Close();
    delete m_player;
}

void S60VideoPlayerSession::applicationGainedFocus()
{
    TRACE("S60VideoPlayerSession::applicationGainedFocus" << qtThisPtr());
    if (m_backendInitiatedPause) {
        m_backendInitiatedPause = false;
        play();
    }
    if (QMediaPlayer::PausedState == state()) {
       TRAPD(err, m_player->RefreshFrameL());
       setError(err);
    }
}

void S60VideoPlayerSession::applicationLostFocus()
{
    TRACE("S60VideoPlayerSession::applicationLostFocus" << qtThisPtr());
    if (QMediaPlayer::PlayingState == state()) {
        if (!m_isaudiostream) {
            m_backendInitiatedPause = true;
            pause();
        }
    }
}

void S60VideoPlayerSession::doLoadL(const TDesC &path)
{
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
    // m_audioOutput needs to be reinitialized after MapcInitComplete
    if (m_audioOutput)
        m_audioOutput->UnregisterObserver(*this);
    delete m_audioOutput;
    m_audioOutput = 0;
#endif
    m_player->OpenFileL(path, KHelixUID);
}

void S60VideoPlayerSession::setPlaybackRate(qreal rate)
{
#ifdef PLAY_RATE_NOT_SUPPORTED
    TRACE("S60VideoPlayerSession::setPlaybackRate" << qtThisPtr()
          << "rate" << rate << "not supported");
#else
    TRACE("S60VideoPlayerSession::setPlaybackRate" << qtThisPtr() << "rate" << rate);
    TRAPD(err, m_player->SetPlayVelocityL((TInt)(rate*100)));
    if (KErrNone == err)
        emit playbackRateChanged(rate);
    else
        setError(err);
#endif
}

void S60VideoPlayerSession::doLoadUrlL(const TDesC &path)
{
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
    // m_audioOutput needs to be reinitialized after MapcInitComplete
    if (m_audioOutput)
        m_audioOutput->UnregisterObserver(*this);
    delete m_audioOutput;
    m_audioOutput = 0;
#endif
    m_accessPointId = m_networkAccessControl->accessPointId();
    m_player->OpenUrlL(path, m_accessPointId, KNullDesC8, KHelixUID);
}

int S60VideoPlayerSession::doGetBufferStatusL() const
{
    int progress = 0;
    m_player->GetVideoLoadingProgressL(progress);
    return progress;
}

qint64 S60VideoPlayerSession::doGetDurationL() const
{
    return m_player->DurationL().Int64() / qint64(1000);
}

void S60VideoPlayerSession::setVideoRenderer(QObject *videoOutput)
{
    TRACE("S60VideoPlayerSession::setVideoRenderer" << qtThisPtr()
          << "output" << videoOutput);
    if (videoOutput != m_videoOutputControl) {
        if (m_videoOutputControl) {
            disconnect(m_videoOutputControl);
            m_videoOutputControl->disconnect(this);
        }
        if (m_videoOutputDisplay) {
            m_videoOutputDisplay->setHasContent(false);
            disconnect(m_videoOutputDisplay);
            m_videoOutputDisplay->disconnect(this);
            m_videoOutputDisplay = 0;
        }
        if (videoOutput) {
            TRACE("S60VideoPlayerSession::setVideoRenderer output" << videoOutput);
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
            if (S60VideoEglRendererControl *control = qobject_cast<S60VideoEglRendererControl *>(videoOutput)) {
                control->setNativeSurface(m_nativeSurface);
                control->setNativeSize(m_nativeSize);
                connect(this, SIGNAL(nativeSurfaceChanged(TSurfaceId)), control, SLOT(setNativeSurface(TSurfaceId)));
                connect(this, SIGNAL(nativeSizeChanged(QSize)), control, SLOT(setNativeSize(QSize)));
            }
            else
#endif
            if (S60VideoWidgetControl *control = qobject_cast<S60VideoWidgetControl *>(videoOutput))
                m_videoOutputDisplay = control->display();
            else if (S60VideoWindowControl *control = qobject_cast<S60VideoWindowControl *>(videoOutput))
                m_videoOutputDisplay = control->display();
            TRACE("S60VideoPlayerSession::setVideoRenderer display" << m_videoOutputDisplay);
            if (m_videoOutputDisplay) {
                m_videoOutputDisplay->setHasContent(QMediaPlayer::PlayingState == state());
                m_videoOutputDisplay->setNativeSize(m_nativeSize);
                connect(this, SIGNAL(nativeSizeChanged(QSize)), m_videoOutputDisplay, SLOT(setNativeSize(QSize)));
                connect(m_videoOutputDisplay, SIGNAL(windowHandleChanged(RWindow *)), this, SLOT(windowHandleChanged()));
                connect(m_videoOutputDisplay, SIGNAL(displayRectChanged(QRect, QRect)), this, SLOT(displayRectChanged()));
                connect(m_videoOutputDisplay, SIGNAL(aspectRatioModeChanged(Qt::AspectRatioMode)), this, SLOT(aspectRatioChanged()));
                connect(m_videoOutputDisplay, SIGNAL(rotationChanged(qreal)), this, SLOT(rotationChanged()));
#ifndef VIDEOOUTPUT_GRAPHICS_SURFACES
                connect(m_videoOutputDisplay, SIGNAL(beginVideoWindowNativePaint()), this, SLOT(suspendDirectScreenAccess()));
                connect(m_videoOutputDisplay, SIGNAL(endVideoWindowNativePaint()), this, SLOT(resumeDirectScreenAccess()));
#endif
            }
        }
        m_videoOutputControl = videoOutput;
        windowHandleChanged();
    }
}

void S60VideoPlayerSession::applyPendingChanges(bool force)
{
    TRACE("S60VideoPlayerSession::applyPendingChanges" << qtThisPtr()
          << "mediaStatus" << mediaStatus() << "force" << force
          << "pendingChanges" << m_pendingChanges);

    if (   force
        || QMediaPlayer::LoadedMedia == mediaStatus()
        || QMediaPlayer::StalledMedia == mediaStatus()
        || QMediaPlayer::BufferingMedia == mediaStatus()
        || QMediaPlayer::BufferedMedia == mediaStatus()
        || QMediaPlayer::EndOfMedia == mediaStatus()) {
        int error = KErrNone;
        RWindow *const window = m_videoOutputDisplay ? m_videoOutputDisplay->windowHandle() : 0;
        const QRect extentRect = m_videoOutputDisplay ? m_videoOutputDisplay->extentRect() : QRect();
        const QRect clipRect = m_videoOutputDisplay ? m_videoOutputDisplay->clipRect() : QRect();
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
        if (m_pendingChanges & WindowHandle) {
            if (window && window != m_displayWindow ) {
                TRAP(error, m_player->AddDisplayWindowL(*m_wsSession, *m_screenDevice,
                                                        *window,
                                                        QRect2TRect(extentRect),
                                                        QRect2TRect(clipRect)));
            }
            if (m_displayWindow && m_displayWindow != window && KErrNone == error){
                m_player->RemoveDisplayWindow(*m_displayWindow);
                m_displayWindow = 0;
            }
            if (KErrNone == error && window )
                m_displayWindow = window;
            m_pendingChanges = ScaleFactors;
        }
        if (KErrNone == error && (m_pendingChanges & DisplayRect) && m_displayWindow) {
            TRAP(error, m_player->SetVideoExtentL(*m_displayWindow, QRect2TRect(extentRect)));
            if (KErrNone == error)
                TRAP(error, m_player->SetWindowClipRectL(*m_displayWindow, QRect2TRect(clipRect)));
            m_pendingChanges ^= DisplayRect;
            m_pendingChanges |= ScaleFactors;
        }
#else
        if (m_pendingChanges & WindowHandle || m_pendingChanges & DisplayRect) {
            if (window) {
               TRAP(error, m_player->SetDisplayWindowL(*m_wsSession, *m_screenDevice,
                                                       *window,
                                                       QRect2TRect(extentRect),
                                                       QRect2TRect(clipRect)));
               if (KErrNone == error)
                   m_displayWindow = window;
            }
            m_dsaActive = (KErrNone == error);
            m_dsaStopped = false;
            m_pendingChanges = ScaleFactors;
        }

#endif // VIDEOOUTPUT_GRAPHICS_SURFACES
        if (KErrNone == error && (m_pendingChanges & ScaleFactors) && m_displayWindow && m_videoOutputDisplay) {
            const TVideoRotation rotation = videoRotation(m_videoOutputDisplay->rotation());
            const bool swap = (rotation == EVideoRotationClockwise90 || rotation == EVideoRotationClockwise270);
            const QSize extentSize = swap ? QSize(extentRect.height(), extentRect.width()) : extentRect.size();
            QSize scaled = m_nativeSize;
            if (m_videoOutputDisplay->aspectRatioMode() == Qt::IgnoreAspectRatio)
                scaled.scale(extentSize, Qt::IgnoreAspectRatio);
            else if (m_videoOutputDisplay->aspectRatioMode() == Qt::KeepAspectRatio)
                scaled.scale(extentSize, Qt::KeepAspectRatio);
            else if (m_videoOutputDisplay->aspectRatioMode() == Qt::KeepAspectRatioByExpanding)
                scaled.scale(extentSize, Qt::KeepAspectRatioByExpanding);
            const qreal width = qreal(scaled.width()) / qreal(m_nativeSize.width()) * qreal(100);
            const qreal height = qreal(scaled.height()) / qreal(m_nativeSize.height()) * qreal(100);
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
            TRAP(error, m_player->SetScaleFactorL(*m_displayWindow, width, height));
#else
            static const TBool antialias = ETrue;
            TRAP(error, m_player->SetScaleFactorL(width, height, antialias));
#endif // VIDEOOUTPUT_GRAPHICS_SURFACES
            m_pendingChanges ^= ScaleFactors;
        }
        if (KErrNone == error && (m_pendingChanges && Rotation) && m_displayWindow && m_videoOutputDisplay) {
            const TVideoRotation rotation = videoRotation(m_videoOutputDisplay->rotation());
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
            TRAP(error, m_player->SetRotationL(*m_displayWindow, rotation));
#else
            TRAP(error, m_player->SetRotationL(rotation));
#endif // VIDEOOUTPUT_GRAPHICS_SURFACES
            m_pendingChanges ^= Rotation;
        }
        setError(error);
    }
}

bool S60VideoPlayerSession::isVideoAvailable()
{
#ifdef PRE_S60_50_PLATFORM
    return true; // this is not supported in pre 5th platforms
#else
    if ( mediaStatus() == QMediaPlayer::LoadingMedia
        || mediaStatus() == QMediaPlayer::UnknownMediaStatus
        || mediaStatus() == QMediaPlayer::NoMedia
        || (mediaStatus() == QMediaPlayer::StalledMedia && state() == QMediaPlayer::StoppedState)
        || mediaStatus() == QMediaPlayer::InvalidMedia)
        return false;

    if (m_player) {
        bool videoAvailable = false;
        TRAPD(err, videoAvailable = m_player->VideoEnabledL());
        setError(err);
        return videoAvailable;
    } else {
        return false;
    }
#endif

}

bool S60VideoPlayerSession::isAudioAvailable()
{
    if ( mediaStatus() == QMediaPlayer::LoadingMedia
        || mediaStatus() == QMediaPlayer::UnknownMediaStatus
        || mediaStatus() == QMediaPlayer::NoMedia
        || (mediaStatus() == QMediaPlayer::StalledMedia && state() == QMediaPlayer::StoppedState)
        || mediaStatus() == QMediaPlayer::InvalidMedia)
         return false;

    if (m_player) {
        bool audioAvailable = false;
        TRAPD(err, audioAvailable = m_player->AudioEnabledL());
        setError(err);
        return audioAvailable;
    } else {
        return false;
    }
}

void S60VideoPlayerSession::doPlay()
{
    m_player->Play();
    if (m_videoOutputDisplay)
        m_videoOutputDisplay->setHasContent(true);
}

void S60VideoPlayerSession::doPauseL()
{
    m_player->PauseL();
}

void S60VideoPlayerSession::doStop()
{
    if (m_stream)
        m_networkAccessControl->resetIndex();
    if (m_videoOutputDisplay)
        m_videoOutputDisplay->setHasContent(false);
    m_player->Stop();
}

void S60VideoPlayerSession::doClose()
{
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
    if (m_audioOutput) {
        m_audioOutput->UnregisterObserver(*this);
        delete m_audioOutput;
        m_audioOutput = 0;
    }
#endif
    m_player->Close();

#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
    m_nativeSurface = TSurfaceId::CreateNullId();
#endif

    // Close will remove the window handle from m_player, so mark
    // it in pending changes.
    m_pendingChanges |= WindowHandle;
}

qint64 S60VideoPlayerSession::doGetPositionL() const
{
    return m_player->PositionL().Int64() / qint64(1000);
}

void S60VideoPlayerSession::doSetPositionL(qint64 microSeconds)
{
    m_player->SetPositionL(TTimeIntervalMicroSeconds(microSeconds));
}

void S60VideoPlayerSession::doSetVolumeL(int volume)
{
    m_player->SetVolumeL(volume * m_player->MaxVolume() / 100);
}

void S60VideoPlayerSession::MvpuoOpenComplete(TInt aError)
{
    TRACE("S60VideoPlayerSession::MvpuoOpenComplete" << qtThisPtr()
          << "error" << aError);
    setError(aError);
#ifdef HTTP_COOKIES_ENABLED
    if (KErrNone == aError) {
        TInt err(KErrNone);
        const QByteArray userAgentString("User-Agent");
        TInt uasize = m_source.canonicalRequest().rawHeader(userAgentString).size();
        TPtrC8 userAgent((const unsigned char*)(m_source.canonicalRequest().rawHeader(userAgentString).constData()), uasize);
        if (userAgent.Length()) {
            err = m_player->CustomCommandSync(m_destinationPckg, EMMFSetSessionInfo, _L8("User-Agent"), userAgent);
            if (err != KErrNone) {
                setError(err);
                return;
            }
        }
        const QByteArray refererString("Referer");
        TInt refsize = m_source.canonicalRequest().rawHeader(refererString).size();
        TPtrC8 referer((const unsigned char*)m_source.canonicalRequest().rawHeader(refererString).constData(),refsize);
        if (referer.Length()) {
            err = m_player->CustomCommandSync(m_destinationPckg, EMMFSetSessionInfo, _L8("Referer"), referer);
            if (err != KErrNone) {
                setError(err);
                return;
            }
        }
        const QByteArray cookieString("Cookie");
        TInt cksize = m_source.canonicalRequest().rawHeader(cookieString).size();
        TPtrC8 cookie((const unsigned char*)m_source.canonicalRequest().rawHeader(cookieString).constData(),cksize);
        if (cookie.Length()) {
            err = m_player->CustomCommandSync(m_destinationPckg, EMMFSetSessionInfo, _L8("Cookie"), cookie);
            if (err != KErrNone) {
                setError(err);
                return;
            }
        }
        m_player->Prepare();
    }
#else
    if (KErrNone == aError)
        m_player->Prepare();
#endif
    const TMMFMessageDestinationPckg dest(KUidInterfaceMMFROPController);
    TRAP_IGNORE(m_player->CustomCommandSync(dest, KMMFROPControllerEnablePausedLoadingStatus, KNullDesC8, KNullDesC8));
}

void S60VideoPlayerSession::MvpuoPrepareComplete(TInt aError)
{
    TRACE("S60VideoPlayerSession::MvpuoPrepareComplete" << qtThisPtr()
          << "error" << aError);
    if (KErrNone == aError && m_stream)
        emit accessPointChanged(m_accessPointId);
    if (KErrCouldNotConnect == aError && !(m_networkAccessControl->isLastAccessPoint())) {
        load(m_source);
        return;
    }
    TInt error = aError;
    if (KErrNone == error || KErrMMPartialPlayback == error) {
        TSize originalSize;
        TRAP(error, m_player->VideoFrameSizeL(originalSize));
        if (KErrNone == error) {
            m_nativeSize = QSize(originalSize.iWidth, originalSize.iHeight);
            emit nativeSizeChanged(m_nativeSize);
            m_pendingChanges |= ScaleFactors;
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
            Q_ASSERT(!m_audioOutput);
            TRAP(error, m_audioOutput = CAudioOutput::NewL(*m_player));
            if (KErrNone == error) {
                TRAP(error, m_audioOutput->RegisterObserverL(*this));
                if (KErrNone == error)
                    setActiveEndpoint(m_audioEndpoint);
            }
#endif
        }
        if (KErrNone == error) {
            if (m_player->VideoFormatMimeType().Length() == 0) {
                m_isaudiostream = true;
                m_backendInitiatedPause = false;
                play();
            } else {
                m_isaudiostream = false;
            }
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
            // Register for callbacks via MMMFSurfaceEventHandler
            TRAP(error, m_player->AddDisplayL(*m_wsSession,
                                              m_screenDevice->GetScreenNumber(),
                                              *this));
            if (!error)
                // When switching from the 'direct' video rendering path (which
                // sets the video surface as the background of a native window)
                // to the EGL rendering path (which uses EGL endpoint to extract
                // video frames as EGL images), the native window is first removed,
                // then the EGL endpoint is created.  In order to prevent the MMF
                // from destroying the video surface when the window is removed,
                // we must also provide a dummy, non-displayed window handle.
                TRAP(error, m_player->AddDisplayWindowL(*m_wsSession, *m_screenDevice,
                                                        *m_dummyWindow->windowHandle(),
                                                        TRect(), TRect()));
#endif
                applyPendingChanges(true); // force apply even though state is not Loaded
            if (KErrNone == error && KErrNone == this->error()) // applyPendingChanges() can call setError()
                loaded();
        }
    } else {
        setError(error);
    }
}

void S60VideoPlayerSession::MvpuoFrameReady(CFbsBitmap &aFrame, TInt aError)
{
    Q_UNUSED(aFrame);
    Q_UNUSED(aError);
}

void S60VideoPlayerSession::MvpuoPlayComplete(TInt aError)
{
    TRACE("S60VideoPlayerSession::MvpuoPlayComplete" << qtThisPtr()
          << "error" << aError);
    if (m_stream)
        m_networkAccessControl->resetIndex();
    if (aError != KErrNone) {
        setError(aError);
        doClose();
    } else {
        endOfMedia();
    }
}

void S60VideoPlayerSession::MvpuoEvent(const TMMFEvent &aEvent)
{
    TRACE("S60VideoPlayerSession::MvpuoEvent" << qtThisPtr()
          << "type" << (void*)aEvent.iEventType.iUid
          << "error" << aEvent.iErrorCode);
    if (aEvent.iEventType == KMMFEventCategoryVideoPlayerGeneralError) {
        if (aEvent.iErrorCode == KErrMMVideoDevice) {
            // MMF sends this event when video playback is paused due to foreground lost event
            applicationLostFocus();
        } else {
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
            // Ignore KErrNotFound when loading for null surface
            if (aEvent.iErrorCode == KErrNotFound && m_bufferingWaitingSurface)
                return;
#endif
            setError(aEvent.iErrorCode);
            doClose();
        }
    }
}

#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
void S60VideoPlayerSession::MmsehSurfaceCreated(TInt aDisplayId, const TSurfaceId& aId,
                                                const TRect& aCropRect,
                                                TVideoAspectRatio aAspectRatio)
{
    TRACE("S60VideoPlayerSession::MmsehSurfaceCreated" << qtThisPtr() << "id" << (void*)aId.iInternal[3]);
    Q_UNUSED(aCropRect)
    Q_UNUSED(aAspectRatio)
    Q_ASSERT(m_nativeSurface.IsNull());
    m_nativeSurface = aId;
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
    if (m_bufferingWaitingSurface) {
        // Loading had started before surface, start buffering now
        m_bufferingWaitingSurface = false;
        buffering();
    }
#endif
    emit nativeSurfaceChanged(m_nativeSurface);
}

void S60VideoPlayerSession::MmsehSurfaceParametersChanged(const TSurfaceId& aId,
                                                          const TRect& aCropRect,
                                                          TVideoAspectRatio aAspectRatio)
{
    TRACE("S60VideoPlayerSession::MmsehSurfaceParametersChanged" << qtThisPtr() << "id" << (void*)aId.iInternal[3]);
    Q_UNUSED(aId)
    Q_UNUSED(aCropRect)
    Q_UNUSED(aAspectRatio)
}

void S60VideoPlayerSession::MmsehRemoveSurface(const TSurfaceId& aId)
{
    TRACE("S60VideoPlayerSession::MmsehRemoveSurface" << qtThisPtr() << "id" << (void*)aId.iInternal[3]);
    if (aId == m_nativeSurface) {
        m_nativeSurface = TSurfaceId::CreateNullId();
        emit nativeSurfaceChanged(m_nativeSurface);
    }
}
#endif // VIDEOOUTPUT_GRAPHICS_SURFACES

void S60VideoPlayerSession::updateMetaDataEntriesL()
{
    metaDataEntries().clear();
    int numberOfMetaDataEntries = 0;
    numberOfMetaDataEntries = m_player->NumberOfMetaDataEntriesL();
    for (int i=0; i<numberOfMetaDataEntries; ++i) {
        CMMFMetaDataEntry *entry = 0;
        entry = m_player->MetaDataEntryL(i);
        metaDataEntries().insert(TDesC2QString(entry->Name()), TDesC2QString(entry->Value()));
        delete entry;
    }
    emit metaDataChanged();
}

void S60VideoPlayerSession::windowHandleChanged()
{
    TRACE("S60VideoPlayerSession::windowHandleChanged" << qtThisPtr());
    m_pendingChanges |= WindowHandle;
    applyPendingChanges();
}

void S60VideoPlayerSession::displayRectChanged()
{
    TRACE("S60VideoPlayerSession::displayRectChanged" << qtThisPtr());
    m_pendingChanges |= DisplayRect;
    applyPendingChanges();
}

void S60VideoPlayerSession::aspectRatioChanged()
{
    TRACE("S60VideoPlayerSession::aspectRatioChanged" << qtThisPtr());
    m_pendingChanges |= ScaleFactors;
    applyPendingChanges();
}

void S60VideoPlayerSession::rotationChanged()
{
    TRACE("S60VideoPlayerSession::rotationChanged" << qtThisPtr());
    m_pendingChanges |= ScaleFactors;
    m_pendingChanges |= Rotation;
    applyPendingChanges();
}

#ifndef VIDEOOUTPUT_GRAPHICS_SURFACES
void S60VideoPlayerSession::suspendDirectScreenAccess()
{
    TRACE("S60VideoPlayerSession::suspendDirectScreenAccess" << qtThisPtr());
    m_dsaStopped = stopDirectScreenAccess();
}

void S60VideoPlayerSession::resumeDirectScreenAccess()
{
    TRACE("S60VideoPlayerSession::resumeDirectScreenAccess" << qtThisPtr());
    if (!m_dsaStopped)
        return;
    startDirectScreenAccess();
    m_dsaStopped = false;
}

void S60VideoPlayerSession::startDirectScreenAccess()
{
    TRACE("S60VideoPlayerSession::startDirectScreenAccess" << qtThisPtr());
    if (m_dsaActive)
        return;
    TRAPD(err, m_player->StartDirectScreenAccessL());
    if (err == KErrNone)
        m_dsaActive = true;
    setError(err);
}

bool S60VideoPlayerSession::stopDirectScreenAccess()
{
    TRACE("S60VideoPlayerSession::stopDirectScreenAccess" << qtThisPtr());
    if (!m_dsaActive)
        return false;
    TRAPD(err, m_player->StopDirectScreenAccessL());
    if (err == KErrNone)
        m_dsaActive = false;
    setError(err);
    return true;
}
#endif

void S60VideoPlayerSession::MvloLoadingStarted()
{
    TRACE("S60VideoPlayerSession::MvloLoadingStarted" << qtThisPtr());
#ifdef VIDEOOUTPUT_GRAPHICS_SURFACES
    if (m_nativeSurface.IsNull()) {
        // Wait for surface before starting buffering
        m_bufferingWaitingSurface = true;
    }
    else
#endif
    buffering();
}

void S60VideoPlayerSession::MvloLoadingComplete()
{
    TRACE("S60VideoPlayerSession::MvloLoadingComplete" << qtThisPtr());
    buffered();
}

void S60VideoPlayerSession::doSetAudioEndpoint(const QString& audioEndpoint)
{
    m_audioEndpoint = audioEndpoint;
}

QString S60VideoPlayerSession::activeEndpoint() const
{
    QString outputName = m_audioEndpoint;
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
    if (m_audioOutput) {
        CAudioOutput::TAudioOutputPreference output = m_audioOutput->AudioOutput();
        outputName = qStringFromTAudioOutputPreference(output);
    }
#endif
    return outputName;
}

QString S60VideoPlayerSession::defaultEndpoint() const
{
    QString outputName = DefaultAudioEndpoint;
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
    if (m_audioOutput) {
        CAudioOutput::TAudioOutputPreference output = m_audioOutput->DefaultAudioOutput();
        outputName = qStringFromTAudioOutputPreference(output);
    }
#endif
    return outputName;
}

void S60VideoPlayerSession::setActiveEndpoint(const QString& name)
{
    TRACE("S60VideoPlayerSession::setActiveEndpoint" << qtThisPtr() << "name" << name);
#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
    CAudioOutput::TAudioOutputPreference output = CAudioOutput::ENoPreference;
    if (name == DefaultAudioEndpoint)
        output = CAudioOutput::ENoPreference;
    else if (name == QString("All"))
        output = CAudioOutput::EAll;
    else if (name == QString("None"))
        output = CAudioOutput::ENoOutput;
    else if (name == QString("Earphone"))
        output = CAudioOutput::EPrivate;
    else if (name == QString("Speaker"))
        output = CAudioOutput::EPublic;
    if (m_audioOutput) {
        TRAPD(err, m_audioOutput->SetAudioOutputL(output));
        setError(err);
    }
#endif
}

#ifdef HAS_AUDIOROUTING_IN_VIDEOPLAYER
void S60VideoPlayerSession::DefaultAudioOutputChanged(CAudioOutput& aAudioOutput,
                                                      CAudioOutput::TAudioOutputPreference aNewDefault)
{
    TRACE("S60VideoPlayerSession::DefaultAudioOutputChanged" << qtThisPtr()
          << "newDefault" << aNewDefault);
    // Emit already implemented in setActiveEndpoint function
    Q_UNUSED(aAudioOutput)
    Q_UNUSED(aNewDefault)
}

QString S60VideoPlayerSession::qStringFromTAudioOutputPreference(CAudioOutput::TAudioOutputPreference output) const
{
    if (output == CAudioOutput::ENoPreference)
        return QString("Default");
    else if (output == CAudioOutput::EAll)
        return QString("All");
    else if (output == CAudioOutput::ENoOutput)
        return QString("None");
    else if (output == CAudioOutput::EPrivate)
        return QString("Earphone");
    else if (output == CAudioOutput::EPublic)
        return QString("Speaker");
    return QString("Default");
}
#endif //HAS_AUDIOROUTING_IN_VIDEOPLAYER)

bool S60VideoPlayerSession::getIsSeekable() const
{
    bool seekable = ETrue;
    int numberOfMetaDataEntries = 0;
    TRAPD(err, numberOfMetaDataEntries = m_player->NumberOfMetaDataEntriesL());
    if (err)
        return seekable;
    for (int i=0; i<numberOfMetaDataEntries; ++i) {
        CMMFMetaDataEntry *entry = 0;
        TRAP(err, entry = m_player->MetaDataEntryL(i));
        if (err)
            return seekable;
        if (!entry->Name().Compare(KSeekable)) {
            if (!entry->Value().Compare(KFalse))
                seekable = EFalse;
            break;
        }
    }
    return seekable;
}