vlcplugin_base.cpp 27.9 KB
Newer Older
1
/*****************************************************************************
2
 * vlcplugin.cpp: a VLC plugin for Mozilla
3
 *****************************************************************************
Jean-Paul Saman's avatar
Jean-Paul Saman committed
4
 * Copyright (C) 2002-2010 the VideoLAN team
5
 * $Id$
6 7
 *
 * Authors: Samuel Hocevar <sam@zoy.org>
8
 *          Damien Fouilleul <damienf.fouilleul@laposte.net>
9
 *          Jean-Paul Saman <jpsaman@videolan.org>
10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
Antoine Cellerier's avatar
Antoine Cellerier committed
23
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 25 26 27 28
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
29 30 31 32
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

33
#include "vlcplugin.h"
Jean-Paul Saman's avatar
Jean-Paul Saman committed
34

35
#include "control/npolibvlc.h"
36

37
#include <cctype>
38

39
#if defined(XP_UNIX)
40 41 42 43
#   include <pthread.h>
#elif defined(XP_WIN)
    /* windows headers */
#   include <winbase.h>
44 45 46 47
#else
#warning "locking not implemented for this platform"
#endif

48 49 50 51
#include <cstdio>
#include <cassert>
#include <cstdlib>
#include <cstring>
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
/*****************************************************************************
 * utilitiy functions
 *****************************************************************************/
static void plugin_lock_init(plugin_lock_t *lock)
{
    assert(lock);

#if defined(XP_UNIX)
    pthread_mutex_init(&lock->mutex, NULL);
#elif defined(XP_WIN)
    InitializeCriticalSection(&lock->cs);
#else
#warning "locking not implemented in this platform"
#endif
}

static void plugin_lock_destroy(plugin_lock_t *lock)
{
    assert(lock);

#if defined(XP_UNIX)
    pthread_mutex_destroy(&lock->mutex);
#elif defined(XP_WIN)
    DeleteCriticalSection(&lock->cs);
#else
#warning "locking not implemented in this platform"
#endif
}

static void plugin_lock(plugin_lock_t *lock)
{
    assert(lock);

#if defined(XP_UNIX)
    pthread_mutex_lock(&lock->mutex);
#elif defined(XP_WIN)
    EnterCriticalSection(&lock->cs);
#else
#warning "locking not implemented in this platform"
#endif
}

static void plugin_unlock(plugin_lock_t *lock)
{
    assert(lock);

#if defined(XP_UNIX)
    pthread_mutex_unlock(&lock->mutex);
#elif defined(XP_WIN)
    LeaveCriticalSection(&lock->cs);
#else
#warning "locking not implemented in this platform"
#endif
}

108
/*****************************************************************************
Jean-Paul Saman's avatar
Jean-Paul Saman committed
109
 * Event Object
110
 *****************************************************************************/
Jean-Paul Saman's avatar
Jean-Paul Saman committed
111 112 113 114 115 116 117
static void handle_input_event(const libvlc_event_t* event, void *param);
static void handle_changed_event(const libvlc_event_t* event, void *param);

static vlcplugin_event_t vlcevents[] = {
    { "MediaPlayerMediaChanged", libvlc_MediaPlayerMediaChanged, handle_input_event },
    { "MediaPlayerNothingSpecial", libvlc_MediaPlayerNothingSpecial, handle_input_event },
    { "MediaPlayerOpening", libvlc_MediaPlayerOpening, handle_input_event },
118
    { "MediaPlayerBuffering", libvlc_MediaPlayerBuffering, handle_changed_event },
Jean-Paul Saman's avatar
Jean-Paul Saman committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    { "MediaPlayerPlaying", libvlc_MediaPlayerPlaying, handle_input_event },
    { "MediaPlayerPaused", libvlc_MediaPlayerPaused, handle_input_event },
    { "MediaPlayerStopped", libvlc_MediaPlayerStopped, handle_input_event },
    { "MediaPlayerForward", libvlc_MediaPlayerForward, handle_input_event },
    { "MediaPlayerBackward", libvlc_MediaPlayerBackward, handle_input_event },
    { "MediaPlayerEndReached", libvlc_MediaPlayerEndReached, handle_input_event },
    { "MediaPlayerEncounteredError", libvlc_MediaPlayerEncounteredError, handle_input_event },
    { "MediaPlayerTimeChanged", libvlc_MediaPlayerTimeChanged, handle_changed_event },
    { "MediaPlayerPositionChanged", libvlc_MediaPlayerPositionChanged, handle_changed_event },
    { "MediaPlayerSeekableChanged", libvlc_MediaPlayerSeekableChanged, handle_changed_event },
    { "MediaPlayerPausableChanged", libvlc_MediaPlayerPausableChanged, handle_changed_event },
    { "MediaPlayerTitleChanged", libvlc_MediaPlayerTitleChanged, handle_changed_event },
    { "MediaPlayerLengthChanged", libvlc_MediaPlayerLengthChanged, handle_changed_event },
};

static void handle_input_event(const libvlc_event_t* event, void *param)
135
{
136
    VlcPluginBase *plugin = (VlcPluginBase*)param;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
137 138 139 140 141 142 143 144 145 146 147
    switch( event->type )
    {
        case libvlc_MediaPlayerNothingSpecial:
        case libvlc_MediaPlayerOpening:
        case libvlc_MediaPlayerPlaying:
        case libvlc_MediaPlayerPaused:
        case libvlc_MediaPlayerStopped:
        case libvlc_MediaPlayerForward:
        case libvlc_MediaPlayerBackward:
        case libvlc_MediaPlayerEndReached:
        case libvlc_MediaPlayerEncounteredError:
148
            plugin->event_callback(event, NULL, 0);
Jean-Paul Saman's avatar
Jean-Paul Saman committed
149 150 151 152
            break;
        default: /* ignore all other libvlc_event_type_t */
            break;
    }
153 154
}

Jean-Paul Saman's avatar
Jean-Paul Saman committed
155 156 157 158 159
static void handle_changed_event(const libvlc_event_t* event, void *param)
{
    uint32_t   npcount = 1;
    NPVariant *npparam = (NPVariant *) NPN_MemAlloc( sizeof(NPVariant) * npcount );

160
    VlcPluginBase *plugin = (VlcPluginBase*)param;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
161 162
    switch( event->type )
    {
163
#ifdef LIBVLC120
164 165 166
        case libvlc_MediaPlayerBuffering:
            DOUBLE_TO_NPVARIANT(event->u.media_player_buffering.new_cache, npparam[0]);
            break;
167
#endif
Jean-Paul Saman's avatar
Jean-Paul Saman committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        case libvlc_MediaPlayerTimeChanged:
            DOUBLE_TO_NPVARIANT(event->u.media_player_time_changed.new_time, npparam[0]);
            break;
        case libvlc_MediaPlayerPositionChanged:
            DOUBLE_TO_NPVARIANT(event->u.media_player_position_changed.new_position, npparam[0]);
            break;
        case libvlc_MediaPlayerSeekableChanged:
            BOOLEAN_TO_NPVARIANT(event->u.media_player_seekable_changed.new_seekable, npparam[0]);
            break;
        case libvlc_MediaPlayerPausableChanged:
            BOOLEAN_TO_NPVARIANT(event->u.media_player_pausable_changed.new_pausable, npparam[0]);
            break;
        case libvlc_MediaPlayerTitleChanged:
            BOOLEAN_TO_NPVARIANT(event->u.media_player_title_changed.new_title, npparam[0]);
            break;
        case libvlc_MediaPlayerLengthChanged:
            DOUBLE_TO_NPVARIANT(event->u.media_player_length_changed.new_length, npparam[0]);
            break;
        default: /* ignore all other libvlc_event_type_t */
            NPN_MemFree( npparam );
            return;
    }
190
    plugin->event_callback(event, npparam, npcount);
191
}
192

193 194
bool EventObj::init()
{
195 196
    plugin_lock_init(&lock);
    return true;
197 198 199 200
}

EventObj::~EventObj()
{
201
    plugin_lock_destroy(&lock);
202
}
203 204

void EventObj::deliver(NPP browser)
205
{
206 207
    plugin_lock(&lock);

Jean-Paul Saman's avatar
Jean-Paul Saman committed
208
    for( ev_l::iterator iter = _elist.begin(); iter != _elist.end(); ++iter )
209
    {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
210
        for( lr_l::iterator j = _llist.begin(); j != _llist.end(); ++j )
211
        {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
212
            if( j->event_type() == iter->event_type() )
213
            {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
                NPVariant result;
                NPVariant *params = iter->params();
                uint32_t   count  = iter->count();

                NPObject *listener = j->listener();
                assert( listener );

                NPN_InvokeDefault( browser, listener, params, count, &result );
                NPN_ReleaseVariantValue( &result );

                for( uint32_t n = 0; n < count; n++ )
                {
                    if( NPVARIANT_IS_STRING(params[n]) )
                        NPN_MemFree( (void*) NPVARIANT_TO_STRING(params[n]).UTF8Characters );
                    else if( NPVARIANT_IS_OBJECT(params[n]) )
                    {
                        NPN_ReleaseObject( NPVARIANT_TO_OBJECT(params[n]) );
                        NPN_MemFree( (void*)NPVARIANT_TO_OBJECT(params[n]) );
                    }
                }
234
                if (params) NPN_MemFree( params );
235 236 237
            }
        }
    }
238
    _elist.clear();
239 240

    plugin_unlock(&lock);
241 242
}

Jean-Paul Saman's avatar
Jean-Paul Saman committed
243 244
void EventObj::callback(const libvlc_event_t* event,
                        NPVariant *npparams, uint32_t count)
245
{
246
    plugin_lock(&lock);
Jean-Paul Saman's avatar
Jean-Paul Saman committed
247
    _elist.push_back(VLCEvent(event->type, npparams, count));
248
    plugin_unlock(&lock);
249
}
250

Jean-Paul Saman's avatar
Jean-Paul Saman committed
251
vlcplugin_event_t *EventObj::find_event(const char *s) const
252
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
253 254 255 256 257 258
    for( int i = 0; i < ARRAY_SIZE(vlcevents); i++ )
    {
        if( strncmp(vlcevents[i].name, s, strlen(vlcevents[i].name)) == 0 )
            return &vlcevents[i];
    }
    return NULL;
259 260
}

Jean-Paul Saman's avatar
Jean-Paul Saman committed
261
const char *EventObj::find_name(const libvlc_event_t *event)
262
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
263 264 265 266 267 268
    for( int i = 0; i < ARRAY_SIZE(vlcevents); i++ )
    {
        if( vlcevents[i].libvlc_type == event->type )
            return vlcevents[i].name;
    }
    return NULL;
269 270
}

Jean-Paul Saman's avatar
Jean-Paul Saman committed
271
bool EventObj::insert(const NPString &name, NPObject *listener, bool bubble)
272
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
273 274
    vlcplugin_event_t *event = find_event(name.UTF8Characters);
    if( !event )
275 276
        return false;

Jean-Paul Saman's avatar
Jean-Paul Saman committed
277 278 279
    lr_l::iterator iter;
    for( iter = _llist.begin(); iter != _llist.end(); ++iter )
        if( iter->listener() == listener && iter->bubble() == bubble )
280 281
            break;

Jean-Paul Saman's avatar
Jean-Paul Saman committed
282 283 284 285
    if( iter == _llist.end() )
    {
        _llist.push_back(Listener(event, listener, bubble));
        return true;
286 287
    }

Jean-Paul Saman's avatar
Jean-Paul Saman committed
288 289
    return false;
}
290

Jean-Paul Saman's avatar
Jean-Paul Saman committed
291
bool EventObj::remove(const NPString &name, NPObject *listener, bool bubble)
292
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
293 294
    vlcplugin_event_t *event = find_event(name.UTF8Characters);
    if( !event )
295 296
        return false;

Jean-Paul Saman's avatar
Jean-Paul Saman committed
297
    for( lr_l::iterator iter = _llist.begin(); iter !=_llist.end(); iter++ )
298
    {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
299 300 301
        if( iter->event_type() == event->libvlc_type &&
            iter->listener() == listener &&
            iter->bubble() == bubble )
302
        {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
303 304
            iter = _llist.erase(iter);
            return true;
305 306
        }
    }
307

Jean-Paul Saman's avatar
Jean-Paul Saman committed
308
    return false;
309 310
}

Jean-Paul Saman's avatar
Jean-Paul Saman committed
311
void EventObj::hook_manager( libvlc_event_manager_t *em, void *userdata )
312
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
313 314 315 316 317 318 319 320 321 322 323 324
    _em = em;

    if( _em )
    {
        /* attach all libvlc events we care about */
        for( int i = 0; i < ARRAY_SIZE(vlcevents); i++ )
        {
            libvlc_event_attach( _em, vlcevents[i].libvlc_type,
                                      vlcevents[i].libvlc_callback,
                                      userdata );
        }
    }
325 326
}

Jean-Paul Saman's avatar
Jean-Paul Saman committed
327
void EventObj::unhook_manager( void *userdata )
328
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
329 330 331 332 333 334 335 336 337 338
    if( _em )
    {
		/* detach all libvlc events we cared about */
        for( int i = 0; i < ARRAY_SIZE(vlcevents); i++ )
        {
            libvlc_event_detach( _em, vlcevents[i].libvlc_type,
                                      vlcevents[i].libvlc_callback,
                                      userdata );
        }
    }
339 340
}

Jean-Paul Saman's avatar
Jean-Paul Saman committed
341
/*****************************************************************************
342
 * VlcPluginBase constructor and destructor
Jean-Paul Saman's avatar
Jean-Paul Saman committed
343
 *****************************************************************************/
344
VlcPluginBase::VlcPluginBase( NPP instance, NPuint16_t mode ) :
Jean-Paul Saman's avatar
Jean-Paul Saman committed
345 346 347 348 349 350 351 352 353 354 355 356 357
    i_npmode(mode),
    b_stream(0),
    b_autoplay(1),
    b_toolbar(0),
    psz_text(NULL),
    psz_target(NULL),
    playlist_index(-1),
    libvlc_instance(NULL),
    libvlc_media_list(NULL),
    libvlc_media_player(NULL),
    p_scriptClass(NULL),
    p_browser(instance),
    psz_baseURL(NULL)
358
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
359
    memset(&npwindow, 0, sizeof(NPWindow));
360 361
}

Jean-Paul Saman's avatar
Jean-Paul Saman committed
362 363 364 365 366
static bool boolValue(const char *value) {
    return ( !strcmp(value, "1") ||
             !strcasecmp(value, "true") ||
             !strcasecmp(value, "yes") );
}
367

368
void VlcPluginBase::eventAsync(void *param)
369
{
370
    VlcPluginBase *plugin = (VlcPluginBase*)param;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
371
    plugin->events.deliver(plugin->getBrowser());
372
    plugin->update_controls();
373 374
}

375 376
void VlcPluginBase::event_callback(const libvlc_event_t* event,
                NPVariant *npparams, uint32_t npcount)
Jean-Paul Saman's avatar
Jean-Paul Saman committed
377
{
378 379 380
#ifdef XP_UNIX
    events.callback(event, npparams, npcount);
    NPN_PluginThreadAsyncCall(getBrowser(), eventAsync, this);
Jean-Paul Saman's avatar
Jean-Paul Saman committed
381
#else
382 383 384
#ifdef _MSC_VER
#pragma message("NPN_PluginThreadAsyncCall not implemented yet.")
#else
Jean-Paul Saman's avatar
Jean-Paul Saman committed
385
#warning NPN_PluginThreadAsyncCall not implemented yet.
386
#endif //_MSC_VER
Jean-Paul Saman's avatar
Jean-Paul Saman committed
387 388 389
    printf("No NPN_PluginThreadAsyncCall(), doing nothing.\n");
#endif
}
390

391
NPError VlcPluginBase::init(int argc, char* const argn[], char* const argv[])
392
{
393
    /* prepare VLC command line */
394
    const char *ppsz_argv[32];
395
    int ppsz_argc = 0;
396

397 398 399 400
#ifndef NDEBUG
    ppsz_argv[ppsz_argc++] = "--no-plugins-cache";
#endif

401 402
    /* locate VLC module path */
#ifdef XP_MACOSX
403
    ppsz_argv[ppsz_argc++] = "--plugin-path=/Library/Internet\\ Plug-Ins/VLC\\ Plugin.plugin/Contents/MacOS/plugins";
404
    ppsz_argv[ppsz_argc++] = "--vout=minimal_macosx";
405 406 407 408 409 410
#elif defined(XP_WIN)
    HKEY h_key;
    DWORD i_type, i_data = MAX_PATH + 1;
    char p_data[MAX_PATH + 1];
    if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, "Software\\VideoLAN\\VLC",
                      0, KEY_READ, &h_key ) == ERROR_SUCCESS )
411
    {
412 413 414 415 416
         if( RegQueryValueEx( h_key, "InstallDir", 0, &i_type,
                              (LPBYTE)p_data, &i_data ) == ERROR_SUCCESS )
         {
             if( i_type == REG_SZ )
             {
417
                 strcat( p_data, "\\plugins" );
418 419
                 ppsz_argv[ppsz_argc++] = "--plugin-path";
                 ppsz_argv[ppsz_argc++] = p_data;
420 421 422
             }
         }
         RegCloseKey( h_key );
423
    }
424
    ppsz_argv[ppsz_argc++] = "--no-one-instance";
425

426
#endif /* XP_MACOSX */
427

428 429 430 431
    /* common settings */
    ppsz_argv[ppsz_argc++] = "-vv";
    ppsz_argv[ppsz_argc++] = "--no-stats";
    ppsz_argv[ppsz_argc++] = "--no-media-library";
432
    ppsz_argv[ppsz_argc++] = "--intf=dummy";
433
    ppsz_argv[ppsz_argc++] = "--no-video-title-show";
Christophe Mutricy's avatar
Christophe Mutricy committed
434
    ppsz_argv[ppsz_argc++] = "--no-xlib";
435

436
    const char *progid = NULL;
437 438

    /* parse plugin arguments */
439
    for( int i = 0; (i < argc) && (ppsz_argc < 32); i++ )
440
    {
441
       /* fprintf(stderr, "argn=%s, argv=%s\n", argn[i], argv[i]); */
442 443 444 445 446 447 448 449

        if( !strcmp( argn[i], "target" )
         || !strcmp( argn[i], "mrl")
         || !strcmp( argn[i], "filename")
         || !strcmp( argn[i], "src") )
        {
            psz_target = argv[i];
        }
450 451
        else if( !strcmp( argn[i], "text" ) )
        {
452
            free( psz_text );
453 454
            psz_text = strdup( argv[i] );
        }
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
        else if( !strcmp( argn[i], "autoplay")
              || !strcmp( argn[i], "autostart") )
        {
            b_autoplay = boolValue(argv[i]);
        }
        else if( !strcmp( argn[i], "fullscreen" ) )
        {
            if( boolValue(argv[i]) )
            {
                ppsz_argv[ppsz_argc++] = "--fullscreen";
            }
            else
            {
                ppsz_argv[ppsz_argc++] = "--no-fullscreen";
            }
        }
        else if( !strcmp( argn[i], "mute" ) )
        {
            if( boolValue(argv[i]) )
            {
475
                ppsz_argv[ppsz_argc++] = "--volume=0";
476 477 478 479 480 481 482 483 484
            }
        }
        else if( !strcmp( argn[i], "loop")
              || !strcmp( argn[i], "autoloop") )
        {
            if( boolValue(argv[i]) )
            {
                ppsz_argv[ppsz_argc++] = "--loop";
            }
485 486
            else
            {
487 488 489
                ppsz_argv[ppsz_argc++] = "--no-loop";
            }
        }
490 491
        else if( !strcmp( argn[i], "version")
              || !strcmp( argn[i], "progid") )
492
        {
493
            progid = argv[i];
494
        }
495
        else if( !strcmp( argn[i], "toolbar" ) )
496
        {
497
            b_toolbar = boolValue(argv[i]);
498
        }
499 500
    }

501
    libvlc_instance = libvlc_new(ppsz_argc, ppsz_argv);
502 503
    if( !libvlc_instance )
        return NPERR_GENERIC_ERROR;
504
    libvlc_media_list = libvlc_media_list_new(libvlc_instance);
505 506 507 508 509 510

    /*
    ** fetch plugin base URL, which is the URL of the page containing the plugin
    ** this URL is used for making absolute URL from relative URL that may be
    ** passed as an MRL argument
    */
Jean-Paul Saman's avatar
Jean-Paul Saman committed
511
    NPObject *plugin = NULL;
512 513 514 515 516 517 518 519 520 521

    if( NPERR_NO_ERROR == NPN_GetValue(p_browser, NPNVWindowNPObject, &plugin) )
    {
        /*
        ** is there a better way to get that info ?
        */
        static const char docLocHref[] = "document.location.href";
        NPString script;
        NPVariant result;

522 523
        script.UTF8Characters = docLocHref;
        script.UTF8Length = sizeof(docLocHref)-1;
524 525 526 527 528 529 530

        if( NPN_Evaluate(p_browser, plugin, &script, &result) )
        {
            if( NPVARIANT_IS_STRING(result) )
            {
                NPString &location = NPVARIANT_TO_STRING(result);

531
                psz_baseURL = (char *) malloc(location.UTF8Length+1);
532 533
                if( psz_baseURL )
                {
534 535
                    strncpy(psz_baseURL, location.UTF8Characters, location.UTF8Length);
                    psz_baseURL[location.UTF8Length] = '\0';
536 537 538 539 540 541 542 543 544 545
                }
            }
            NPN_ReleaseVariantValue(&result);
        }
        NPN_ReleaseObject(plugin);
    }

    if( psz_target )
    {
        // get absolute URL from src
546 547
        char *psz_absurl = getAbsoluteURL(psz_target);
        psz_target = psz_absurl ? psz_absurl : strdup(psz_target);
548 549 550
    }

    /* assign plugin script root class */
551 552
    /* new APIs */
    p_scriptClass = RuntimeNPClass<LibvlcRootNPObject>::getClass();
553

554
    if( !events.init() )
555 556
        return NPERR_GENERIC_ERROR;

557
    return NPERR_NO_ERROR;
558 559
}

560
VlcPluginBase::~VlcPluginBase()
561
{
562 563
    free(psz_baseURL);
    free(psz_target);
564
    free(psz_text);
Jean-Paul Saman's avatar
Jean-Paul Saman committed
565

566
    if( libvlc_media_player )
567
    {
568 569
        if( playlist_isplaying() )
            playlist_stop();
Jean-Paul Saman's avatar
Jean-Paul Saman committed
570
        events.unhook_manager( this );
571
        libvlc_media_player_release( libvlc_media_player );
572
    }
573 574
    if( libvlc_media_list )
        libvlc_media_list_release( libvlc_media_list );
575
    if( libvlc_instance )
Jean-Paul Saman's avatar
Jean-Paul Saman committed
576
        libvlc_release( libvlc_instance );
577 578
}

579
void VlcPluginBase::setWindow(const NPWindow &window)
580 581 582 583
{
    npwindow = window;
};

584
/*****************************************************************************
585
 * VlcPluginBase playlist replacement methods
586
 *****************************************************************************/
587
int VlcPluginBase::playlist_add( const char *mrl )
588 589
{
    int item = -1;
590
    libvlc_media_t *p_m = libvlc_media_new_location(libvlc_instance,mrl);
591
    if( !p_m )
592
        return -1;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
593
    assert( libvlc_media_list );
594
    libvlc_media_list_lock(libvlc_media_list);
595
    if( !libvlc_media_list_add_media(libvlc_media_list,p_m) )
596
        item = libvlc_media_list_count(libvlc_media_list)-1;
597 598 599 600 601 602 603
    libvlc_media_list_unlock(libvlc_media_list);

    libvlc_media_release(p_m);

    return item;
}

604
int VlcPluginBase::playlist_add_extended_untrusted( const char *mrl, const char *name,
605
                    int optc, const char **optv )
606
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
607
    libvlc_media_t *p_m;
608
    int item = -1;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
609 610 611

    assert( libvlc_media_list );

612
    p_m = libvlc_media_new_location(libvlc_instance, mrl);
613
    if( !p_m )
614 615 616
        return -1;

    for( int i = 0; i < optc; ++i )
617
        libvlc_media_add_option_flag(p_m, optv[i], libvlc_media_option_unique);
618 619

    libvlc_media_list_lock(libvlc_media_list);
620
    if( !libvlc_media_list_add_media(libvlc_media_list,p_m) )
621
        item = libvlc_media_list_count(libvlc_media_list)-1;
622 623 624 625 626 627
    libvlc_media_list_unlock(libvlc_media_list);
    libvlc_media_release(p_m);

    return item;
}

628
bool VlcPluginBase::playlist_select( int idx )
629 630 631
{
    libvlc_media_t *p_m = NULL;

Jean-Paul Saman's avatar
Jean-Paul Saman committed
632 633
    assert( libvlc_media_list );

634 635
    libvlc_media_list_lock(libvlc_media_list);

636
    int count = libvlc_media_list_count(libvlc_media_list);
637 638 639 640 641
    if( idx<0||idx>=count )
        goto bad_unlock;

    playlist_index = idx;

642
    p_m = libvlc_media_list_item_at_index(libvlc_media_list,playlist_index);
643 644
    libvlc_media_list_unlock(libvlc_media_list);

645
    if( !p_m )
646 647 648 649
        return false;

    if( libvlc_media_player )
    {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
650 651
        if( playlist_isplaying() )
            playlist_stop();
Jean-Paul Saman's avatar
Jean-Paul Saman committed
652
        events.unhook_manager( this );
653 654 655 656
        libvlc_media_player_release( libvlc_media_player );
        libvlc_media_player = NULL;
    }

Jean-Paul Saman's avatar
Jean-Paul Saman committed
657
    libvlc_media_player = libvlc_media_player_new_from_media( p_m );
658
    if( libvlc_media_player )
659
    {
660
        set_player_window();
Jean-Paul Saman's avatar
Jean-Paul Saman committed
661 662 663 664

        libvlc_event_manager_t *p_em;
        p_em = libvlc_media_player_event_manager( libvlc_media_player );
        events.hook_manager( p_em, this );
665 666
    }

667
    libvlc_media_release( p_m );
668
    return true;
669 670

bad_unlock:
Jean-Paul Saman's avatar
Jean-Paul Saman committed
671
    libvlc_media_list_unlock( libvlc_media_list );
672 673 674
    return false;
}

675
int VlcPluginBase::playlist_delete_item( int idx )
676
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
677 678
    if( !libvlc_media_list )
        return -1;
679
    libvlc_media_list_lock(libvlc_media_list);
680
    int ret = libvlc_media_list_remove_index(libvlc_media_list,idx);
681
    libvlc_media_list_unlock(libvlc_media_list);
682
    return ret;
683 684
}

685
void VlcPluginBase::playlist_clear()
686 687 688
{
    if( libvlc_media_list )
        libvlc_media_list_release(libvlc_media_list);
689
    libvlc_media_list = libvlc_media_list_new(getVLC());
690 691
}

692
int VlcPluginBase::playlist_count()
693 694
{
    int items_count = 0;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
695 696
    if( !libvlc_media_list )
        return items_count;
697
    libvlc_media_list_lock(libvlc_media_list);
698
    items_count = libvlc_media_list_count(libvlc_media_list);
699 700 701 702 703
    libvlc_media_list_unlock(libvlc_media_list);
    return items_count;
}


704
bool  VlcPluginBase::player_has_vout()
705
{
Jean-Paul Saman's avatar
Jean-Paul Saman committed
706
    bool r = false;
707
    if( playlist_isplaying() )
708
        r = libvlc_media_player_has_vout(libvlc_media_player);
709 710 711
    return r;
}

712
/*****************************************************************************
713
 * VlcPluginBase methods
714
 *****************************************************************************/
715

716
char *VlcPluginBase::getAbsoluteURL(const char *url)
717
{
718
    if( NULL != url )
719
    {
720 721 722
        // check whether URL is already absolute
        const char *end=strchr(url, ':');
        if( (NULL != end) && (end != url) )
723
        {
724 725
            // validate protocol header
            const char *start = url;
726 727 728
            char c = *start;
            if( isalpha(c) )
            {
729
                ++start;
730 731 732 733 734 735 736 737 738 739 740 741 742 743
                while( start != end )
                {
                    c  = *start;
                    if( ! (isalnum(c)
                       || ('-' == c)
                       || ('+' == c)
                       || ('.' == c)
                       || ('/' == c)) ) /* VLC uses / to allow user to specify a demuxer */
                        // not valid protocol header, assume relative URL
                        goto relativeurl;
                    ++start;
                }
                /* we have a protocol header, therefore URL is absolute */
                return strdup(url);
744
            }
745
            // not a valid protocol header, assume relative URL
746
        }
747

748 749
relativeurl:

750 751 752
        if( psz_baseURL )
        {
            size_t baseLen = strlen(psz_baseURL);
Jean-Paul Saman's avatar
Jean-Paul Saman committed
753
            char *href = (char *) malloc(baseLen+strlen(url)+1);
754 755 756
            if( href )
            {
                /* prepend base URL */
JP Dinger's avatar
JP Dinger committed
757
                memcpy(href, psz_baseURL, baseLen+1);
758 759 760 761 762 763 764 765 766 767 768 769 770 771

                /*
                ** relative url could be empty,
                ** in which case return base URL
                */
                if( '\0' == *url )
                    return href;

                /*
                ** locate pathname part of base URL
                */

                /* skip over protocol part  */
                char *pathstart = strchr(href, ':');
JP Dinger's avatar
JP Dinger committed
772
                char *pathend = href+baseLen;
773
                if( pathstart )
774 775 776
                {
                    if( '/' == *(++pathstart) )
                    {
777 778 779 780 781 782 783 784 785 786 787 788
                        if( '/' == *(++pathstart) )
                        {
                            ++pathstart;
                        }
                    }
                    /* skip over host part */
                    pathstart = strchr(pathstart, '/');
                    if( ! pathstart )
                    {
                        // no path, add a / past end of url (over '\0')
                        pathstart = pathend;
                        *pathstart = '/';
789 790
                    }
                }
791
                else
792
                {
793 794 795 796
                    /* baseURL is just a UNIX path */
                    if( '/' != *href )
                    {
                        /* baseURL is not an absolute path */
Jean-Paul Saman's avatar
Jean-Paul Saman committed
797
                        free(href);
798 799 800
                        return NULL;
                    }
                    pathstart = href;
801 802 803 804 805 806 807 808 809 810
                }

                /* relative URL made of an absolute path ? */
                if( '/' == *url )
                {
                    /* replace path completely */
                    strcpy(pathstart, url);
                    return href;
                }

811
                /* find last path component and replace it */
812 813
                while( '/' != *pathend)
                    --pathend;
814 815 816 817 818 819 820 821 822 823 824 825

                /*
                ** if relative url path starts with one or more '../',
                ** factor them out of href so that we return a
                ** normalized URL
                */
                while( pathend != pathstart )
                {
                    const char *p = url;
                    if( '.' != *p )
                        break;
                    ++p;
826 827 828 829
                    if( '\0' == *p  )
                    {
                        /* relative url is just '.' */
                        url = p;
830
                        break;
831 832 833 834 835 836 837
                    }
                    if( '/' == *p  )
                    {
                        /* relative url starts with './' */
                        url = ++p;
                        continue;
                    }
838
                    if( '.' != *p )
839 840
                        break;
                    ++p;
841 842 843 844 845 846
                    if( '\0' == *p )
                    {
                        /* relative url is '..' */
                    }
                    else
                    {
847
                        if( '/' != *p )
848 849 850 851
                            break;
                        /* relative url starts with '../' */
                        ++p;
                    }
852
                    url = p;
853 854 855 856 857
                    do
                    {
                        --pathend;
                    }
                    while( '/' != *pathend );
858
                }
859 860
                /* skip over '/' separator */
                ++pathend;
861
                /* concatenate remaining base URL and relative URL */
862
                strcpy(pathend, url);
863 864 865
            }
            return href;
        }
866
    }
867 868
    return NULL;
}
869

870
void VlcPluginBase::control_handler(vlc_toolbar_clicked_t clicked)
871
{
872
    switch( clicked )
873
    {
874 875 876 877 878
        case clicked_Play:
        {
            playlist_play();
        }
        break;
879

880 881 882 883 884
        case clicked_Pause:
        {
            playlist_pause();
        }
        break;
885

886 887 888 889 890
        case clicked_Stop:
        {
            playlist_stop();
        }
        break;
891

892 893
        case clicked_Fullscreen:
        {
894
            toggle_fullscreen();
895 896
        }
        break;
897

898 899 900 901 902 903 904 905 906
        case clicked_Mute:
        case clicked_Unmute:
#if 0
        {
            if( p_md )
                libvlc_audio_toggle_mute( p_md );
        }
#endif
        break;
907

908 909 910 911 912 913 914 915
        case clicked_timeline:
#if 0
        {
            /* if a movie is loaded */
            if( p_md )
            {
                int64_t f_length;
                f_length = libvlc_media_player_get_length( p_md ) / 100;
916

917 918
                f_length = (float)f_length *
                        ( ((float)i_xPos-4.0 ) / ( ((float)i_width-8.0)/100) );
919

920 921 922
                libvlc_media_player_set_time( p_md, f_length );
            }
        }
Jean-Paul Saman's avatar
Jean-Paul Saman committed
923
#endif
924
        break;
925

926 927 928 929 930
        case clicked_Time:
        {
            /* Not implemented yet*/
        }
        break;
931

932 933 934 935
        default: /* button_Unknown */
            fprintf(stderr, "button Unknown!\n");
        break;
    }
936
}
937 938 939 940

// Verifies the version of the NPAPI.
// The eventListeners use a NPAPI function available
// since Gecko 1.9.
941
bool VlcPluginBase::canUseEventListener()
942 943 944 945 946 947 948 949 950 951 952
{
    int plugin_major, plugin_minor;
    int browser_major, browser_minor;

    NPN_Version(&plugin_major, &plugin_minor,
                &browser_major, &browser_minor);

    if (browser_minor >= 19 || browser_major > 0)
        return true;
    return false;
}