summaryrefslogtreecommitdiff
path: root/src/plugins/blackberry/bbmediaplayercontrol.cpp
blob: 166009826eb44a6d658413decc99dcc72e6f62ba (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
/****************************************************************************
**
** Copyright (C) 2012 Research In Motion
** Contact: http://www.qt-project.org/
**
** This file is part of the Qt Toolkit.
**
** $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 "bbmediaplayercontrol.h"
#include "bbvideowindowcontrol.h"
#include "bbutil.h"
#include <QtCore/qabstracteventdispatcher.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qdir.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/quuid.h>
#include <mm/renderer.h>
#include <bps/mmrenderer.h>
#include <bps/screen.h>
#include <errno.h>
#include <sys/strm.h>
#include <sys/stat.h>

//#define QBBMEDIA_DEBUG

#ifdef QBBMEDIA_DEBUG
#define qBbMediaDebug qDebug
#else
#define qBbMediaDebug QT_NO_QDEBUG_MACRO
#endif

QT_BEGIN_NAMESPACE

static int idCounter = 0;

BbMediaPlayerControl::BbMediaPlayerControl(QObject *parent)
    : QMediaPlayerControl(parent),
      m_connection(0),
      m_context(0),
      m_audioId(-1),
      m_state(QMediaPlayer::StoppedState),
      m_volume(100),
      m_muted(false),
      m_rate(1),
      m_id(-1),
      m_eventMonitor(0),
      m_position(0),
      m_mediaStatus(QMediaPlayer::NoMedia),
      m_playAfterMediaLoaded(false),
      m_inputAttached(false),
      m_stopEventsToIgnore(0),
      m_bufferStatus(0)
{
    m_loadingTimer.setSingleShot(true);
    m_loadingTimer.setInterval(0);
    connect(&m_loadingTimer, SIGNAL(timeout()), this, SLOT(continueLoadMedia()));
    QCoreApplication::eventDispatcher()->installNativeEventFilter(this);
    openConnection();
}

BbMediaPlayerControl::~BbMediaPlayerControl()
{
    stop();
    detach();
    closeConnection();
    QCoreApplication::eventDispatcher()->removeNativeEventFilter(this);
}

void BbMediaPlayerControl::openConnection()
{
    m_connection = mmr_connect(NULL);
    if (!m_connection) {
        emitPError("Unable to connect to the multimedia renderer");
        return;
    }

    m_id = idCounter++;
    m_contextName = QString("BbMediaPlayerControl_%1_%2").arg(m_id)
                                                         .arg(QCoreApplication::applicationPid());
    m_context = mmr_context_create(m_connection, m_contextName.toLatin1(),
                                   0, S_IRWXU|S_IRWXG|S_IRWXO);
    if (!m_context) {
        emitPError("Unable to create context");
        closeConnection();
        return;
    }

    m_eventMonitor = mmrenderer_request_events(m_contextName.toLatin1(), 0, m_id);
    if (!m_eventMonitor) {
        qBbMediaDebug() << "Unable to request multimedia events";
        emit error(0, "Unable to request multimedia events");
    }
}

void BbMediaPlayerControl::closeConnection()
{
    if (m_eventMonitor) {
        mmrenderer_stop_events(m_eventMonitor);
        m_eventMonitor = 0;
    }

    if (m_context) {
        mmr_context_destroy(m_context);
        m_context = 0;
        m_contextName.clear();
    }

    if (m_connection) {
        mmr_disconnect(m_connection);
        m_connection = 0;
    }
}

QString BbMediaPlayerControl::resourcePathForUrl(const QUrl &url)
{
    // If this is a local file, mmrenderer expects the file:// prefix and an absolute path.
    // We treat URLs without scheme as local files, most likely someone just forgot to set the
    // file:// prefix when constructing the URL.
    if (url.isLocalFile() || url.scheme().isEmpty()) {
        QString relativeFilePath;
        if (!url.scheme().isEmpty())
            relativeFilePath = url.toLocalFile();
        else
            relativeFilePath = url.path();
        const QFileInfo fileInfo(relativeFilePath);
        return QStringLiteral("file://") + fileInfo.absoluteFilePath();

    // QRC, copy to temporary file, as mmrenderer does not support resource files
    } else if (url.scheme() == QStringLiteral("qrc")) {
        const QString qrcPath = ':' + url.path();
        const QFileInfo resourceFileInfo(qrcPath);
        m_tempMediaFileName = QDir::tempPath() + QStringLiteral("/qtmedia_") +
                              QUuid::createUuid().toString() + QStringLiteral(".") +
                              resourceFileInfo.suffix();
        if (!QFile::copy(qrcPath, m_tempMediaFileName)) {
            const QString errorMsg =
                QString("Failed to copy resource file to temporary file %1 for playback").arg(m_tempMediaFileName);
            qBbMediaDebug() << errorMsg;
            emit error(0, errorMsg);
            return QString();
        }
        return m_tempMediaFileName;

    // HTTP or similar URL, use as-is
    } else {
        return url.toString();
    }
}

void BbMediaPlayerControl::attach()
{
    if (m_media.isNull() || !m_context) {
        setMediaStatus(QMediaPlayer::NoMedia);
        return;
    }

    if (m_videoControl)
        m_videoControl->attachDisplay(m_context);

    m_audioId = mmr_output_attach(m_context, "audio:default", "audio");
    if (m_audioId == -1) {
        emitMmError("mmr_output_attach() for audio failed");
        return;
    }

    const QString resourcePath = resourcePathForUrl(m_media.canonicalUrl());
    if (resourcePath.isEmpty()) {
        detach();
        return;
    }

    if (mmr_input_attach(m_context, QFile::encodeName(resourcePath), "track") != 0) {
        emitMmError(QString("mmr_input_attach() for %1 failed").arg(resourcePath));
        setMediaStatus(QMediaPlayer::InvalidMedia);
        detach();
        return;
    }

    // For whatever reason, the mmrenderer sends out a MMR_STOPPED event when calling
    // mmr_input_attach() above. Ignore it, as otherwise we'll trigger stopping right after we
    // started.
    m_stopEventsToIgnore++;

    m_inputAttached = true;
    setMediaStatus(QMediaPlayer::LoadedMedia);
    m_bufferStatus = 0;
    emit bufferStatusChanged(m_bufferStatus);
}

void BbMediaPlayerControl::detach()
{
    if (m_context) {
        if (m_inputAttached) {
            mmr_input_detach(m_context);
            m_inputAttached = false;
        }
        if (m_videoControl)
            m_videoControl->detachDisplay();
        if (m_audioId != -1 && m_context) {
            mmr_output_detach(m_context, m_audioId);
            m_audioId = -1;
        }
    }

    if (!m_tempMediaFileName.isEmpty()) {
        QFile::remove(m_tempMediaFileName);
        m_tempMediaFileName.clear();
    }
    m_loadingTimer.stop();
}

QMediaPlayer::State BbMediaPlayerControl::state() const
{
    return m_state;
}

QMediaPlayer::MediaStatus BbMediaPlayerControl::mediaStatus() const
{
    return m_mediaStatus;
}

qint64 BbMediaPlayerControl::duration() const
{
    return m_metaData.duration();
}

qint64 BbMediaPlayerControl::position() const
{
    return m_position;
}

void BbMediaPlayerControl::setPosition(qint64 position)
{
    if (m_position != position) {
        m_position = position;

        // Don't update in stopped state, it would not have any effect. Instead, the position is
        // updated in play().
        if (m_state != QMediaPlayer::StoppedState)
            setPositionInternal(m_position);

        emit positionChanged(m_position);
    }
}

int BbMediaPlayerControl::volume() const
{
    return m_volume;
}

void BbMediaPlayerControl::setVolumeInternal(int newVolume)
{
    if (!m_context)
        return;

    newVolume = qBound(0, newVolume, 100);
    if (m_audioId != -1) {
        strm_dict_t * dict = strm_dict_new();
        dict = strm_dict_set(dict, "volume", QString::number(newVolume).toLatin1());
        if (mmr_output_parameters(m_context, m_audioId, dict) != 0)
            emitMmError("mmr_output_parameters: Setting volume failed");
    }
}

void BbMediaPlayerControl::setPlaybackRateInternal(qreal rate)
{
    if (!m_context)
        return;

    const int mmRate = rate * 1000;
    if (mmr_speed_set(m_context, mmRate) != 0)
        emitMmError("mmr_speed_set failed");
}

void BbMediaPlayerControl::setPositionInternal(qint64 position)
{
    if (!m_context)
        return;

    if (mmr_seek(m_context, QString::number(position).toLatin1()) != 0)
        emitMmError("Seeking failed");
}

void BbMediaPlayerControl::setMediaStatus(QMediaPlayer::MediaStatus status)
{
    if (m_mediaStatus != status) {
        m_mediaStatus = status;
        emit mediaStatusChanged(m_mediaStatus);
    }
}

void BbMediaPlayerControl::setState(QMediaPlayer::State state)
{
    if (m_state != state) {
        m_state = state;
        emit stateChanged(m_state);
    }
}

void BbMediaPlayerControl::stopInternal(StopCommand stopCommand)
{
    if (m_state != QMediaPlayer::StoppedState) {

        if (stopCommand == StopMmRenderer) {
            ++m_stopEventsToIgnore;
            mmr_stop(m_context);
        }

        setState(QMediaPlayer::StoppedState);
    }

    if (m_position != 0) {
        m_position = 0;
        emit positionChanged(0);
    }
}

void BbMediaPlayerControl::setVolume(int volume)
{
    const int newVolume = qBound(0, volume, 100);
    if (m_volume != newVolume) {
        m_volume = newVolume;
        if (!m_muted)
            setVolumeInternal(m_volume);
        emit volumeChanged(m_volume);
    }
}

bool BbMediaPlayerControl::isMuted() const
{
    return m_muted;
}

void BbMediaPlayerControl::setMuted(bool muted)
{
    if (m_muted != muted) {
        m_muted = muted;
        setVolumeInternal(muted ? 0 : m_volume);
        emit mutedChanged(muted);
    }
}

int BbMediaPlayerControl::bufferStatus() const
{
    return m_bufferStatus;
}

bool BbMediaPlayerControl::isAudioAvailable() const
{
    return m_metaData.hasAudio();
}

bool BbMediaPlayerControl::isVideoAvailable() const
{
    return m_metaData.hasVideo();
}

bool BbMediaPlayerControl::isSeekable() const
{
    // We can currently not get that information from the mmrenderer API. Just pretend we can seek,
    // it will fail at runtime if we can not.
    return true;
}

QMediaTimeRange BbMediaPlayerControl::availablePlaybackRanges() const
{
    // We can't get this information from the mmrenderer API yet, so pretend we can seek everywhere
    return QMediaTimeRange(0, m_metaData.duration());
}

qreal BbMediaPlayerControl::playbackRate() const
{
    return m_rate;
}

void BbMediaPlayerControl::setPlaybackRate(qreal rate)
{
    if (m_rate != rate) {
        m_rate = rate;
        setPlaybackRateInternal(m_rate);
        emit playbackRateChanged(m_rate);
    }
}

QMediaContent BbMediaPlayerControl::media() const
{
    return m_media;
}

const QIODevice *BbMediaPlayerControl::mediaStream() const
{
    // Always 0, we don't support QIODevice streams
    return 0;
}

void BbMediaPlayerControl::setMedia(const QMediaContent &media, QIODevice *stream)
{
    Q_UNUSED(stream); // not supported

    stop();
    detach();

    m_media = media;
    emit mediaChanged(m_media);

    // Slight hack: With MediaPlayer QtQuick elements that have autoPlay set to true, playback
    // would start before the QtQuick canvas is propagated to all elements, and therefore our
    // video output would not work. Therefore, delay actually playing the media a bit so that the
    // canvas is ready.
    // The mmrenderer doesn't allow to attach video outputs after playing has started, otherwise
    // this would be unnecessary.
    if (!m_media.isNull()) {
        setMediaStatus(QMediaPlayer::LoadingMedia);
        m_loadingTimer.start(); // singleshot timer to continueLoadMedia()
    } else {
        continueLoadMedia(); // still needed, as it will update the media status and clear metadata
    }
}

void BbMediaPlayerControl::continueLoadMedia()
{
    attach();
    updateMetaData();
    if (m_playAfterMediaLoaded)
        play();
}

void BbMediaPlayerControl::play()
{
    if (m_playAfterMediaLoaded)
        m_playAfterMediaLoaded = false;

    // No-op if we are already playing, except if we were called from continueLoadMedia(), in which
    // case m_playAfterMediaLoaded is true (hence the 'else').
    else if (m_state == QMediaPlayer::PlayingState)
        return;

    if (m_mediaStatus == QMediaPlayer::LoadingMedia) {

        // State changes are supposed to be synchronous
        setState(QMediaPlayer::PlayingState);

        // Defer playing to later, when the timer triggers continueLoadMedia()
        m_playAfterMediaLoaded = true;
        return;
    }

    // Un-pause the state when it is paused
    if (m_state == QMediaPlayer::PausedState) {
        setPlaybackRateInternal(m_rate);
        setState(QMediaPlayer::PlayingState);
        return;
    }

    if (m_media.isNull() || !m_connection || !m_context || m_audioId == -1) {
        setState(QMediaPlayer::StoppedState);
        return;
    }

    setPositionInternal(m_position);
    setVolumeInternal(m_volume);
    setPlaybackRateInternal(m_rate);

    if (mmr_play(m_context) != 0) {
        setState(QMediaPlayer::StoppedState);
        emitMmError("mmr_play() failed");
        return;
    }

    setState( QMediaPlayer::PlayingState);
}

void BbMediaPlayerControl::pause()
{
    if (m_state == QMediaPlayer::PlayingState) {
        setPlaybackRateInternal(0);
        setState(QMediaPlayer::PausedState);
    }
}

void BbMediaPlayerControl::stop()
{
    stopInternal(StopMmRenderer);
}

void BbMediaPlayerControl::setVideoControl(BbVideoWindowControl *videoControl)
{
    m_videoControl = videoControl;
}

bool BbMediaPlayerControl::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
    Q_UNUSED(eventType);
    Q_UNUSED(result);

    bps_event_t * const event = static_cast<bps_event_t *>(message);
    if (!event ||
        (bps_event_get_domain(event) != mmrenderer_get_domain() &&
         bps_event_get_domain(event) != screen_get_domain()))
        return false;

    if (m_videoControl)
        m_videoControl->bpsEventHandler(event);

    if (bps_event_get_domain(event) == mmrenderer_get_domain()) {
        if (bps_event_get_code(event) == MMRENDERER_STATE_CHANGE) {
            const mmrenderer_state_t newState = mmrenderer_event_get_state(event);
            if (newState == MMR_STOPPED) {

                // Only react to stop events that happen when the end of the stream is reached and
                // playback is stopped because of this.
                // Ignore other stop event sources, souch as calling mmr_stop() ourselves and
                // mmr_input_attach().
                if (m_stopEventsToIgnore > 0) {
                    --m_stopEventsToIgnore;
                } else {
                    setMediaStatus(QMediaPlayer::EndOfMedia);
                    stopInternal(IgnoreMmRenderer);
                }
                return false;
            }
        }

        if (bps_event_get_code(event) == MMRENDERER_STATUS_UPDATE) {

            // Prevent spurious position change events from overriding our own position, for example
            // when setting the position to 0 in stop().
            // Also, don't change the position while we're loading the media, as then play() would
            // set a wrong initial position.
            if (m_state != QMediaPlayer::PlayingState ||
                m_mediaStatus == QMediaPlayer::LoadingMedia ||
                m_mediaStatus == QMediaPlayer::NoMedia ||
                m_mediaStatus == QMediaPlayer::InvalidMedia)
                return false;

            const qint64 newPosition = QString::fromLatin1(mmrenderer_event_get_position(event)).toLongLong();
            if (newPosition != 0 && newPosition != m_position) {
                m_position = newPosition;
                emit positionChanged(m_position);
            }

            const QString bufferStatus = QString::fromLatin1(mmrenderer_event_get_bufferlevel(event));
            const int slashPos = bufferStatus.indexOf('/');
            if (slashPos != -1) {
                const int fill = bufferStatus.left(slashPos).toInt();
                const int capacity = bufferStatus.mid(slashPos + 1).toInt();
                if (capacity != 0) {
                    m_bufferStatus = fill / static_cast<float>(capacity) * 100.0f;
                    emit bufferStatusChanged(m_bufferStatus);
                }
            }
        }
    }

    return false;
}

void BbMediaPlayerControl::updateMetaData()
{
    if (m_mediaStatus == QMediaPlayer::LoadedMedia)
        m_metaData.parse(m_contextName);
    else
        m_metaData.clear();

    if (m_videoControl)
        m_videoControl->setMetaData(m_metaData);

    emit durationChanged(m_metaData.duration());
    emit audioAvailableChanged(m_metaData.hasAudio());
    emit videoAvailableChanged(m_metaData.hasVideo());
    emit availablePlaybackRangesChanged(availablePlaybackRanges());
}

void BbMediaPlayerControl::emitMmError(const QString &msg)
{
    int errorCode = MMR_ERROR_NONE;
    const QString errorMessage = mmErrorMessage(msg, m_context, &errorCode);
    qBbMediaDebug() << errorMessage;
    emit error(errorCode, errorMessage);
}

void BbMediaPlayerControl::emitPError(const QString &msg)
{
    const QString errorMessage = QString("%1: %2").arg(msg).arg(strerror(errno));
    qBbMediaDebug() << errorMessage;
    emit error(errno, errorMessage);
}

QT_END_NAMESPACE