summaryrefslogtreecommitdiffstats
path: root/src/plugins/mediaservices/qt7/mediaplayer/qt7playersession.mm
blob: d516a990511ff983ae95119e1864cdaa9ea8b400 (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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#import <QTKit/QTDataReference.h>
#import <QTKit/QTMovie.h>

#include "qt7backend.h"

#include "qt7playersession.h"
#include "qt7playercontrol.h"
#include "qt7videooutputcontrol.h"

#include <QtMultimedia/qmediaplaylistnavigator.h>

#include <CoreFoundation/CoreFoundation.h>

#include <QtCore/qurl.h>
#include <QtCore/qdebug.h>

@interface QTMovieObserver : NSObject
{
@private
    QT7PlayerSession *m_session;
    QTMovie *m_movie;
}

- (QTMovieObserver *) initWithPlayerSession:(QT7PlayerSession*)session;
- (void) setMovie:(QTMovie *)movie;
- (void) processEOS:(NSNotification *)notification;
- (void) processStateChange:(NSNotification *)notification;
@end

@implementation QTMovieObserver

- (QTMovieObserver *) initWithPlayerSession:(QT7PlayerSession*)session
{
    if (!(self = [super init]))
        return nil;

    self->m_session = session;
    return self;
}

- (void) setMovie:(QTMovie *)movie
{
    if (m_movie == movie)
        return;

    if (m_movie) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [m_movie release];
    }

    m_movie = movie;

    if (movie) {
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(processEOS:) 
                                                     name:QTMovieDidEndNotification
                                                   object:m_movie];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(processStateChange:) 
                                                     name:QTMovieLoadStateDidChangeNotification 
                                                   object:m_movie];

        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(processVolumeChange:) 
                                                     name:QTMovieVolumeDidChangeNotification 
                                                   object:m_movie];

        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(processNaturalSizeChange:)
                                                     name: 
#if defined(MAC_OS_X_VERSION_10_6) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
                                                          QTMovieNaturalSizeDidChangeNotification
#else
                                                          QTMovieEditedNotification
#endif
                                                   object:m_movie];
        [movie retain];
    }
}

- (void) processEOS:(NSNotification *)notification
{
    Q_UNUSED(notification);
    m_session->processEOS();
}

- (void) processStateChange:(NSNotification *)notification
{
    Q_UNUSED(notification);
    m_session->processStateChange();
}

- (void) processVolumeChange:(NSNotification *)notification
{
    Q_UNUSED(notification);
    m_session->processVolumeChange();
}

- (void) processNaturalSizeChange :(NSNotification *)notification
{
    Q_UNUSED(notification);
    m_session->processNaturalSizeChange();
}

@end

QT_BEGIN_NAMESPACE

static CFStringRef qString2CFStringRef(const QString &string)
{
    return CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>(string.unicode()),
                                        string.length());
}

QT7PlayerSession::QT7PlayerSession(QObject *parent)
   : QObject(parent)
   , m_QTMovie(0)
   , m_state(QMediaPlayer::StoppedState)
   , m_mediaStatus(QMediaPlayer::NoMedia)
   , m_mediaStream(0)
   , m_videoOutput(0)
   , m_muted(false)
   , m_volume(100)
   , m_rate(1.0)
{
    m_movieObserver = [[QTMovieObserver alloc] initWithPlayerSession:this];
}

QT7PlayerSession::~QT7PlayerSession()
{
    [(QTMovieObserver*)m_movieObserver setMovie:nil];
    [(QTMovieObserver*)m_movieObserver release];
}

void *QT7PlayerSession::movie() const
{
    return m_QTMovie;
}

void QT7PlayerSession::setVideoOutput(QT7VideoOutput *output)
{
    if (m_videoOutput == output)
        return;

    if (m_videoOutput) {
        m_videoOutput->setEnabled(false);
        m_videoOutput->setMovie(0);
    }

    m_videoOutput = output;

    if (m_videoOutput) {
        m_videoOutput->setEnabled(m_QTMovie != 0);
        m_videoOutput->setMovie(m_QTMovie);
    }
}


qint64 QT7PlayerSession::position() const
{
    if (!m_QTMovie || m_state == QMediaPlayer::PausedState)
        return m_currentTime;

    AutoReleasePool pool;

    QTTime qtTime = [(QTMovie*)m_QTMovie currentTime];
    quint64 t = static_cast<quint64>(float(qtTime.timeValue) / float(qtTime.timeScale) * 1000.0f);
    m_currentTime = t;

    return m_currentTime;
}

qint64 QT7PlayerSession::duration() const
{
    if (!m_QTMovie)
        return 0;

    AutoReleasePool pool;

    QTTime qtTime = [(QTMovie*)m_QTMovie duration];

    return static_cast<quint64>(float(qtTime.timeValue) / float(qtTime.timeScale) * 1000.0f);
}

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

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

int QT7PlayerSession::bufferStatus() const
{
    return 100;
}

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

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

bool QT7PlayerSession::isSeekable() const
{
    return true;
}

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

void QT7PlayerSession::setPlaybackRate(qreal rate)
{
    if (qFuzzyCompare(m_rate, rate))
        return;

    m_rate = rate;

    if (m_QTMovie && m_state == QMediaPlayer::PlayingState) {        
        float preferredRate = [[(QTMovie*)m_QTMovie attributeForKey:@"QTMoviePreferredRateAttribute"] floatValue];
        [(QTMovie*)m_QTMovie setRate:preferredRate*m_rate];
    }
}

void QT7PlayerSession::setPosition(qint64 pos)
{
    if ( !isSeekable() || pos == position())
        return;

    AutoReleasePool pool;

    pos = qMin(pos, duration());

    QTTime newQTTime = [(QTMovie*)m_QTMovie currentTime];
    newQTTime.timeValue = (pos / 1000.0f) * newQTTime.timeScale;
    [(QTMovie*)m_QTMovie setCurrentTime:newQTTime];
}

void QT7PlayerSession::play()
{
    float preferredRate = [[(QTMovie*)m_QTMovie attributeForKey:@"QTMoviePreferredRateAttribute"] floatValue];
    [(QTMovie*)m_QTMovie setRate:preferredRate*m_rate];

    if (m_state != QMediaPlayer::PlayingState)
        emit stateChanged(m_state = QMediaPlayer::PlayingState);
}

void QT7PlayerSession::pause()
{
    m_state = QMediaPlayer::PausedState;

    [(QTMovie*)m_QTMovie setRate:0];

    emit stateChanged(m_state);
}

void QT7PlayerSession::stop()
{
    m_state = QMediaPlayer::StoppedState;

    [(QTMovie*)m_QTMovie setRate:0];
    setPosition(0);

    if (m_state == QMediaPlayer::StoppedState)
        emit stateChanged(m_state);
}

void QT7PlayerSession::setVolume(int volume)
{
    if (m_QTMovie) {
        m_volume = volume;
        [(QTMovie*)m_QTMovie setVolume:(volume/100.0f)];
    }
}

void QT7PlayerSession::setMuted(bool muted)
{
    if (m_muted != muted) {
        m_muted = muted;

        if (m_QTMovie)
            [(QTMovie*)m_QTMovie setMuted:m_muted];

        emit mutedChanged(muted);
    }
}

QMediaContent QT7PlayerSession::media() const
{
    return m_resources;
}

const QIODevice *QT7PlayerSession::mediaStream() const
{
    return m_mediaStream;
}

void QT7PlayerSession::setMedia(const QMediaContent &content, QIODevice *stream)
{
    AutoReleasePool pool;

    if (m_QTMovie) {
        [(QTMovieObserver*)m_movieObserver setMovie:nil];

        if (m_videoOutput) {
            m_videoOutput->setEnabled(false);
            m_videoOutput->setMovie(0);
        }

        [(QTMovie*)m_QTMovie release];
        m_QTMovie = 0;
    }

    m_resources = content;
    m_mediaStream = stream;
    m_mediaStatus = QMediaPlayer::NoMedia;

    QUrl url;

    if (!content.isNull())
        url = content.canonicalUrl();
    else
        return;

    qDebug() << "Open media" << url;

    NSError *err = 0;
    NSString *urlString = (NSString *)qString2CFStringRef(url.toString());

    NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSURL URLWithString:urlString], QTMovieURLAttribute,
                            [NSNumber numberWithBool:YES], QTMovieOpenAsyncOKAttribute,
                            [NSNumber numberWithBool:YES], QTMovieIsActiveAttribute,
                            [NSNumber numberWithBool:YES], QTMovieResolveDataRefsAttribute,
                            [NSNumber numberWithBool:YES], QTMovieDontInteractWithUserAttribute,
                            nil];

    m_QTMovie = [[QTMovie movieWithAttributes:attr error:&err] retain];

    if (err) {
        [(QTMovie*)m_QTMovie release];
        m_QTMovie = 0;
        QString description = QString::fromUtf8([[err localizedDescription] UTF8String]);

        emit error(QMediaPlayer::FormatError, description );
    } else {
        [(QTMovieObserver*)m_movieObserver setMovie:(QTMovie*)m_QTMovie];

        if (m_videoOutput) {            
            m_videoOutput->setMovie(m_QTMovie);
            m_videoOutput->setEnabled(true);
        }
        processStateChange();

        [(QTMovie*)m_QTMovie setMuted:m_muted];
        setVolume(m_volume);
    }
}

bool QT7PlayerSession::isAudioAvailable() const
{
    if (!m_QTMovie)
        return false;

    AutoReleasePool pool;
    return [[(QTMovie*)m_QTMovie attributeForKey:@"QTMovieHasAudioAttribute"] boolValue] == YES;
}

bool QT7PlayerSession::isVideoAvailable() const
{
    if (!m_QTMovie)
        return false;

    AutoReleasePool pool;
    return [[(QTMovie*)m_QTMovie attributeForKey:@"QTMovieHasVideoAttribute"] boolValue] == YES;
}

void QT7PlayerSession::processEOS()
{    
    m_mediaStatus = QMediaPlayer::EndOfMedia;
    emit stateChanged(m_state = QMediaPlayer::StoppedState);
    emit mediaStatusChanged(m_mediaStatus);
}

void QT7PlayerSession::processStateChange()
{
    signed long state = [[(QTMovie*)m_QTMovie attributeForKey:QTMovieLoadStateAttribute]
                         longValue];
    qDebug() << "Moview load state changed:" << state;

#ifndef QUICKTIME_C_API_AVAILABLE
    enum {
      kMovieLoadStateError          = -1L,
      kMovieLoadStateLoading        = 1000,
      kMovieLoadStateLoaded         = 2000,
      kMovieLoadStatePlayable       = 10000,
      kMovieLoadStatePlaythroughOK  = 20000,
      kMovieLoadStateComplete       = 100000
    };
#endif

    QMediaPlayer::MediaStatus newStatus = QMediaPlayer::NoMedia;
    bool isPlaying = (m_state != QMediaPlayer::StoppedState);

    if (state >= kMovieLoadStateComplete) {
        newStatus = isPlaying ? QMediaPlayer::BufferedMedia : QMediaPlayer::LoadedMedia;
    } else if (state >= kMovieLoadStatePlayable)
        newStatus = isPlaying ? QMediaPlayer::BufferingMedia : QMediaPlayer::LoadingMedia;
    else if (state >= kMovieLoadStateLoading)
        newStatus = isPlaying ? QMediaPlayer::StalledMedia : QMediaPlayer::LoadingMedia;

    if (state == kMovieLoadStateError) {
        newStatus = QMediaPlayer::InvalidMedia;
        emit error(QMediaPlayer::FormatError, tr("Playback failed"));
    }

    if (newStatus != m_mediaStatus) {
        switch (newStatus) {
        case QMediaPlayer::BufferedMedia:
        case QMediaPlayer::BufferingMedia:
            //delayed playback start is necessary for network sources
            if (m_state == QMediaPlayer::PlayingState) {
                QMetaObject::invokeMethod(this, "play", Qt::QueuedConnection);
            }
            //fall
        case QMediaPlayer::LoadedMedia:
        case QMediaPlayer::LoadingMedia:
            emit durationChanged(duration());
            emit audioAvailableChanged(isAudioAvailable());
            emit videoAvailableChanged(isVideoAvailable());
            break;
        case QMediaPlayer::InvalidMedia:
            emit stateChanged(m_state = QMediaPlayer::StoppedState);
        default:
            break;
        }

        emit mediaStatusChanged(m_mediaStatus = newStatus);
    }
}

void QT7PlayerSession::processVolumeChange()
{
    if (!m_QTMovie)
        return;

    int newVolume = qRound(100.0f*[((QTMovie*)m_QTMovie) volume]);

    if (newVolume != m_volume) {
        emit volumeChanged(m_volume = newVolume);
    }
}

void QT7PlayerSession::processNaturalSizeChange()
{
    if (m_videoOutput) {
        NSSize size = [[(QTMovie*)m_QTMovie attributeForKey:@"QTMovieNaturalSizeAttribute"] sizeValue];
        qDebug() << "Native size changed:" << QSize(size.width, size.height);
        m_videoOutput->updateNaturalSize(QSize(size.width, size.height));
    }
}

#include "moc_qt7playersession.cpp"

QT_END_NAMESPACE