aboutsummaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/jogamp/opengl/util/av/GLMediaPlayerImpl.java
blob: a82c84d171ce6808935bd1611400174f1d84453a (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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
/**
 * Copyright 2012 JogAmp Community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of JogAmp Community.
 */
package jogamp.opengl.util.av;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;

import javax.media.nativewindow.AbstractGraphicsDevice;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLDrawable;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.GLES2;
import javax.media.opengl.GLException;
import javax.media.opengl.GLProfile;

import com.jogamp.common.os.Platform;
import com.jogamp.opengl.util.av.AudioSink;
import com.jogamp.opengl.util.av.AudioSink.AudioFrame;
import com.jogamp.opengl.util.av.GLMediaPlayer;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureSequence;

/**
 * After object creation an implementation may customize the behavior:
 * <ul>
 *   <li>{@link #setDesTextureCount(int)}</li>
 *   <li>{@link #setTextureTarget(int)}</li>
 *   <li>{@link EGLMediaPlayerImpl#setEGLTexImageAttribs(boolean, boolean)}.</li>
 * </ul>
 * 
 * <p>
 * See {@link GLMediaPlayer}.
 * </p>
 */
public abstract class GLMediaPlayerImpl implements GLMediaPlayer {

    protected static final String unknown = "unknown";

    /** Default texture count w/o threading, value {@value}. */
    protected static final int TEXTURE_COUNT_DEFAULT = 2;
    
    protected volatile State state;
    private Object stateLock = new Object();
    
    protected int textureCount;
    protected int textureTarget;
    protected int textureFormat;
    protected int textureInternalFormat; 
    protected int textureType;
    protected int texUnit;
    
    
    protected int[] texMinMagFilter = { GL.GL_NEAREST, GL.GL_NEAREST };
    protected int[] texWrapST = { GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE };
    
    protected URI streamLoc = null;
    
    protected volatile float playSpeed = 1.0f;
    
    /** Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int vid = GLMediaPlayer.STREAM_ID_AUTO;
    /** Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int aid = GLMediaPlayer.STREAM_ID_AUTO;
    /** Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int width = 0;
    /** Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int height = 0;
    /** Video avg. fps. Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected float fps = 0;
    /** Video avg. frame duration in ms. Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected float frame_duration = 0f;
    /** Stream bps. Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int bps_stream = 0;
    /** Video bps. Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int bps_video = 0;
    /** Audio bps. Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int bps_audio = 0;
    /** In frames. Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int videoFrames = 0;
    /** In frames. Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int audioFrames = 0;
    /** In ms. Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected int duration = 0;
    /** Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected String acodec = unknown;
    /** Shall be set by the {@link #initGLStreamImpl(GL, int, int)} method implementation. */
    protected String vcodec = unknown;
    
    protected volatile int decodedFrameCount = 0;
    protected int presentedFrameCount = 0;
    protected int displayedFrameCount = 0;
    protected volatile int video_pts_last = 0;
    
    /** See {@link #getAudioSink()}. Set by implementation if used from within {@link #initGLStreamImpl(GL, int, int)}! */
    protected AudioSink audioSink = null;
    protected boolean audioSinkPlaySpeedSet = false;
    
    /** System Clock Reference (SCR) of first audio PTS at start time. */
    private long audio_scr_t0 = 0;
    private boolean audioSCR_reset = true;
    
    /** System Clock Reference (SCR) of first video frame at start time. */
    private long video_scr_t0 = 0;
    /** System Clock Reference (SCR) PTS offset, i.e. first video PTS at start time. */
    private int video_scr_pts = 0;
    /** Cumulative video pts diff. */
    private float video_dpts_cum = 0;
    /** Cumulative video frames. */
    private int video_dpts_count = 0;
    /** Number of min frame count required for video cumulative sync. */ 
    private static final int VIDEO_DPTS_NUM = 20;
    /** Cumulative coefficient, value {@value}. */
    private static final float VIDEO_DPTS_COEFF = 0.7943282f; // (float) Math.exp(Math.log(0.01) / VIDEO_DPTS_NUM);
    /** Maximum valid video pts diff. */
    private static final int VIDEO_DPTS_MAX = 5000; // 5s max diff
    /** Trigger video PTS reset with given cause as bitfield. */
    private boolean videoSCR_reset = false;
    
    protected SyncedRingbuffer<TextureFrame> videoFramesFree =  null;
    protected SyncedRingbuffer<TextureFrame> videoFramesDecoded =  null;
    protected volatile TextureFrame lastFrame = null;

    private ArrayList<GLMediaEventListener> eventListeners = new ArrayList<GLMediaEventListener>();

    protected GLMediaPlayerImpl() {
        this.textureCount=0;
        this.textureTarget=GL.GL_TEXTURE_2D;
        this.textureFormat = GL.GL_RGBA;
        this.textureInternalFormat = GL.GL_RGBA;
        this.textureType = GL.GL_UNSIGNED_BYTE;        
        this.texUnit = 0;
        this.state = State.Uninitialized;
    }

    @Override
    public final void setTextureUnit(int u) { texUnit = u; }
    
    @Override
    public final int getTextureUnit() { return texUnit; }
    
    @Override
    public final int getTextureTarget() { return textureTarget; }
    
    @Override
    public final int getTextureCount() { return textureCount; }
    
    protected final void setTextureTarget(int target) { textureTarget=target; }
    protected final void setTextureFormat(int internalFormat, int format) { 
        textureInternalFormat=internalFormat; 
        textureFormat=format; 
    }    
    protected final void setTextureType(int t) { textureType=t; }

    public final void setTextureMinMagFilter(int[] minMagFilter) { texMinMagFilter[0] = minMagFilter[0]; texMinMagFilter[1] = minMagFilter[1];}
    public final int[] getTextureMinMagFilter() { return texMinMagFilter; }
    
    public final void setTextureWrapST(int[] wrapST) { texWrapST[0] = wrapST[0]; texWrapST[1] = wrapST[1];}
    public final int[] getTextureWrapST() { return texWrapST; }    
    
    @Override
    public String getRequiredExtensionsShaderStub() throws IllegalStateException {
        if(State.Uninitialized == state) {
            throw new IllegalStateException("Instance not initialized: "+this);
        }
        if(GLES2.GL_TEXTURE_EXTERNAL_OES == textureTarget) {
            return TextureSequence.GL_OES_EGL_image_external_Required_Prelude;
        }
        return "";
    }
        
    @Override
    public String getTextureSampler2DType() throws IllegalStateException {
        if(State.Uninitialized == state) {
            throw new IllegalStateException("Instance not initialized: "+this);
        }
        switch(textureTarget) {
            case GL.GL_TEXTURE_2D:
            case GL2.GL_TEXTURE_RECTANGLE: 
                return TextureSequence.sampler2D;
            case GLES2.GL_TEXTURE_EXTERNAL_OES:
                return TextureSequence.samplerExternalOES;
            default:
                throw new GLException("Unsuported texture target: "+toHexString(textureTarget));            
        }
    }
    
    /**
     * {@inheritDoc}
     * 
     * This implementation simply returns the build-in function name of <code>texture2D</code>,
     * if not overridden by specialization.
     */
    @Override
    public String getTextureLookupFunctionName(String desiredFuncName) throws IllegalStateException {
        if(State.Uninitialized == state) {
            throw new IllegalStateException("Instance not initialized: "+this);
        }
        return "texture2D";
    }
    
    /**
     * {@inheritDoc}
     * 
     * This implementation simply returns an empty string since it's using 
     * the build-in function <code>texture2D</code>,
     * if not overridden by specialization.
     */
    @Override
    public String getTextureLookupFragmentShaderImpl() throws IllegalStateException {
        if(State.Uninitialized == state) {
            throw new IllegalStateException("Instance not initialized: "+this);
        }
        return ""; 
    }
    
    @Override
    public final int getDecodedFrameCount() { return decodedFrameCount; }
    
    @Override
    public final int getPresentedFrameCount() { return this.presentedFrameCount; }
    
    @Override
    public final int getVideoPTS() { return video_pts_last; }
    
    @Override
    public final int getAudioPTS() { 
        if( State.Uninitialized != state ) {
            return getAudioPTSImpl();
        }
        return 0;
    }
    /** Override if not using audioSink! */
    protected int getAudioPTSImpl() {
        if( null != audioSink ) {
            return audioSink.getPTS();
        } else {
            return 0;
        }
    }
    
    public final State getState() { return state; }
    
    public final State play() {
        synchronized( stateLock ) {
            switch( state ) {
                case Paused:
                    if( playImpl() ) {
                        // FIXME
                        resetAudioVideoPTS();
                        if( null != audioSink ) {
                            audioSink.play(); // cont. w/ new data
                        }                        
                        resumeFramePusher();
                        state = State.Playing;
                    }
                default:
            }
            if(DEBUG) { System.err.println("Play: "+toString()); }
            return state;
        }
    }
    protected abstract boolean playImpl();
    
    public final State pause() {
        synchronized( stateLock ) {
            if( State.Playing == state ) {
                state = State.Paused;
                // FIXME
                pauseFramePusher();
                if( null != audioSink ) {
                    audioSink.pause();
                }
                if( !pauseImpl() ) {
                    play();
                }
            }
            if(DEBUG) { System.err.println("Pause: "+toString()); }            
            return state;
        }
    }
    protected abstract boolean pauseImpl();
    
    public final int seek(int msec) {
        synchronized( stateLock ) {
            final int pts1;
            switch(state) {
                case Playing:
                case Paused:
                    final State _state = state;
                    state = State.Paused;
                    // FIXME
                    pauseFramePusher();
                    pts1 = seekImpl(msec);
                    resetAllAudioVideoSync();
                    if( null != audioSink && State.Playing == _state ) {
                        audioSink.play(); // cont. w/ new data
                    }
                    resumeFramePusher();
                    state = _state;
                    break;
                default:
                    pts1 = 0;
            }
            if(DEBUG) { System.err.println("Seek("+msec+"): "+toString()); }
            return pts1;
        }
    }
    protected abstract int seekImpl(int msec);
    
    @Override
    public final float getPlaySpeed() {
        return playSpeed;
    }
    
    @Override
    public final boolean setPlaySpeed(float rate) {
        synchronized( stateLock ) {
            boolean res = false;
            if(State.Uninitialized != state ) {
                if( rate > 0.01f ) {
                    if( Math.abs(1.0f - rate) < 0.01f ) {
                        rate = 1.0f;
                    }
                    if( setPlaySpeedImpl(rate) ) {
                        resetAudioVideoPTS();
                        playSpeed = rate;
                        if(DEBUG) { System.err.println("SetPlaySpeed: "+toString()); }
                        res = true;
                    }
                }
            }
            return res;
        }
    }
    /** 
     * Override if not using AudioSink, or AudioSink's {@link AudioSink#setPlaySpeed(float)} is not sufficient!
     * <p>
     * AudioSink shall respect <code>!audioSinkPlaySpeedSet</code> to determine data_size 
     * at {@link AudioSink#enqueueData(com.jogamp.opengl.util.av.AudioSink.AudioFrame)}.
     * </p> 
     */
    protected boolean setPlaySpeedImpl(float rate) {
        if( null != audioSink ) {
            audioSinkPlaySpeedSet = audioSink.setPlaySpeed(rate);
        }
        // still true, even if audioSink rejects command since we deal w/ video sync 
        // and AudioSink w/ audioSinkPlaySpeedSet at enqueueData(..).
        return true;
    }

    @Override
    public final State initGLStream(GL gl, int reqTextureCount, URI streamLoc, int vid, int aid) throws IllegalStateException, GLException, IOException {
        synchronized( stateLock ) {
            if(State.Uninitialized != state) {
                throw new IllegalStateException("Instance not in state "+State.Uninitialized+", but "+state+", "+this);
            }
            decodedFrameCount = 0;
            presentedFrameCount = 0;
            displayedFrameCount = 0;
            this.streamLoc = streamLoc;
            if (this.streamLoc != null) {
                try {                
                    if( null != gl ) {
                        removeAllTextureFrames(gl);
                        textureCount = validateTextureCount(reqTextureCount);
                        if( textureCount < TEXTURE_COUNT_DEFAULT ) {
                            throw new InternalError("Validated texture count < "+TEXTURE_COUNT_DEFAULT+": "+textureCount);
                        }
                        initGLStreamImpl(gl, vid, aid); // also initializes width, height, .. etc
                        videoFramesFree = new SyncedRingbuffer<TextureFrame>(createTexFrames(gl, textureCount), true /* full */);
                        if( TEXTURE_COUNT_DEFAULT < textureCount ) {
                            videoFramesDecoded = new SyncedRingbuffer<TextureFrame>(new TextureFrame[textureCount], false /* full */);
                            framePusher = new FramePusher(gl);
                            framePusher.doStart();
                        } else {
                            videoFramesDecoded = null;
                        }
                        lastFrame = videoFramesFree.getBlocking(false /* clearRef */ );
                        state = State.Paused;
                    }
                    return state;
                } catch (Throwable t) {
                    throw new GLException("Error initializing GL resources", t);
                }
            }
            return state;
        }
    }
    /**
     * Implementation shall set the following set of data here
     * @see #vid
     * @see #aid 
     * @see #width
     * @see #height
     * @see #fps
     * @see #bps_stream
     * @see #videoFrames
     * @see #audioFrames
     * @see #acodec
     * @see #vcodec
    */
    protected abstract void initGLStreamImpl(GL gl, int vid, int aid) throws IOException;
    
    /** 
     * Returns the validated number of textures to be handled.
     * <p>
     * Default is 2 textures w/o threading, last texture and the decoding texture. 
     * </p>
     * <p>
     * &gt; 2 textures is used for threaded decoding, a minimum of 4 textures seems reasonable in this case.
     * </p>
     */
    protected int validateTextureCount(int desiredTextureCount) {
        return TEXTURE_COUNT_DEFAULT;
    }
    
    private final TextureFrame[] createTexFrames(GL gl, final int count) {
        final int[] texNames = new int[count];
        gl.glGenTextures(count, texNames, 0);
        final int err = gl.glGetError();
        if( GL.GL_NO_ERROR != err ) {
            throw new RuntimeException("TextureNames creation failed (num: "+count+"): err "+toHexString(err));
        }
        final TextureFrame[] texFrames = new TextureFrame[count];
        for(int i=0; i<count; i++) {
            texFrames[i] = createTexImage(gl, texNames[i]);
        }
        return texFrames;
    }
    protected abstract TextureFrame createTexImage(GL gl, int texName);
    
    protected final Texture createTexImageImpl(GL gl, int texName, int tWidth, int tHeight, boolean mustFlipVertically) {
        if( 0 > texName ) {
            throw new RuntimeException("TextureName "+toHexString(texName)+" invalid.");
        }
        gl.glActiveTexture(GL.GL_TEXTURE0+getTextureUnit());
        gl.glBindTexture(textureTarget, texName);
        {
            final int err = gl.glGetError();
            if( GL.GL_NO_ERROR != err ) {
                throw new RuntimeException("Couldn't bind textureName "+toHexString(texName)+" to 2D target, err "+toHexString(err));
            }
        }

        if(GLES2.GL_TEXTURE_EXTERNAL_OES != textureTarget) {
            // create space for buffer with a texture
            gl.glTexImage2D(
                    textureTarget,    // target
                    0,                // level
                    textureInternalFormat, // internal format
                    tWidth,           // width
                    tHeight,          // height
                    0,                // border
                    textureFormat,
                    textureType,
                    null);            // pixels -- will be provided later
            {
                final int err = gl.glGetError();
                if( GL.GL_NO_ERROR != err ) {
                    throw new RuntimeException("Couldn't create TexImage2D RGBA "+tWidth+"x"+tHeight+", err "+toHexString(err));
                }
            }
            if(DEBUG) {
                System.err.println("Created TexImage2D RGBA "+tWidth+"x"+tHeight+", target "+toHexString(textureTarget)+
                                   ", ifmt "+toHexString(GL.GL_RGBA)+", fmt "+toHexString(textureFormat)+", type "+toHexString(textureType));
            }
        }
        gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MIN_FILTER, texMinMagFilter[0]);
        gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MAG_FILTER, texMinMagFilter[1]);        
        gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_WRAP_S, texWrapST[0]);
        gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_WRAP_T, texWrapST[1]);
        
        return com.jogamp.opengl.util.texture.TextureIO.newTexture(
                     texName, textureTarget,
                     tWidth, tHeight,
                     width,  height,
                     mustFlipVertically);        
    }
        
    protected void destroyTexFrame(GL gl, TextureFrame frame) {
        frame.getTexture().destroy(gl);        
    }

    @Override
    public final TextureFrame getLastTexture() throws IllegalStateException {
        if(State.Uninitialized == state) {
            throw new IllegalStateException("Instance not initialized: "+this);
        }
        return lastFrame;
    }
    
    private final void removeAllTextureFrames(GL gl) {
        if( null != videoFramesFree ) {
            final TextureFrame[] texFrames = videoFramesFree.getArray(); 
            videoFramesFree = null;
            videoFramesDecoded = null;
            lastFrame = null;
            for(int i=0; i<texFrames.length; i++) {
                final TextureFrame frame = texFrames[i];
                if(null != frame) {
                    destroyTexFrame(gl, frame);
                    texFrames[i] = null;
                }
                System.err.println(Thread.currentThread().getName()+"> Clear TexFrame["+i+"]: "+frame+" -> null");            
            }        
        }
        textureCount=0;
    }
    
    protected TextureFrame cachedFrame = null;
    protected long lastTimeMillis = 0;
    
    @Override
    public final TextureFrame getNextTexture(GL gl, boolean blocking) throws IllegalStateException {
        synchronized( stateLock ) {
            if(State.Uninitialized == state) {
                throw new IllegalStateException("Instance not initialized: "+this);
            }
            if(State.Playing == state) {
                TextureFrame nextFrame = null;
                boolean ok = true;
                boolean dropFrame = false;
                try {
                    do {
                        final long currentTimeMillis;
                        final boolean playCached = null != cachedFrame;
                        if( dropFrame ) {
                            presentedFrameCount--;
                            dropFrame = false;
                        }
                        if( playCached ) {
                            nextFrame = cachedFrame;
                            cachedFrame = null;
                            presentedFrameCount--;
                            currentTimeMillis = Platform.currentTimeMillis();
                        } else if( TEXTURE_COUNT_DEFAULT < textureCount ) {
                            nextFrame = videoFramesDecoded.getBlocking(false /* clearRef */ );
                            currentTimeMillis = Platform.currentTimeMillis();
                        } else {
                            nextFrame = videoFramesFree.getBlocking(false /* clearRef */ );
                            nextFrame.setPTS( TextureFrame.INVALID_PTS ); // mark invalid until processed!
                            ok = getNextTextureImpl(gl, nextFrame, blocking, true /* issuePreAndPost */);
                            currentTimeMillis = Platform.currentTimeMillis();
                            if( ok ) {
                                newFrameAvailable(nextFrame, currentTimeMillis);
                            }
                        }
                        if( ok ) {
                            presentedFrameCount++;
                            final int video_pts = nextFrame.getPTS();
                            if( video_pts != TextureFrame.INVALID_PTS ) {
                                final int audio_pts = getAudioPTSImpl();
                                final int audio_scr = (int) ( ( currentTimeMillis - audio_scr_t0 ) * playSpeed );
                                final int d_apts;
                                if( audio_pts != AudioFrame.INVALID_PTS ) {
                                    d_apts = audio_pts - audio_scr;
                                } else {
                                    d_apts = 0;
                                }
                                
                                final int frame_period_last = video_pts - video_pts_last; // rendering loop interrupted ?
                                if( videoSCR_reset || frame_period_last > frame_duration*10 ) {
                                    videoSCR_reset = false;
                                    video_scr_t0 = currentTimeMillis;
                                    video_scr_pts = video_pts;
                                }
                                final int video_scr = video_scr_pts + (int) ( ( currentTimeMillis - video_scr_t0 ) * playSpeed );
                                final int d_vpts = video_pts - video_scr;
                                // final int d_avpts = d_vpts - d_apts;
                                if( -VIDEO_DPTS_MAX > d_vpts || d_vpts > VIDEO_DPTS_MAX ) {
                                // if( -VIDEO_DPTS_MAX > d_avpts || d_avpts > VIDEO_DPTS_MAX ) {
                                    if( DEBUG ) {
                                        System.err.println( "AV*: dT "+(currentTimeMillis-lastTimeMillis)+", "+
                                                getPerfStringImpl( video_scr, video_pts, d_vpts, audio_scr, audio_pts, d_apts, 0 ) + ", "+nextFrame+", playCached " + playCached+ ", dropFrame "+dropFrame);
                                    }
                                } else {
                                    final int dpy_den = displayedFrameCount > 0 ? displayedFrameCount : 1;
                                    final int avg_dpy_duration = ( (int) ( currentTimeMillis - video_scr_t0 ) ) / dpy_den ; // ms/f
                                    final int maxVideoDelay = Math.min(avg_dpy_duration, MAXIMUM_VIDEO_ASYNC);
                                    video_dpts_count++;
                                    // video_dpts_cum = d_avpts + VIDEO_DPTS_COEFF * video_dpts_cum;
                                    video_dpts_cum = d_vpts + VIDEO_DPTS_COEFF * video_dpts_cum;
                                    final int video_dpts_avg_diff = video_dpts_count >= VIDEO_DPTS_NUM ? getVideoDPTSAvg() : 0;
                                    final int dt = (int) ( video_dpts_avg_diff / playSpeed + 0.5f );
                                    // final int dt = (int) ( d_vpts  / playSpeed + 0.5f );
                                    // final int dt = (int) ( d_avpts / playSpeed + 0.5f );
                                    if( dt > maxVideoDelay ) {
                                        cachedFrame = nextFrame;
                                        nextFrame = null;
                                    } else if ( dt < -maxVideoDelay ) {
                                        dropFrame = true;
                                    }
                                    video_pts_last = video_pts;
                                    if( DEBUG ) {
                                        System.err.println( "AV_: dT "+(currentTimeMillis-lastTimeMillis)+", "+
                                                getPerfStringImpl( video_scr, video_pts, d_vpts,
                                                                   audio_scr, audio_pts, d_apts,
                                                                   video_dpts_avg_diff ) + 
                                                                   ", avg dpy-fps "+avg_dpy_duration+" ms/f, maxD "+maxVideoDelay+" ms, "+nextFrame+", playCached " + playCached + ", dropFrame "+dropFrame);
                                    }
                                }
                            } else if( DEBUG ) {
                                System.err.println("Invalid PTS: "+nextFrame);
                            }
                            if( null != nextFrame ) {
                                final TextureFrame _lastFrame = lastFrame;
                                lastFrame = nextFrame;
                                videoFramesFree.putBlocking(_lastFrame);
                            }
                        }
                        lastTimeMillis = currentTimeMillis;
                    } while( dropFrame );
                } catch (InterruptedException e) {
                    ok = false;
                    e.printStackTrace();
                } finally {
                    if( !ok && null != nextFrame ) { // put back
                        if( !videoFramesFree.put(nextFrame) ) {
                            throw new InternalError("XXX: free "+videoFramesFree+", decoded "+videoFramesDecoded+", "+GLMediaPlayerImpl.this); 
                        }
                    }
                }
            }
            displayedFrameCount++;
            return lastFrame;
        }
    }
    protected void preNextTextureImpl(GL gl) {}
    protected void postNextTextureImpl(GL gl) {}
    protected abstract boolean getNextTextureImpl(GL gl, TextureFrame nextFrame, boolean blocking, boolean issuePreAndPost);
    protected boolean syncAVRequired() { return false; }
    
    /** 
     * {@inheritDoc}
     * <p>
     * Note: All {@link AudioSink} operations are performed from {@link GLMediaPlayerImpl},
     * i.e. {@link #play()}, {@link #pause()}, {@link #seek(int)}, {@link #setPlaySpeed(float)}, {@link #getAudioPTS()}.
     * </p>
     * <p>
     * Implementations using an {@link AudioSink} shall write it's instance to {@link #audioSink}
     * from within their {@link #initGLStreamImpl(GL, int, int)} implementation.
     * </p>
     */
    @Override
    public final AudioSink getAudioSink() { return audioSink; }
    
    /** 
     * To be called from implementation at 1st PTS after start
     * w/ current pts value in milliseconds.
     * @param audio_scr_t0
     */
    protected void setFirstAudioPTS2SCR(int pts) {
        if( audioSCR_reset ) {
            audio_scr_t0 = Platform.currentTimeMillis() - pts;
            audioSCR_reset = false;
        }
    }
    private void flushAllVideoFrames() {
        if( null != videoFramesFree ) {
            videoFramesFree.reset(true);
        }
        if( null != videoFramesDecoded ) {
            videoFramesDecoded.reset(false);
        }
        lastFrame = videoFramesFree.get(false /* clearRef */ );
        if( null == lastFrame ) { throw new InternalError("XXX"); }
        cachedFrame = null;
    }
    private void resetAllAudioVideoSync() {
        video_dpts_cum = 0;
        video_dpts_count = 0;
        resetAudioVideoPTS();
        flushAllVideoFrames();
        if( null != audioSink ) {
            audioSink.flush();
        }
    }
    private void resetAudioVideoPTS() {
        presentedFrameCount = 0;
        displayedFrameCount = 0;
        decodedFrameCount = 0;
        audioSCR_reset = true;
        videoSCR_reset = true;
    }
    private final int getVideoDPTSAvg() {
        return (int) ( video_dpts_cum * (1.0f - VIDEO_DPTS_COEFF) + 0.5f );
    }
    
    private final void newFrameAvailable(TextureFrame frame, long currentTimeMillis) {
        decodedFrameCount++;
        if( 0 == frame.getDuration() ) { // patch frame duration if not set already 
            frame.setDuration( (int) frame_duration );
        }
        synchronized(eventListenersLock) {
            for(Iterator<GLMediaEventListener> i = eventListeners.iterator(); i.hasNext(); ) {
                i.next().newFrameAvailable(this, frame, currentTimeMillis);
            }
        }
    }
    
    class FramePusher extends Thread {
        private volatile boolean isRunning = false;
        private volatile boolean isActive = false;
        private volatile boolean isBlocked = false;
        
        private volatile boolean shallPause = true;
        private volatile boolean shallStop = false;
        
        private final GL gl;
        private GLDrawable dummyDrawable = null;
        private GLContext sharedGLCtx = null;
        
        FramePusher(GL gl) {
            setDaemon(true);
            
            final GLContext glCtx = gl.getContext();
            final boolean glCtxCurrent = glCtx.isCurrent();
            final GLProfile glp = gl.getGLProfile();
            final GLDrawableFactory factory = GLDrawableFactory.getFactory(glp);
            final AbstractGraphicsDevice device = glCtx.getGLDrawable().getNativeSurface().getGraphicsConfiguration().getScreen().getDevice();
            dummyDrawable = factory.createDummyDrawable(device, true, glp); // own device!
            dummyDrawable.setRealized(true);
            sharedGLCtx = dummyDrawable.createContext(glCtx);
            makeCurrent(sharedGLCtx);
            if( glCtxCurrent ) {
                makeCurrent(glCtx);
            } else {
                sharedGLCtx.release();
            }
            this.gl = sharedGLCtx.getGL();
        }
        
        private void makeCurrent(GLContext ctx) {
            if( GLContext.CONTEXT_NOT_CURRENT >= ctx.makeCurrent() ) {
                throw new GLException("Couldn't make ctx current: "+ctx);
            }
        }
        
        private void destroySharedGL() {
            if( null != sharedGLCtx ) {
                postNextTextureImpl(gl);
                if( sharedGLCtx.isCreated() ) {
                    // Catch dispose GLExceptions by GLEventListener, just 'print' them
                    // so we can continue with the destruction.
                    try {
                        sharedGLCtx.destroy();
                    } catch (GLException gle) {
                        gle.printStackTrace();
                    }
                }
                sharedGLCtx = null;            
            }
            if( null != dummyDrawable ) {
                final AbstractGraphicsDevice device = dummyDrawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice();
                dummyDrawable.setRealized(false);
                dummyDrawable = null;
                device.close();
            }            
        }
        
        public synchronized void doPause() {
            if( isActive ) {
                shallPause = true;
                if( isBlocked && isActive ) {
                    this.interrupt();
                }
                while( isActive ) {
                    try {
                        this.wait(); // wait until paused
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        public synchronized void doResume() {
            if( isRunning && !isActive ) {
                shallPause = false;
                while( !isActive ) {
                    this.notify();  // wake-up pause-block
                    try {
                        this.wait(); // wait until resumed 
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        public synchronized void doStart() {
            start();
            while( !isRunning ) {
                try {
                    this.wait();  // wait until started
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        public synchronized void doStop() {
            if( isRunning ) {
                shallStop = true;
                if( isBlocked && isRunning ) {
                    this.interrupt();
                }
                while( isRunning ) {
                    this.notify();  // wake-up pause-block (opt)
                    try {
                        this.wait();  // wait until stopped
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        public boolean isRunning() { return isRunning; }
        public boolean isActive() { return isActive; }
        
        public void run() {
            setName(getName()+"-FramePusher_"+FramePusherInstanceId);
            FramePusherInstanceId++;
            
            synchronized ( this ) {
                makeCurrent( sharedGLCtx );
                preNextTextureImpl(gl);
                isRunning = true;
                this.notify();   // wake-up doStart()
            }
            
            while( !shallStop ){
                if( shallPause ) {
                    synchronized ( this ) {
                        postNextTextureImpl(gl);
                        sharedGLCtx.release();
                        while( shallPause && !shallStop ) {
                            isActive = false;
                            this.notify();   // wake-up doPause()
                            try {
                                System.err.println("!!! PAUSE ON"); // FIXME
                                this.wait(); // wait until resumed
                            } catch (InterruptedException e) {
                                if( !shallPause ) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        makeCurrent(sharedGLCtx);
                        preNextTextureImpl(gl);
                        System.err.println("!!! PAUSE OFF"); // FIXME
                        isActive = true;
                        this.notify(); // wake-up doResume()
                    }
                }
                
                if( !shallStop ) {
                    TextureFrame nextFrame = null;
                    try {
                        isBlocked = true;
                        nextFrame = videoFramesFree.getBlocking(false /* clearRef */ );
                        isBlocked = false;
                        nextFrame.setPTS( TextureFrame.INVALID_PTS ); // mark invalid until processed!
                        if( getNextTextureImpl(gl, nextFrame, true, false /* issuePreAndPost */) ) {
                            // gl.glFinish();
                            gl.glFlush(); // even better: sync object!
                            if( !videoFramesDecoded.put(nextFrame) ) { 
                                throw new InternalError("XXX: free "+videoFramesFree+", decoded "+videoFramesDecoded+", "+GLMediaPlayerImpl.this); 
                            }
                            newFrameAvailable(nextFrame, Platform.currentTimeMillis());
                            nextFrame = null;
                        }
                    } catch (InterruptedException e) {
                        isBlocked = false;
                        if( !shallStop && !shallPause ) {
                            e.printStackTrace(); // oops
                            shallPause = false;
                            shallStop = true;
                        }
                    } finally {
                        if( null != nextFrame ) { // put back
                            videoFramesFree.put(nextFrame);
                        }
                    }
                }
            }
            postNextTextureImpl(gl);
            destroySharedGL();
            synchronized ( this ) {
                isRunning = false;
                isActive = false;
                this.notify(); // wake-up doStop()
            }
        }
    }    
    static int FramePusherInstanceId = 0;    
    private FramePusher framePusher = null;

    private final void pauseFramePusher() {
        if( null != framePusher ) {
            framePusher.doPause();
        }
    }
    private final void resumeFramePusher() {
        if( null != framePusher ) {
            framePusher.doResume();
        }
    }
    private final void destroyFramePusher() {
        if( null != framePusher ) {
            framePusher.doStop();
            framePusher = null;
        }
    }
    
    protected final void updateAttributes(int vid, int aid, int width, int height, int bps_stream, 
                                          int bps_video, int bps_audio, float fps, 
                                          int videoFrames, int audioFrames, int duration, String vcodec, String acodec) {
        int event_mask = 0;
        if( this.vid != vid ) {
            event_mask |= GLMediaEventListener.EVENT_CHANGE_VID;
            this.vid = vid;
        }   
        if( this.aid != aid ) {
            event_mask |= GLMediaEventListener.EVENT_CHANGE_AID;
            this.aid = aid;
        }   
        if( this.width != width || this.height != height ) {
            event_mask |= GLMediaEventListener.EVENT_CHANGE_SIZE;
            this.width = width;
            this.height = height;
        }   
        if( this.fps != fps ) {
            event_mask |= GLMediaEventListener.EVENT_CHANGE_FPS;
            this.fps = fps;
            this.frame_duration = 1000f / (float)fps;
        }
        if( this.bps_stream != bps_stream || this.bps_video != bps_video || this.bps_audio != bps_audio ) {
            event_mask |= GLMediaEventListener.EVENT_CHANGE_BPS;
            this.bps_stream = bps_stream;
            this.bps_video = bps_video;
            this.bps_audio = bps_audio;
        }
        if( this.videoFrames != videoFrames || this.audioFrames != audioFrames || this.duration != duration ) {
            event_mask |= GLMediaEventListener.EVENT_CHANGE_LENGTH;
            this.videoFrames = videoFrames;
            this.audioFrames = audioFrames;
            this.duration = duration;
        }
        if( (null!=acodec && acodec.length()>0 && !this.acodec.equals(acodec)) ) { 
            event_mask |= GLMediaEventListener.EVENT_CHANGE_CODEC;
            this.acodec = acodec;
        }
        if( (null!=vcodec && vcodec.length()>0 && !this.vcodec.equals(vcodec)) ) {
            event_mask |= GLMediaEventListener.EVENT_CHANGE_CODEC;
            this.vcodec = vcodec;
        }
        if(0==event_mask) {
            return;
        }
        attributesUpdated(event_mask);    
    }

    protected final void attributesUpdated(int event_mask) {
        synchronized(eventListenersLock) {
            for(Iterator<GLMediaEventListener> i = eventListeners.iterator(); i.hasNext(); ) {
                i.next().attributesChanges(this, event_mask, Platform.currentTimeMillis());
            }
        }
    }
    
    @Override
    public final State destroy(GL gl) {
        synchronized( stateLock ) {
            destroyFramePusher();
            destroyImpl(gl);
            removeAllTextureFrames(gl);
            if( null != videoFramesFree ) {
                videoFramesFree.clear();
            }
            if( null != videoFramesDecoded ) {
                videoFramesDecoded.clear();
            }
            state = State.Uninitialized;
            return state;
        }
    }
    protected abstract void destroyImpl(GL gl);

    @Override
    public final URI getURI() {
        return streamLoc;
    }

    @Override
    public final int getVID() { return vid; }
    
    @Override
    public final int getAID() { return aid; }
    
    @Override
    public final String getVideoCodec() {
        return vcodec;
    }

    @Override
    public final String getAudioCodec() {
        return acodec;
    }

    @Override
    public final int getVideoFrames() {
        return videoFrames;
    }
    
    public final int getAudioFrames() {
        return audioFrames;
    }

    @Override
    public final int getDuration() {
        return duration;
    }
    
    @Override
    public final long getStreamBitrate() {
        return bps_stream;
    }

    @Override
    public final int getVideoBitrate() {
        return bps_video;
    }
    
    @Override
    public final int getAudioBitrate() {
        return bps_audio;
    }
    
    @Override
    public final float getFramerate() {
        return fps;
    }

    @Override
    public final int getWidth() {
        return width;
    }

    @Override
    public final int getHeight() {
        return height;
    }

    @Override
    public final String toString() {
        final float tt = getDuration() / 1000.0f;
        final String loc = ( null != streamLoc ) ? streamLoc.toString() : "<undefined stream>" ;
        final int freeVideoFrames = null != videoFramesFree ? videoFramesFree.size() : 0;
        final int decVideoFrames = null != videoFramesDecoded ? videoFramesDecoded.size() : 0;
        final int video_scr = video_scr_pts + (int) ( ( Platform.currentTimeMillis() - video_scr_t0 ) * playSpeed );        
        return "GLMediaPlayer["+state+", vSCR "+video_scr+", frames[p "+presentedFrameCount+", d "+decodedFrameCount+", t "+videoFrames+" ("+tt+" s)], "+
               "speed "+playSpeed+", "+bps_stream+" bps, "+
               "Texture[count "+textureCount+", free "+freeVideoFrames+", dec "+decVideoFrames+", target "+toHexString(textureTarget)+", format "+toHexString(textureFormat)+", type "+toHexString(textureType)+"], "+               
               "Video[id "+vid+", <"+vcodec+">, "+width+"x"+height+", "+fps+" fps, "+frame_duration+" fdur, "+bps_video+" bps], "+
               "Audio[id "+aid+", <"+acodec+">, "+bps_audio+" bps, "+audioFrames+" frames], uri "+loc+"]";
    }
    
    @Override
    public final String getPerfString() {
        final long currentTimeMillis = Platform.currentTimeMillis();
        final int video_scr = video_scr_pts + (int) ( ( currentTimeMillis - video_scr_t0 ) * playSpeed );        
        final int d_vpts = video_pts_last - video_scr;
        final int audio_scr = (int) ( ( currentTimeMillis - audio_scr_t0 ) * playSpeed );
        final int audio_pts = getAudioPTSImpl();
        final int d_apts = audio_pts - audio_scr;
        return getPerfStringImpl( video_scr, video_pts_last, d_vpts, audio_scr, audio_pts, d_apts, getVideoDPTSAvg() );
    }
    private final String getPerfStringImpl(final int video_scr, final int video_pts, final int d_vpts,
                                           final int audio_scr, final int audio_pts, final int d_apts,
                                           final int video_dpts_avg_diff) {
        final float tt = getDuration() / 1000.0f;        
        final String audioSinkInfo;
        final AudioSink audioSink = getAudioSink();
        if( null != audioSink ) {
            audioSinkInfo = "AudioSink[frames [d "+audioSink.getEnqueuedFrameCount()+", q "+audioSink.getQueuedFrameCount()+", f "+audioSink.getFreeFrameCount()+"], time "+audioSink.getQueuedTime()+", bytes "+audioSink.getQueuedByteCount()+"]";
        } else {
            audioSinkInfo = "";
        }
        final int freeVideoFrames = null != videoFramesFree ? videoFramesFree.size() : 0;
        final int decVideoFrames = null != videoFramesDecoded ? videoFramesDecoded.size() : 0;
        return state+", frames[(p "+presentedFrameCount+", d "+decodedFrameCount+") / "+videoFrames+", "+tt+" s], "+
               "speed " + playSpeed+", dAV "+( d_vpts - d_apts )+", vSCR "+video_scr+", vpts "+video_pts+", dSCR["+d_vpts+", avrg "+video_dpts_avg_diff+"], "+
               "aSCR "+audio_scr+", apts "+audio_pts+" ( "+d_apts+" ), "+audioSinkInfo+
               ", Texture[count "+textureCount+", free "+freeVideoFrames+", dec "+decVideoFrames+"]";
    }

    @Override
    public final void addEventListener(GLMediaEventListener l) {
        if(l == null) {
            return;
        }
        synchronized(eventListenersLock) {
            eventListeners.add(l);
        }
    }

    @Override
    public final void removeEventListener(GLMediaEventListener l) {
        if (l == null) {
            return;
        }
        synchronized(eventListenersLock) {
            eventListeners.remove(l);
        }
    }

    @Override
    public final GLMediaEventListener[] getEventListeners() {
        synchronized(eventListenersLock) {
            return eventListeners.toArray(new GLMediaEventListener[eventListeners.size()]);
        }
    }

    private Object eventListenersLock = new Object();

    protected static final String toHexString(long v) {
        return "0x"+Long.toHexString(v);
    }
    protected static final String toHexString(int v) {
        return "0x"+Integer.toHexString(v);
    }
}