summaryrefslogtreecommitdiff
path: root/core/multimedia/opieplayer/loopcontrol.cpp
blob: 91153fdef84eb6e64f6b1fff05ebb1680f037dd1 (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
/**********************************************************************
 ** Copyright (C) 2000 Trolltech AS.  All rights reserved.
 **
 ** This file is part of Qtopia Environment.
 **
 ** This file may be distributed and/or modified under the terms of the
 ** GNU General Public License version 2 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL included in the
 ** packaging of this file.
 **
 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 **
 ** See http://www.trolltech.com/gpl/ for GPL licensing information.
 **
 ** Contact info@trolltech.com if any conditions of this licensing are
 ** not clear to you.
 **
 **********************************************************************/
// L.J.Potter added changes Fri 02-15-2002


#include "mediaplayerstate.h"
#include "loopcontrol.h"
#include "videowidget.h"
#include "audiodevice.h"

/* OPIE */
#include <qpe/qpeapplication.h>
#include <qpe/mediaplayerplugininterface.h>
#include <opie2/odebug.h>

#ifdef Q_WS_QWS
#include <qpe/qcopenvelope_qws.h>
#endif

/* QT */

/* STD */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>


extern VideoWidget *videoUI; // now only needed to tell it to play a frame
extern MediaPlayerState *mediaPlayerState;


//#define DecodeLoopDebug(x)  qDebug x
#define DecodeLoopDebug(x)


static char     *audioBuffer = NULL;
static AudioDevice  *audioDevice = NULL;
static bool     disabledSuspendScreenSaver = FALSE;
static bool     previousSuspendMode = FALSE;


pthread_t audio_tid;
pthread_attr_t  audio_attr;
bool threadOkToGo = FALSE;


class Mutex {
public:
    Mutex() {
        pthread_mutexattr_t attr;
        pthread_mutexattr_init( &attr );
        pthread_mutex_init( &mutex, &attr );
        pthread_mutexattr_destroy( &attr );
    }

    ~Mutex() {
        pthread_mutex_destroy( &mutex );
    }

    void lock() {
        pthread_mutex_lock( &mutex );
    }

    void unlock() {
        pthread_mutex_unlock( &mutex );
    }
private:
    pthread_mutex_t mutex;
};


void *startAudioThread( void *ptr ) {
    LoopControl *mpegView = (LoopControl *)ptr;
    while ( TRUE ) {
        if ( threadOkToGo && mpegView->moreAudio )
            mpegView->startAudio();
        else
            usleep( 10000 ); // Semi-buzy-wait till we are playing again
    }
    return 0;
}


Mutex *audioMutex;


LoopControl::LoopControl( QObject *parent, const char *name )
        : QObject( parent, name ) {
    isMuted = FALSE;
    connect( qApp, SIGNAL( volumeChanged(bool) ), this, SLOT( setMute(bool) ) );
    //odebug << "starting loopcontrol" << oendl;
    audioMutex = new Mutex;

    pthread_attr_init(&audio_attr);
#define USE_REALTIME_AUDIO_THREAD
#ifdef USE_REALTIME_AUDIO_THREAD
      // Attempt to set it to real-time round robin
    if ( pthread_attr_setschedpolicy( &audio_attr, SCHED_RR ) == 0 ) {
        sched_param params;
        params.sched_priority = 50;
        pthread_attr_setschedparam(&audio_attr,&params);
    } else {
       //        odebug << "Error setting up a realtime thread, reverting to using a normal thread." << oendl;
        pthread_attr_destroy(&audio_attr);
        pthread_attr_init(&audio_attr);
    }
#endif
    //odebug << "create audio thread" << oendl;
    pthread_create(&audio_tid, &audio_attr, (void * (*)(void *))startAudioThread, this);
}


LoopControl::~LoopControl() {
    stop();
}


static long prev_frame = 0;
static int currentSample = 0;


void LoopControl::timerEvent( QTimerEvent *te ) {

    if ( te->timerId() == videoId )
        startVideo();

    if ( te->timerId() == sliderId ) {
        if ( hasAudioChannel && !hasVideoChannel && moreAudio ) {
            mediaPlayerState->updatePosition( audioSampleCounter );
        } else if ( hasVideoChannel && moreVideo ) {
            mediaPlayerState->updatePosition( current_frame );
        }
    }

    if ( !moreVideo && !moreAudio ) {
        mediaPlayerState->setPlaying( FALSE );
        mediaPlayerState->setNext();
    }
}


void LoopControl::setPosition( long pos ) {
    audioMutex->lock();
//    odebug << "Loop control " << pos << "" << oendl;
    if ( hasVideoChannel && hasAudioChannel ) {
        playtime.restart();
        playtime = playtime.addMSecs( long((double)-pos * 1000.0 / framerate) );
        current_frame = pos + 1;
        mediaPlayerState->curDecoder()->videoSetFrame( current_frame, stream );
        prev_frame = current_frame - 1;
        currentSample = (int)( (double)current_frame * freq / framerate );
        mediaPlayerState->curDecoder()->audioSetSample( currentSample, stream );
        audioSampleCounter = currentSample - 1;
    } else if ( hasVideoChannel ) {
        playtime.restart();
        playtime = playtime.addMSecs( long((double)-pos * 1000.0 / framerate) );
        current_frame = pos + 1;
        mediaPlayerState->curDecoder()->videoSetFrame( current_frame, stream );
        prev_frame = current_frame - 1;
    } else if ( hasAudioChannel ) {
        playtime.restart();
        playtime = playtime.addMSecs( long((double)-pos * 1000.0 / freq) );
        currentSample = pos + 1;
        mediaPlayerState->curDecoder()->audioSetSample( currentSample, stream );
        audioSampleCounter = currentSample - 1;
    }

    audioMutex->unlock();
}


void LoopControl::startVideo() {

    if ( moreVideo ) {

        if ( mediaPlayerState->curDecoder() ) {

            if ( hasAudioChannel && !isMuted ) {

                current_frame = long( playtime.elapsed() * framerate / 1000 );

                if ( prev_frame != -1 && current_frame <= prev_frame )
                    return;

            } else {
                  // Don't skip
                current_frame++;
            }

            if ( prev_frame == -1 || current_frame > prev_frame ) {
                if ( current_frame > prev_frame + 1 ) {
                    mediaPlayerState->curDecoder()->videoSetFrame( current_frame, stream );
                }
                moreVideo = videoUI->playVideo();
                prev_frame = current_frame;
            }

        } else {

            moreVideo = FALSE;
            killTimer( videoId );

        }

    }
}


void LoopControl::startAudio() {

    audioMutex->lock();
    if ( moreAudio ) {

        if ( !isMuted && mediaPlayerState->curDecoder() ) {

            currentSample = audioSampleCounter + 1;

//              if ( currentSample != audioSampleCounter + 1 )
//                  odebug << "out of sync with decoder " << currentSample << " " << audioSampleCounter << "" << oendl;

            long samplesRead = 0;
            bool readOk=mediaPlayerState->curDecoder()->audioReadSamples( (short*)audioBuffer, channels, 1024, samplesRead, stream );
            long sampleWeShouldBeAt = long( playtime.elapsed() ) * freq / 1000;
            long sampleWaitTime = currentSample - sampleWeShouldBeAt;

// this causes drop outs not sure why its even here
         if ( hasVideoChannel ) {
           if ( ( sampleWaitTime > 2000 ) && ( sampleWaitTime < 20000 ) ) {
         usleep( (long)((double)sampleWaitTime * 1000000.0 / freq) );
           }
         else if ( sampleWaitTime <= -5000 ) {
            //        odebug << "need to catch up by: " << -sampleWaitTime << " (" << currentSample << "," << sampleWeShouldBeAt << ")" << oendl;
 //       //mediaPlayerState->curDecoder()->audioSetSample( sampleWeShouldBeAt, stream );
        currentSample = sampleWeShouldBeAt;
          }
}

            audioDevice->write( audioBuffer, samplesRead * 2 * channels );

            if(  mediaPlayerState->isStreaming == FALSE)
                audioSampleCounter = currentSample + samplesRead - 1;

            moreAudio = readOk && (audioSampleCounter <= total_audio_samples);

        } else {

            moreAudio = FALSE;

        }

    }

    audioMutex->unlock();
}


void LoopControl::killTimers() {

    audioMutex->lock();

    if ( hasVideoChannel )
        killTimer( videoId );
    killTimer( sliderId );
    threadOkToGo = FALSE;

    audioMutex->unlock();
}


void LoopControl::startTimers() {

    audioMutex->lock();

    moreVideo = FALSE;
    moreAudio = FALSE;

    if ( hasVideoChannel ) {
        moreVideo = TRUE;
        int mSecsBetweenFrames = (int)(100 / framerate); // 10% of the real value
        videoId = startTimer( mSecsBetweenFrames );
    }

    if ( hasAudioChannel ) {
        moreAudio = TRUE;
        threadOkToGo = TRUE;
    }

    sliderId = startTimer( 300 ); // update slider every 1/3 second

    audioMutex->unlock();
}


void LoopControl::setPaused( bool pause ) {

    if ( !mediaPlayerState->curDecoder() || !mediaPlayerState->curDecoder()->isOpen() )
        return;

    if ( pause ) {
        killTimers();
    } else {
          // Force an update of the position
        mediaPlayerState->setPosition( mediaPlayerState->position() + 1 );
        mediaPlayerState->setPosition( mediaPlayerState->position() - 1 );
          // Just like we never stopped
        startTimers();
    }
}


void LoopControl::stop( bool willPlayAgainShortly ) {

#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
    if ( !willPlayAgainShortly && disabledSuspendScreenSaver ) {
        disabledSuspendScreenSaver = FALSE;
          // Re-enable the suspend mode
        QCopEnvelope("QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
    }
#endif

    if ( mediaPlayerState->curDecoder() && mediaPlayerState->curDecoder()->isOpen() ) {

        killTimers();

        audioMutex->lock();

        mediaPlayerState->curDecoder()->close();

        if ( audioDevice ) {
            delete audioDevice;
            delete audioBuffer;
            audioDevice = 0;
            audioBuffer = 0;
        }

        audioMutex->unlock();
    }
    audioSampleCounter=0;
    current_frame=0;
    total_audio_samples=0;
}


bool LoopControl::init( const QString& filename ) {
    stop();
    audioMutex->lock();

    fileName = filename;
    stream = 0; // only play stream 0 for now
    current_frame = total_video_frames = total_audio_samples = 0;

    //    odebug << "Using the " << mediaPlayerState->curDecoder()->pluginName() << " decoder" << oendl;

      // ### Hack to use libmpeg3plugin to get the number of audio samples if we are using the libmad plugin
//     if ( mediaPlayerState->curDecoder()->pluginName() == QString("LibMadPlugin") ) {
//         if ( mediaPlayerState->libMpeg3Decoder() && mediaPlayerState->libMpeg3Decoder()->open( filename )) {
//             total_audio_samples = mediaPlayerState->libMpeg3Decoder()->audioSamples( 0 );
//             mediaPlayerState->libMpeg3Decoder()->close();
//         }
//     }

    if ( !mediaPlayerState->curDecoder()|| !mediaPlayerState->curDecoder()->open( filename ) ) {
        audioMutex->unlock();
        return FALSE;
    }

    hasAudioChannel = mediaPlayerState->curDecoder()->audioStreams() > 0;
    hasVideoChannel = mediaPlayerState->curDecoder()->videoStreams() > 0;

    if ( hasAudioChannel ) {
        int astream = 0;

        if ( mediaPlayerState->curDecoder()->pluginName() == QString("LibMpeg3Plugin") )
            channels = 2; //dont akx me why, but it needs this hack
        else
            channels = mediaPlayerState->curDecoder()->audioChannels( astream );

        //        odebug << "LC- channels = " << channels << "" << oendl;

//        if ( !total_audio_samples )
            total_audio_samples = mediaPlayerState->curDecoder()->audioSamples( astream );

        total_audio_samples += 1000;
        //        odebug << "total samples " << total_audio_samples << "" << oendl;
        mediaPlayerState->setLength( total_audio_samples );

        freq = mediaPlayerState->curDecoder()->audioFrequency( astream );
        //        odebug << "LC- frequency = " << freq << "" << oendl;

        audioSampleCounter = 0;
        int bits_per_sample;
        if ( mediaPlayerState->curDecoder()->pluginName() == QString("LibWavPlugin") ) {
            bits_per_sample =(int) mediaPlayerState->curDecoder()->getTime();
            //            odebug << "using stupid hack" << oendl;
        } else {
            bits_per_sample=0;
        }

        audioDevice = new AudioDevice( freq, channels, bits_per_sample);
        audioBuffer = new char[ audioDevice->bufferSize() ];
        channels = audioDevice->channels();

          //### must check which frequency is actually used.
        static const int size = 1;
        short int buf[size];
        long samplesRead = 0;
        mediaPlayerState->curDecoder()->audioReadSamples( buf, channels, size, samplesRead, stream );
    }

    if ( hasVideoChannel ) {
        total_video_frames = mediaPlayerState->curDecoder()->videoFrames( stream );

        mediaPlayerState->setLength( total_video_frames );

        framerate = mediaPlayerState->curDecoder()->videoFrameRate( stream );
        DecodeLoopDebug(( "Frame rate %g total %ld", framerate, total_video_frames ));

        if ( framerate <= 1.0 ) {
            DecodeLoopDebug(( "Crazy frame rate, resetting to sensible" ));
            framerate = 25;
        }

        if ( total_video_frames == 1 ) {
            DecodeLoopDebug(( "Cannot seek to frame" ));
        }

    }

    current_frame = 0;
    prev_frame = -1;

    connect( mediaPlayerState, SIGNAL( positionChanged(long) ), this, SLOT( setPosition(long) ) );
    connect( mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( setPaused(bool) ) );

    audioMutex->unlock();

    return TRUE;
}


void LoopControl::play() {
   //    odebug << "LC- play" << oendl;
    mediaPlayerState->setPosition( 0); //uglyhack

#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
    if ( !disabledSuspendScreenSaver || previousSuspendMode != hasVideoChannel ) {
        disabledSuspendScreenSaver = TRUE;
        previousSuspendMode = hasVideoChannel;
          // Stop the screen from blanking and power saving state
        QCopEnvelope("QPE/System", "setScreenSaverMode(int)" )
            << ( hasVideoChannel ? QPEApplication::Disable : QPEApplication::DisableSuspend );
    }
#endif

    playtime.start();
    startTimers();
}


void LoopControl::setMute( bool on ) {
    if ( on != isMuted ) {
        isMuted = on;
        if ( !on ) {
              // Force an update of the position
            mediaPlayerState->setPosition( mediaPlayerState->position() + 1 );
            mediaPlayerState->setPosition( mediaPlayerState->position() - 1 );
              // Resume playing audio
            moreAudio = TRUE;
        }
    }
}