aboutsummaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/jogamp/opengl/util/av/GLMediaPlayerImpl.java
blob: 27c9267046de899c0ebbfc24c3e8dac80f4fa634 (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
/**
 * 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.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLES2;
import javax.media.opengl.GLException;

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 #setTextureCount(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";

    protected State state;
    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 URLConnection urlConn = null;
    
    protected float playSpeed = 1.0f;
    
    /** Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected int width = 0;
    /** Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected int height = 0;
    /** Video fps. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected float fps = 0;
    /** Stream bps. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected int bps_stream = 0;
    /** Video bps. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected int bps_video = 0;
    /** Audio bps. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected int bps_audio = 0;
    /** In frames. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected int totalFrames = 0;
    /** In ms. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected int duration = 0;
    /** Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected String acodec = unknown;
    /** Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
    protected String vcodec = unknown;
    
    protected int frameNumber = 0;
    
    protected TextureSequence.TextureFrame[] texFrames = null;
    protected HashMap<Integer, TextureSequence.TextureFrame> texFrameMap = new HashMap<Integer, TextureSequence.TextureFrame>();
    private ArrayList<GLMediaEventListener> eventListeners = new ArrayList<GLMediaEventListener>();

    protected GLMediaPlayerImpl() {
        this.textureCount=3;
        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 void setTextureUnit(int u) { texUnit = u; }
    
    @Override
    public int getTextureUnit() { return texUnit; }
    
    protected final void setTextureCount(int textureCount) {
        this.textureCount=textureCount;
    }
    @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 final TextureSequence.TextureFrame getLastTexture() throws IllegalStateException {
        if(State.Uninitialized == state) {
            throw new IllegalStateException("Instance not initialized: "+this);
        }
        return getLastTextureImpl();
    }
    protected abstract TextureSequence.TextureFrame getLastTextureImpl();
    
    @Override
    public final synchronized TextureSequence.TextureFrame getNextTexture(GL gl, boolean blocking) throws IllegalStateException {
        if(State.Uninitialized == state) {
            throw new IllegalStateException("Instance not initialized: "+this);
        }
        if(State.Playing == state) {
            final TextureSequence.TextureFrame f = getNextTextureImpl(gl, blocking);
            return f;
        }
        return getLastTextureImpl();        
    }
    protected abstract TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking);
    
    @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 synchronized float getPlaySpeed() {
        return playSpeed;
    }
    
    @Override
    public final synchronized void setPlaySpeed(float rate) {
        if(State.Uninitialized != state && setPlaySpeedImpl(rate)) {
            playSpeed = rate;
        }
        if(DEBUG) { System.err.println("SetPlaySpeed: "+toString()); }
    }
    protected abstract boolean setPlaySpeedImpl(float rate);

    public final State start() {
        switch(state) {
            case Stopped:
            case Paused:
                if(startImpl()) {
                    state = State.Playing;
                }
        }
        if(DEBUG) { System.err.println("Start: "+toString()); }
        return state;
    }
    protected abstract boolean startImpl();
    
    public final State pause() {
        if(State.Playing == state && pauseImpl()) {
            state = State.Paused;
        }
        if(DEBUG) { System.err.println("Pause: "+toString()); }            
        return state;
    }
    protected abstract boolean pauseImpl();
    
    public final State stop() {
        switch(state) {
            case Playing:
            case Paused:
                if(stopImpl()) {
                    state = State.Stopped;
                }
        }
        if(DEBUG) { System.err.println("Stop: "+toString()); }
        return state;
    }
    protected abstract boolean stopImpl();
    
    @Override
    public final int getCurrentPosition() {
        if(State.Uninitialized != state) {
            return getCurrentPositionImpl();
        }
        return 0;
    }
    protected abstract int getCurrentPositionImpl();
    
    public final int seek(int msec) {
        final int cp;
        switch(state) {
            case Stopped:
            case Playing:
            case Paused:
                cp = seekImpl(msec);
                break;
            default:
                cp = 0;
        }
        if(DEBUG) { System.err.println("Seek("+msec+"): "+toString()); }
        return cp;        
    }
    protected abstract int seekImpl(int msec);
    
    public final State getState() { return state; }
    
    @Override
    public final State initGLStream(GL gl, URLConnection urlConn) throws IllegalStateException, GLException, IOException {
        if(State.Uninitialized != state) {
            throw new IllegalStateException("Instance not in state "+State.Uninitialized+", but "+state+", "+this);
        }
        this.urlConn = urlConn;
        if (this.urlConn != null) {
            try {                
                if(null != gl) {
                    if(null!=texFrames) {
                        // re-init ..
                        removeAllImageTextures(gl);
                    } else {
                        texFrames = new TextureSequence.TextureFrame[textureCount];
                    }
                    final int[] tex = new int[textureCount];
                    {
                        gl.glGenTextures(textureCount, tex, 0);
                        final int err = gl.glGetError();
                        if( GL.GL_NO_ERROR != err ) {
                            throw new RuntimeException("TextureNames creation failed (num: "+textureCount+"): err "+toHexString(err));
                        }
                    }
                    initGLStreamImpl(gl, tex);
                    
                    for(int i=0; i<textureCount; i++) {
                        final TextureSequence.TextureFrame tf = createTexImage(gl, i, tex); 
                        texFrames[i] = tf;
                        texFrameMap.put(tex[i], tf);
                    }
                }
                state = State.Stopped;
                return state;
            } catch (Throwable t) {
                throw new GLException("Error initializing GL resources", t);
            }
        }
        return state;        
    }
    
    /**
     * Implementation shall set the following set of data here 
     * @param gl TODO
     * @param texNames TODO
     * @see #width
     * @see #height
     * @see #fps
     * @see #bps_stream
     * @see #totalFrames
     * @see #acodec
     * @see #vcodec
    */
    protected abstract void initGLStreamImpl(GL gl, int[] texNames) throws IOException;
    
    protected TextureSequence.TextureFrame createTexImage(GL gl, int idx, int[] tex) {
        return new TextureSequence.TextureFrame( createTexImageImpl(gl, idx, tex, width, height, false) );
    }
    
    protected Texture createTexImageImpl(GL gl, int idx, int[] tex, int tWidth, int tHeight, boolean mustFlipVertically) {
        if( 0 > tex[idx] ) {
            throw new RuntimeException("TextureName "+toHexString(tex[idx])+" invalid.");
        }
        gl.glActiveTexture(GL.GL_TEXTURE0+getTextureUnit());
        gl.glBindTexture(textureTarget, tex[idx]);
        {
            final int err = gl.glGetError();
            if( GL.GL_NO_ERROR != err ) {
                throw new RuntimeException("Couldn't bind textureName "+toHexString(tex[idx])+" 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(tex[idx],
                     textureTarget,
                     tWidth, tHeight,
                     width,  height,
                     mustFlipVertically);        
    }
    
    protected void destroyTexImage(GL gl, TextureSequence.TextureFrame imgTex) {
        imgTex.getTexture().destroy(gl);        
    }
    
    protected void removeAllImageTextures(GL gl) {
        if(null != texFrames) {
            for(int i=0; i<textureCount; i++) {
                final TextureSequence.TextureFrame imgTex = texFrames[i];
                if(null != imgTex) {
                    destroyTexImage(gl, imgTex);
                    texFrames[i] = null;
                }
            }
        }
        texFrameMap.clear();
    }

    protected final void updateAttributes(int width, int height, int bps_stream, int bps_video, int bps_audio, 
                                          float fps, int totalFrames, int duration, 
                                          String vcodec, String acodec) {
        int event_mask = 0;
        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;
        }
        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.totalFrames != totalFrames || this.duration != duration ) {
            event_mask |= GLMediaEventListener.EVENT_CHANGE_LENGTH;
            this.totalFrames = totalFrames;
            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, System.currentTimeMillis());
            }
        }
    }
    protected final void newFrameAvailable() {
        frameNumber++;        
        synchronized(eventListenersLock) {
            for(Iterator<GLMediaEventListener> i = eventListeners.iterator(); i.hasNext(); ) {
                i.next().newFrameAvailable(this, System.currentTimeMillis());
            }
        }
    }
    
    @Override
    public final synchronized State destroy(GL gl) {
        destroyImpl(gl);
        removeAllImageTextures(gl);
        state = State.Uninitialized;
        return state;
    }
    protected abstract void destroyImpl(GL gl);

    @Override
    public final synchronized URLConnection getURLConnection() {
        return urlConn;
    }

    @Override
    public final synchronized String getVideoCodec() {
        return vcodec;
    }

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

    @Override
    public final synchronized long getTotalFrames() {
        return totalFrames;
    }

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

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

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

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

    @Override
    public final synchronized String toString() {
        final float ct = getCurrentPosition() / 1000.0f, tt = getDuration() / 1000.0f;
        final String loc = ( null != urlConn ) ? urlConn.getURL().toExternalForm() : "<undefined stream>" ;
        return "GLMediaPlayer["+state+", "+frameNumber+"/"+totalFrames+" frames, "+ct+"/"+tt+"s, speed "+playSpeed+", "+bps_stream+" bps, "+
                "Texture[count "+textureCount+", target "+toHexString(textureTarget)+", format "+toHexString(textureFormat)+", type "+toHexString(textureType)+"], "+               
               "Stream[Video[<"+vcodec+">, "+width+"x"+height+", "+fps+" fps, "+bps_video+" bsp], "+
               "Audio[<"+acodec+">, "+bps_audio+" bsp]], "+loc+"]";
    }

    @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 synchronized 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);
    }
        
}