summaryrefslogtreecommitdiffstats
path: root/xine_artsplugin/xinePlayObject_impl.cpp
blob: a7f6defdb95f0685f3af61a67392488ad82c0c67 (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
/*
   This file is part of KDE/aRts (Noatun) - xine integration
   Copyright (C) 2002-2003 Ewald Snel <ewald@rambo.its.tudelft.nl>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <sys/time.h>
#include <audiosubsys.h>
#include <convert.h>
#include <debug.h>

#include "xinePlayObject_impl.h"

#ifndef HAVE_XSHMGETEVENTBASE
extern "C" {
extern int XShmGetEventBase( Display* );
};
#endif

#define TIMEOUT		15	// 15 seconds

using namespace Arts;


// Global xine pointer
static xine_t		*xine_shared	 = NULL;
static pthread_mutex_t	 xine_mutex	 = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t	 xine_cond	 = PTHREAD_COND_INITIALIZER;
static int		 xineRefCount	 = 0;
static bool		 xineForceXShm	 = false;

static void xine_init_routine()
{
    const char *id;
    char cfgFileName[272];

    xine_shared = (xine_t *)xine_new();

    snprintf( cfgFileName, 272, "%s/.xine/config", getenv( "HOME" ) );

    xine_config_load( xine_shared, (const char *)cfgFileName );

    // Check default video output driver
    id = xine_config_register_string (xine_shared, "video.driver",
                                      "auto", "video driver to use",
                                      NULL, 10, NULL, NULL);

    xineForceXShm = (id && !strcasecmp( id, "XShm" ));

    xine_init( xine_shared );
}

static void *xine_timeout_routine( void * )
{
    pthread_mutex_lock( &xine_mutex );

    while (xine_shared != 0)
    {
	if (xineRefCount == 0)
	{
	    struct timespec ts;
	    struct timeval tv;

	    gettimeofday( &tv, 0 );

	    ts.tv_sec	= tv.tv_sec;
	    ts.tv_nsec	= tv.tv_usec * 1000;
	    ts.tv_sec  += TIMEOUT;

	    if (pthread_cond_timedwait( &xine_cond, &xine_mutex, &ts ) != 0 &&
		xineRefCount == 0)
	    {
		xine_exit( xine_shared );
		xine_shared = NULL;
		break;
	    }
	}
	else
	{
	    pthread_cond_wait( &xine_cond, &xine_mutex );
	}
    }
    pthread_mutex_unlock( &xine_mutex );

    return NULL;
}

static xine_t *xine_shared_init()
{
    pthread_mutex_lock( &xine_mutex );

    ++xineRefCount;

    if (xine_shared == 0)
    {
	pthread_t thread;

	xine_init_routine();

	if (pthread_create( &thread, NULL, xine_timeout_routine, NULL ) == 0)
	{
	    pthread_detach( thread );
	}
    }
    else
    {
	pthread_cond_signal( &xine_cond );
    }
    pthread_mutex_unlock( &xine_mutex );

    return xine_shared;
}

static void xine_shared_exit( xine_t * )
{
    pthread_mutex_lock( &xine_mutex );

    if (--xineRefCount == 0)
    {
	pthread_cond_signal( &xine_cond );
    }
    pthread_mutex_unlock( &xine_mutex );
}

int ao_fifo_arts_delay()
{
    return (int)(1000 * Arts::AudioSubSystem::the()->outputDelay());
}

xinePlayObject_impl::xinePlayObject_impl(bool audioOnly)
    : mrl( "" ), xine( 0 ), stream( 0 ), queue( 0 ), ao_port( 0 ), vo_port( 0 ), audioOnly(audioOnly)
{

    if (!audioOnly)
    {
        XInitThreads();

        if (!(display = XOpenDisplay( NULL )))
  	{
			arts_fatal( "could not open X11 display" );
	}

    	XFlush( display );

	    // Create a special window for uninterrupted X11 communication
    	xcomWindow = XCreateSimpleWindow( display, DefaultRootWindow( display ),
					  0, 0, 1, 1, 0, 0, 0 );

	XSelectInput( display, xcomWindow, ExposureMask );
    }
    pthread_mutex_init( &mutex, 0 );

    if (!audioOnly)
    {
    	// Initialize X11 properties
    	xcomAtomQuit	   = XInternAtom( display, "VPO_INTERNAL_EVENT", False );
	xcomAtomResize	   = XInternAtom( display, "VPO_RESIZE_NOTIFY", False );
	screen		   = DefaultScreen( display );
	shmCompletionType	   = (XShmQueryExtension( display ) == True)
				   ?  XShmGetEventBase( display ) + ShmCompletion : -1;

        width		   = 0;
        height		   = 0;
        dscbTimeOut		   = 0;

    	// Initialize xine visual structure
        visual.display	   = display;
        visual.screen	   = screen;
        visual.d		   = xcomWindow;
        visual.dest_size_cb	   = &dest_size_cb;
        visual.frame_output_cb = &frame_output_cb;
        visual.user_data	   = this;
    }

    // Initialize audio and video details
    Arts::SoundServerV2 server = Arts::Reference( "global:Arts_SoundServerV2" );
    audio.sample_rate	   = 0;
    audio.num_channels	   = 0;
    audio.bits_per_sample  = 0;

    flpos		   = 0.0;
    if (!audioOnly)
        if (pthread_create( &thread, 0, pthread_start_routine, this ))
    	{
	    arts_fatal( "could not create thread" );
        }
}

xinePlayObject_impl::~xinePlayObject_impl()
{
    XEvent event;

    halt();

    // Send stop event to thread (X11 client message)
    memset( &event, 0, sizeof(event) );

    event.type			= ClientMessage;
    event.xclient.window	= xcomWindow;
    event.xclient.message_type	= xcomAtomQuit;
    event.xclient.format	= 32;

    if (!audioOnly)
    {

        XSendEvent( display, xcomWindow, True, 0, &event );

        XFlush( display );

        // Wait for the thread to die
        pthread_join( thread, 0 );

    }

    // Destroy stream, xine and related resources
    if (stream != 0)
    {
	halt();

	xine_event_dispose_queue( queue );
	xine_dispose( stream );
	xine_close_audio_driver( xine, ao_port );
	xine_close_video_driver( xine, vo_port );
    }
    if (xine != 0)
    {
	xine_shared_exit( xine );
    }

    pthread_mutex_destroy( &mutex );

    if (!audioOnly)
    {
        XSync( display, False );
        XDestroyWindow( display, xcomWindow );
        XCloseDisplay( display );
    }
}

bool xinePlayObject_impl::loadMedia( const string &url )
{
    bool result = false;

    pthread_mutex_lock( &mutex );

    mrl = "";

    if (stream == 0)
    {
	if (xine == 0)
	{
	    xine = xine_shared_init();
	}

	ao_port = init_audio_out_plugin( xine, &audio, &ao_driver );

	if (xineForceXShm && !audioOnly)
	{
	    vo_port = xine_open_video_driver( xine, "XShm",
					      XINE_VISUAL_TYPE_X11,
					      (void *)&visual );
	}
	if (vo_port == 0 && !audioOnly)
	{
	    vo_port = xine_open_video_driver( xine, "Xv",
					      XINE_VISUAL_TYPE_X11,
					      (void *)&visual );
	}
	if (vo_port == 0 && !audioOnly)
	{
	    vo_port = xine_open_video_driver( xine, "XShm",
					      XINE_VISUAL_TYPE_X11,
					      (void *)&visual );
	}
	if (vo_port == 0 && !audioOnly)
	{
	    vo_port = xine_open_video_driver( xine, "OpenGL",
					      XINE_VISUAL_TYPE_X11,
					      (void *)&visual );
	}
	if (vo_port == 0)
	{
	    vo_port = xine_open_video_driver( xine, 0,
					      XINE_VISUAL_TYPE_NONE, 0 );
	}

	if (ao_port != 0 && vo_port != 0 )
	{
	    stream = xine_stream_new( xine, ao_port, vo_port );

	    if (stream != 0)
	    {
		xine_set_param( stream, XINE_PARAM_AUDIO_CHANNEL_LOGICAL, 0 );
		xine_set_param( stream, XINE_PARAM_SPU_CHANNEL, -1 );

   	    	queue = xine_event_new_queue( stream );
		xine_event_create_listener_thread( queue, xine_handle_event, this );
	    }
	}
	if (stream == 0)
	{
	    if (ao_port != 0)
	    {
		xine_close_audio_driver( xine, ao_port );
		ao_port = 0;
	    }
	    if (vo_port != 0)
	    {
		xine_close_video_driver( xine, vo_port );
		vo_port = 0;
	    }
	}
    }

    if (stream != 0)
    {
	if (xine_get_status( stream ) == XINE_STATUS_PLAY)
	{
	    ao_fifo_clear( ao_driver, 2 );

	    xine_stop( stream );

	    clearWindow();
	}
	if ((result = xine_open( stream, url.c_str() )))
	{
	    mrl = url;
	}

	streamLength = 0;
	streamPosition = 0;

	width = 0;
	height = 0;
    }

    pthread_mutex_unlock( &mutex );

    return result;
}

string xinePlayObject_impl::description()
{
    return "xine aRts plugin";
}

poTime xinePlayObject_impl::currentTime()
{
    poTime time;
    int pos_time;

    pthread_mutex_lock( &mutex );

    if (stream != 0 && !mrl.empty())
    {
	if (xine_get_pos_length( stream, 0, &pos_time, 0 ))
	{
	    streamPosition = pos_time;
	}
	else
	{
	    pos_time = streamPosition;
	}

	time.seconds = pos_time / 1000;
	time.ms = pos_time % 1000;
    }
    else
    {
	time.seconds = 0;
	time.ms = 0;
    }
    pthread_mutex_unlock( &mutex );

    return time;
}

poTime xinePlayObject_impl::overallTime()
{
    poTime time;
    int length_time;

    pthread_mutex_lock( &mutex );

    if (stream != 0 && !mrl.empty())
    {
	if (xine_get_pos_length( stream, 0, 0, &length_time ))
	{
	    streamLength = length_time;
	}
	else
	{
	    length_time = streamLength;
	}

	if (length_time <= 0)
	{
	    length_time = 1;
	}

	time.seconds = length_time / 1000;
	time.ms = length_time % 1000;
    }
    else
    {
	time.seconds = 0;
	time.ms = 1;
    }
    pthread_mutex_unlock( &mutex );

    return time;
}

poCapabilities xinePlayObject_impl::capabilities()
{
    int n;

    pthread_mutex_lock( &mutex );

    n = (stream == 0) ? 0 : xine_get_stream_info( stream, XINE_STREAM_INFO_SEEKABLE );

    pthread_mutex_unlock( &mutex );

    return static_cast<poCapabilities>( capPause | ((n == 0) ? 0 : capSeek) );
}

string xinePlayObject_impl::mediaName()
{
    return mrl;
}

poState xinePlayObject_impl::state()
{
    poState state;

    pthread_mutex_lock( &mutex );

    if (stream == 0 || xine_get_status( stream ) != XINE_STATUS_PLAY)
	state = posIdle;
    else if (xine_get_param( stream, XINE_PARAM_SPEED ) == XINE_SPEED_PAUSE)
	state = posPaused;
    else
	state = posPlaying;

    pthread_mutex_unlock( &mutex );

    return state;
}

void xinePlayObject_impl::play()
{
    pthread_mutex_lock( &mutex );

    if (stream != 0)
    {
	if (xine_get_status( stream ) == XINE_STATUS_PLAY)
	{
	    if (xine_get_param( stream, XINE_PARAM_SPEED ) == XINE_SPEED_PAUSE)
	    {
	        xine_set_param( stream, XINE_PARAM_SPEED, XINE_SPEED_NORMAL );
	    }
	}
	else if (!mrl.empty())
	{
	    xine_play( stream, 0, 0 );
	}
    }
    pthread_mutex_unlock( &mutex );
}

void xinePlayObject_impl::halt()
{
    pthread_mutex_lock( &mutex );

    if (stream != 0 && xine_get_status( stream ) == XINE_STATUS_PLAY)
    {
	ao_fifo_clear( ao_driver, 2 );

	xine_stop( stream );

	clearWindow();

	streamLength = 0;
	streamPosition = 0;
    }
    pthread_mutex_unlock( &mutex );
}

void xinePlayObject_impl::seek( const class poTime &t )
{
    pthread_mutex_lock( &mutex );

    if (stream != 0 && xine_get_status( stream ) == XINE_STATUS_PLAY)
    {
	int seekPosition = (1000 * t.seconds) + t.ms;
	int paused = (xine_get_param( stream, XINE_PARAM_SPEED ) == XINE_SPEED_PAUSE);

	ao_fifo_clear( ao_driver, 1 );

	if (xine_play( stream, 0, seekPosition ))
	{
	    if (seekPosition >= 0 && seekPosition <= streamLength)
	    {
		streamPosition = seekPosition;
	    }
	}

	if (paused)
	{
	    xine_set_param( stream, XINE_PARAM_SPEED, XINE_SPEED_PAUSE );
	}

	ao_fifo_clear( ao_driver, 0 );
    }
    pthread_mutex_unlock( &mutex );
}

void xinePlayObject_impl::pause()
{
    pthread_mutex_lock( &mutex );

    if (stream != 0 && xine_get_status( stream ) == XINE_STATUS_PLAY)
    {
	ao_fifo_clear( ao_driver, 1 );

	xine_set_param( stream, XINE_PARAM_SPEED, XINE_SPEED_PAUSE );
    }
    pthread_mutex_unlock( &mutex );
}

void xinePlayObject_impl::calculateBlock( unsigned long samples )
{
    unsigned int skip, received = 0, converted = 0, xSamples = 0;
    unsigned char *buffer;
    double speed = 1.0;

    pthread_mutex_lock( &mutex );

    if (stream != 0)
    {
	// Calculate resampling parameters
	speed = (double)audio.sample_rate / samplingRateFloat;
	xSamples = (unsigned int)((double)samples * speed + 8.0);
	received = ao_fifo_read( ao_driver, &buffer, xSamples );
    }

    pthread_mutex_unlock( &mutex );

    // Convert samples and fill gaps with zeroes
    if (received)
    {
	converted = uni_convert_stereo_2float( samples, buffer, received,
					       audio.num_channels,
					       audio.bits_per_sample,
					       left, right, speed, flpos );
	flpos += (double)converted * speed;
	skip   = (int)floor( flpos );
	skip   = (received < (xSamples - 8)) ? (xSamples - 8) : skip;
	flpos  = flpos - floor( flpos );
	ao_fifo_flush( ao_driver, skip );
    }
    for (unsigned long i=converted; i < samples; i++)
    {
	left[i] = 0;
	right[i] = 0;
    }
}

void xinePlayObject_impl::xineEvent( const xine_event_t &event )
{
    if (event.type == XINE_EVENT_UI_PLAYBACK_FINISHED)
    {
	clearWindow();
    }
}

void xinePlayObject_impl::clearWindow()
{
    if (audioOnly) return;

    Window root;
    unsigned int u, w, h;
    int x, y, screen;

    XLockDisplay( display );

    screen = DefaultScreen( display );

    XGetGeometry( display, visual.d, &root, &x, &y, &w, &h, &u, &u );

    XSetForeground( display, DefaultGC( display, screen ),
		    BlackPixel( display, screen ) );
    XFillRectangle( display, visual.d,
		    DefaultGC( display, screen ), x, y, w, h );

    XUnlockDisplay( display );
}

void xinePlayObject_impl::frameOutput( int &x, int &y,
				       int &width, int &height, double &ratio,
				       int displayWidth, int displayHeight,
				       double displayPixelAspect, bool dscb )
{
    if (audioOnly) return;

    Window child, root;
    unsigned int u;
    int n;

    XLockDisplay( display );

    XGetGeometry( display, visual.d, &root, &n, &n,
		  (unsigned int *)&width, (unsigned int *)&height, &u, &u );

    if (!dscb)
    {
	XTranslateCoordinates( display, visual.d, root, 0, 0, &x, &y, &child );
    }

    // Most displays use (nearly) square pixels
    ratio = 1.0;

    // Correct for display pixel aspect
    if (displayPixelAspect < 1.0)
    {
	displayHeight = (int)((displayHeight / displayPixelAspect) + .5);
    }
    else
    {
	displayWidth  = (int)((displayWidth  * displayPixelAspect) + .5);
    }

    if (dscb || dscbTimeOut == 0 || --dscbTimeOut == 0)
    {
	// Notify client of new display size
	if (displayWidth != this->width || displayHeight != this->height)
	{
	    this->width  = displayWidth;
	    this->height = displayHeight;

	    resizeNotify();
	}

	// Reset 'seen dest_size_cb' time out
	if (dscb)
	{
	    dscbTimeOut = 25;
	}
    }
    XUnlockDisplay( display );
}

void xinePlayObject_impl::resizeNotify()
{
    if (audioOnly) return;
    XEvent event;

    // Resize notify signal for front-ends
    memset( &event, 0, sizeof(event) );

    event.type                  = ClientMessage;
    event.xclient.window        = visual.d;
    event.xclient.message_type  = xcomAtomResize;
    event.xclient.format        = 32;
    event.xclient.data.l[0]     = width;
    event.xclient.data.l[1]     = height;

    XSendEvent( display, visual.d, True, 0, &event );

    XFlush( display );
}

void xinePlayObject_impl::eventLoop()
{
    XEvent event;

    do
    {
	XNextEvent( display, &event );

	if (event.type == Expose && event.xexpose.count == 0 &&
	    event.xexpose.window == visual.d)
	{
	    pthread_mutex_lock( &mutex );

	    if (stream != 0)
	    {
#if XINE_MAJOR_VERSION > 1 || ( XINE_MAJOR_VERSION == 1 && XINE_MINOR_VERSION >= 2 )
		xine_port_send_gui_data( vo_port,
#else
		xine_gui_send_vo_data( stream,
#endif
				       XINE_GUI_SEND_EXPOSE_EVENT,
				       &event );
	    }
	    else
	    {
		clearWindow();
	    }
	    pthread_mutex_unlock( &mutex );
	}
	else if (event.type == shmCompletionType)
	{
	    pthread_mutex_lock( &mutex );

	    if (stream != 0)
	    {
#if XINE_MAJOR_VERSION > 1 || ( XINE_MAJOR_VERSION == 1 && XINE_MINOR_VERSION >= 2 )
		xine_port_send_gui_data( vo_port,
#else
		xine_gui_send_vo_data( stream,
#endif
				       XINE_GUI_SEND_COMPLETION_EVENT,
				       &event );
	    }
	    pthread_mutex_unlock( &mutex );
	}
    }
    while (event.type != ClientMessage ||
	   event.xclient.message_type != xcomAtomQuit ||
	   event.xclient.window != xcomWindow);
}

void xineVideoPlayObject_impl::x11WindowId( long window )
{
    pthread_mutex_lock( &mutex );

    if (window == -1)
    {
	window = xcomWindow;
    }

    if ((Window)window != visual.d)
    {
	XLockDisplay( display );

	// Change window and set event mask of new window
	visual.d = window;

	XSelectInput( display, window, ExposureMask );

	if (stream != 0)
	{
	    resizeNotify();

#if XINE_MAJOR_VERSION > 1 || ( XINE_MAJOR_VERSION == 1 && XINE_MINOR_VERSION >= 2 )
	    xine_port_send_gui_data( vo_port,
#else
	    xine_gui_send_vo_data( stream,
#endif
				   XINE_GUI_SEND_DRAWABLE_CHANGED,
				   (void *)window );
	}

	XUnlockDisplay( display );
    }
    pthread_mutex_unlock( &mutex );
}

long xineVideoPlayObject_impl::x11WindowId()
{
    return (visual.d == xcomWindow) ? (long)-1 : visual.d;
}

long xineVideoPlayObject_impl::x11Snapshot()
{
    long pixmap = -1;

    pthread_mutex_lock( &mutex );

    if (stream != 0 && xine_get_status( stream ) == XINE_STATUS_PLAY)
    {
	// FIXME: snapshot...
	pixmap = (long)-1;
    }
    pthread_mutex_unlock( &mutex );

    return pixmap;
}

REGISTER_IMPLEMENTATION(xinePlayObject_impl);
REGISTER_IMPLEMENTATION(xineAudioPlayObject_impl);
REGISTER_IMPLEMENTATION(xineVideoPlayObject_impl);