-
Notifications
You must be signed in to change notification settings - Fork 435
Expand file tree
/
Copy pathJavaJMFSEPort.java
More file actions
652 lines (537 loc) · 23.2 KB
/
JavaJMFSEPort.java
File metadata and controls
652 lines (537 loc) · 23.2 KB
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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.codename1.impl.javase;
import com.codename1.io.Log;
import com.codename1.impl.javase.ffmpeg.FFMPEGMedia;
import com.codename1.media.AbstractMedia;
import com.codename1.media.AsyncMedia;
import com.codename1.media.Media;
import com.codename1.ui.CN;
import com.codename1.ui.Component;
import com.codename1.ui.Form;
import com.codename1.ui.Label;
import com.codename1.ui.PeerComponent;
import com.codename1.util.AsyncResource;
import java.awt.EventQueue;
import java.io.InputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.AudioDeviceUnavailableEvent;
import javax.media.ConnectionErrorEvent;
import javax.media.Controller;
import javax.media.ControllerAdapter;
import javax.media.ControllerErrorEvent;
import javax.media.DataLostErrorEvent;
import javax.media.EndOfMediaEvent;
import javax.media.InternalErrorEvent;
import javax.media.Player;
import javax.media.ResourceUnavailableEvent;
import javax.media.StartEvent;
import javax.media.StopEvent;
import javax.media.Time;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* A "fall-back" JavaSE implementation that does not support a native browser component, and uses JMF for media.
* This is only used if CEF and FX are both not found.
* @author shannah
*/
public class JavaJMFSEPort extends JavaSEPort {
@Override
public AsyncResource<Media> createMediaAsync(final InputStream stream, final String mimeType, final Runnable onCompletion) {
if ("ffmpeg".equalsIgnoreCase(System.getProperty("cn1.javase.mediaImplementation", "")) && FFMPEGMedia.isConfigured()) {
return super.createMediaAsync(stream, mimeType, onCompletion);
}
final AsyncResource<Media> out = new AsyncResource<Media>();
java.awt.Container cnt = canvas.getParent();
while (!(cnt instanceof JFrame)) {
cnt = cnt.getParent();
if (cnt == null) {
out.error(new RuntimeException("Could not find canvas. Cannot create media"));
return out;
}
}
final java.awt.Container fCnt = cnt;
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
out.complete(new CodenameOneMediaPlayer(stream, mimeType, (JFrame)fCnt, onCompletion, out));
} catch (IOException ex) {
out.error(ex);
}
}
});
return out;
}
@Override
public AsyncResource<Media> createMediaAsync(final String uriAddress, final boolean isVideo, final Runnable onCompletion) {
if ("ffmpeg".equalsIgnoreCase(System.getProperty("cn1.javase.mediaImplementation", "")) && FFMPEGMedia.isConfigured()) {
return super.createMediaAsync(uriAddress, isVideo, onCompletion);
}
final AsyncResource<Media> out = new AsyncResource<Media>();
java.awt.Container cnt = canvas.getParent();
while (!(cnt instanceof JFrame)) {
cnt = cnt.getParent();
if (cnt == null) {
out.error(new RuntimeException("Could not find canvas. Cannot create media"));
return out;
}
}
final java.awt.Container fCnt = cnt;
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
out.complete(new CodenameOneMediaPlayer(uriAddress, isVideo, (JFrame)fCnt, onCompletion, out));
} catch (IOException ex) {
out.error(ex);
}
}
});
return out;
}
@Override
public PeerComponent createBrowserComponent(Object browserComponent) {
return null;
}
@Override
public boolean isNativeBrowserComponentSupported() {
return false;
}
class CodenameOneMediaPlayer extends AbstractMedia {
private java.util.Timer endMediaPoller;
private Runnable onCompletion;
private java.util.List<Runnable> completionHandlers;
private Player player;
// private MediaPlayer player;
private boolean realized = false;
private boolean isVideo;
private JFrame frm;
private boolean playing = false;
private boolean nativePlayerMode;
private AsyncResource<Media> _callback;
/**
* This is a callback for the JMF media player that is supposed to fire
* when the media is paused.
*/
private Runnable onPaused = new Runnable() {
public void run() {
if (endMediaPoller != null) {
endMediaPoller.cancel();
endMediaPoller = null;
}
stopEndMediaPoller();
playing = false;
fireMediaStateChange(AsyncMedia.State.Paused);
}
};
/**
* This is a callback for the JMF media player that is supposed to fire
* when the media is paused.
*/
private Runnable onPlaying = new Runnable() {
@Override
public void run() {
playing = true;
startEndMediaPoller();
fireMediaStateChange(AsyncMedia.State.Playing);
}
};
private String lastErrorMessage;
private AsyncMedia.MediaErrorType lastErrorType;
/**
* This is a callback for the JMF media player that is supposed to fire
* when the media is paused.
*/
private Runnable onError = new Runnable() {
public void run() {
if (_callback != null && !_callback.isDone()) {
_callback.error(createMediaException(lastErrorMessage, lastErrorType));
return;
} else {
Log.p(lastErrorMessage);
}
fireMediaError(createMediaException(lastErrorMessage, lastErrorType));
if (!playing) {
stopEndMediaPoller();
fireMediaStateChange(AsyncMedia.State.Playing);
fireMediaStateChange(AsyncMedia.State.Paused);
}
}
};
private boolean isPlayable(String uri) {
return true;
}
public CodenameOneMediaPlayer(InputStream stream, String mimeType, JFrame f, final Runnable onCompletion, final AsyncResource<Media> callback) throws IOException {
String suffix = guessSuffixForMimetype(mimeType);
File temp = File.createTempFile("mtmp", suffix);
temp.deleteOnExit();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[1024];
int len = 0;
while ((len = stream.read(buf, 0, buf.length)) > -1) {
out.write(buf, 0, len);
}
stream.close();
init(temp.toURI().toString(), mimeType.contains("video"), f, onCompletion, callback);
}
public CodenameOneMediaPlayer(String uri, boolean isVideo, JFrame f, final Runnable onCompletion, final AsyncResource<Media> callback) throws IOException {
init(uri, isVideo, f, onCompletion, callback);
}
private void init(String uri, boolean isVideo, JFrame f, final Runnable onCompletion, final AsyncResource<Media> callback) throws IOException {
frm = f;
_callback = callback;
if (onCompletion != null) {
addCompletionHandler(onCompletion);
}
this.onCompletion = new Runnable() {
@Override
public void run() {
if (callback != null && !callback.isDone()) {
callback.complete(CodenameOneMediaPlayer.this);
}
stopEndMediaPoller();
playing = false;
fireMediaStateChange(AsyncMedia.State.Paused);
fireCompletionHandlers();
}
};
this.isVideo = isVideo;
this.frm = f;
try {
if (uri.startsWith("file:")) {
uri = unfile(uri);
}
File fff = new File(uri);
if(fff.exists()) {
uri = fff.toURI().toURL().toExternalForm();
}
if (isVideo && !isPlayable(uri)) {
File temp = File.createTempFile("mtmp", ".mp4");
temp.deleteOnExit();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[1024];
int len = 0;
InputStream stream = new URL(uri).openStream();
while ((len = stream.read(buf, 0, buf.length)) > -1) {
out.write(buf, 0, len);
}
stream.close();
uri = temp.toURI().toURL().toExternalForm();
}
player = javax.media.Manager.createRealizedPlayer(new java.net.URL(uri));
player.addControllerListener(new ControllerAdapter() {
@Override
public void endOfMedia(EndOfMediaEvent e) {
System.out.println("Reached end of media");
CodenameOneMediaPlayer.this.onCompletion.run();
}
@Override
public void start(StartEvent e) {
System.out.println("In start event");
onPlaying.run();
}
@Override
public void stop(StopEvent e) {
System.out.println("In stop event");
onPaused.run();
}
@Override
public void connectionError(ConnectionErrorEvent e) {
lastErrorType = MediaErrorType.Network;
lastErrorMessage = e.getMessage();
onError.run();
}
@Override
public void dataLostError(DataLostErrorEvent e) {
lastErrorMessage = e.getMessage();
lastErrorType = MediaErrorType.Network;
onError.run();
}
@Override
public void internalError(InternalErrorEvent e) {
lastErrorMessage = e.getMessage();
lastErrorType = MediaErrorType.Unknown;
}
@Override
public void controllerError(ControllerErrorEvent e) {
lastErrorMessage = e.getMessage();
lastErrorType = MediaErrorType.Unknown;
}
@Override
public void resourceUnavailable(ResourceUnavailableEvent e) {
lastErrorMessage = e.getMessage();
lastErrorType = MediaErrorType.LineUnavailable;
}
@Override
public void audioDeviceUnavailable(AudioDeviceUnavailableEvent e) {
lastErrorMessage = "Audio device unavailable";
lastErrorType = MediaErrorType.LineUnavailable;
}
});
} catch (Exception ex) {
if (callback != null && !callback.isDone()) {
callback.error(ex);
} else {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
private com.codename1.media.AsyncMedia.MediaException createMediaException(String message, AsyncMedia.MediaErrorType type) {
return new com.codename1.media.AsyncMedia.MediaException(type, message);
}
/**
* This starts a timer which checks the status of media every Xms so that it can fire
* status change events and on completion events. The JavaFX media player has onPlaying,
* onPaused, etc.. status events of its own that seem to not work in many cases, so we
* need to use this timer to poll for the status. That really sucks!!
*/
private void startEndMediaPoller() {
stopEndMediaPoller();
endMediaPoller = new java.util.Timer();
endMediaPoller.schedule(new TimerTask() {
@Override
public void run() {
// Check if the media is playing but we haven't updated our status.
// If so, we change our status to playing, and fire a state change event.
if (!playing && player.getState() == Controller.Started) {
EventQueue.invokeLater(new Runnable() {
// State tracking on the fx thread to avoid race conditions.
public void run() {
if (!playing && player.getState() == Controller.Started) {
playing = true;
fireMediaStateChange(AsyncMedia.State.Playing);
}
}
});
} else if (playing && player.getState() != Controller.Started) {
stopEndMediaPoller();
EventQueue.invokeLater(new Runnable() {
public void run() {
if (playing && player.getState() != Controller.Started) {
playing = false;
fireMediaStateChange(AsyncMedia.State.Paused);
}
}
});
}
double diff = player.getDuration().getNanoseconds()/1_000_000l- player.getMediaTime().getNanoseconds()/1_000_000l;
if (playing && diff < 0.01) {
EventQueue.invokeLater(new Runnable() {
public void run() {
double diff = player.getDuration().getNanoseconds()/1_000_000l- player.getMediaTime().getNanoseconds()/1_000_000l;
if (playing && diff < 0.01) {
Runnable completionCallback = CodenameOneMediaPlayer.this.onCompletion;
if (completionCallback != null) {
completionCallback.run();
}
}
}
});
}
}
}, 100, 100);
}
/**
* Stop the media state poller. This is called when the media is paused.
*/
private void stopEndMediaPoller() {
if (endMediaPoller != null) {
endMediaPoller.cancel();
endMediaPoller = null;
}
}
private void fireCompletionHandlers() {
if (completionHandlers != null && !completionHandlers.isEmpty()) {
CN.callSerially(new Runnable() {
@Override
public void run() {
if (completionHandlers != null && !completionHandlers.isEmpty()) {
List<Runnable> toRun;
synchronized(CodenameOneMediaPlayer.this) {
toRun = new ArrayList<Runnable>(completionHandlers);
}
for (Runnable r : toRun) {
r.run();
}
}
}
});
}
}
public void addCompletionHandler(Runnable onCompletion) {
synchronized(this) {
if (completionHandlers == null) {
completionHandlers = new ArrayList<Runnable>();
}
completionHandlers.add(onCompletion);
}
}
public void removeCompletionHandler(Runnable onCompletion) {
if (completionHandlers != null) {
synchronized(this) {
completionHandlers.remove(onCompletion);
}
}
}
public void cleanup() {
pause();
player.deallocate();
}
public void prepare() {
player.prefetch();
}
@Override
protected void playImpl() {
if (isVideo && nativePlayerMode) {
// To simulate native player mode, we will show a form with the player.
final Form currForm = CN.getCurrentForm();
Form playerForm = new Form("Video Player", new com.codename1.ui.layouts.BorderLayout()) {
@Override
protected void onShow() {
EventQueue.invokeLater(new Runnable() {
public void run() {
playInternal();
}
});
}
};
com.codename1.ui.Toolbar tb = new com.codename1.ui.Toolbar();
playerForm.setToolbar(tb);
tb.setBackCommand("Back", new com.codename1.ui.events.ActionListener<com.codename1.ui.events.ActionEvent>() {
public void actionPerformed(com.codename1.ui.events.ActionEvent e) {
pauseInternal();
currForm.showBack();
}
});
Component videoComponent = getVideoComponent();
if (videoComponent.getComponentForm() != null) {
videoComponent.remove();
}
playerForm.addComponent(com.codename1.ui.layouts.BorderLayout.CENTER, videoComponent);
playerForm.show();
return;
}
playInternal();
}
private void playInternal() {
if (player.getState() != Controller.Started) {
player.start();
startEndMediaPoller();
}
}
private void pauseInternal() {
if (player.getState() == Controller.Started) {
player.stop();
stopEndMediaPoller();
}
}
@Override
protected void pauseImpl() {
//if(player.getStatus() == Status.PLAYING) {
if (player.getState() == Controller.Started) {
pauseInternal();
}
//playing = false;
}
public int getTime() {
return (int)(player.getMediaTime().getNanoseconds() / 1_000_000l);
}
public void setTime(final int time) {
player.setMediaTime(new Time(time * 1_000_000l));
}
public int getDuration() {
int d = (int) (player.getDuration().getNanoseconds() / 1_000_000l);
if(d == 0){
return -1;
}
return d;
}
public void setVolume(int vol) {
player.getGainControl().setLevel(((float) vol / 100f));
}
public int getVolume() {
return (int) player.getGainControl().getLevel() * 100;
}
private Component videoComponent;
@Override
public Component getVideoComponent() {
if (videoComponent != null) {
return videoComponent;
}
if (!isVideo) {
return new Label();
}
final java.awt.Component awtComponent = player.getVisualComponent();
if (awtComponent != null) {
if (videoComponent == null) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
videoComponent = new Peer(frm, awtComponent);
}
});
CN.invokeAndBlock(new Runnable() {
@Override
public void run() {
while (videoComponent == null) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(JavaJMFSEPort.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
return videoComponent;
}
System.out.println("Video Playing is not supported on this platform");
Label l = new Label("Video");
l.getStyle().setAlignment(Component.CENTER);
return l;
}
public boolean isVideo() {
return isVideo;
}
public boolean isFullScreen() {
return false;
}
public void setFullScreen(boolean fullScreen) {
}
@Override
public boolean isPlaying() {
return playing;
}
@Override
public void setNativePlayerMode(boolean nativePlayer) {
nativePlayerMode = nativePlayer;
}
@Override
public boolean isNativePlayerMode() {
return nativePlayerMode;
}
public void setVariable(String key, Object value) {
}
public Object getVariable(String key) {
return null;
}
}
@Override
public void addCompletionHandler(Media media, Runnable onCompletion) {
super.addCompletionHandler(media, onCompletion);
if (media instanceof CodenameOneMediaPlayer) {
((CodenameOneMediaPlayer)media).addCompletionHandler(onCompletion);
}
}
}