-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
StreamPlayer.java
1391 lines (1167 loc) 路 39.9 KB
/
StreamPlayer.java
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
/*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>. Also(warning!): 1)You are not allowed to sell this product to third party. 2)You can't change license and made it
* like you are the owner,author etc. 3)All redistributions of source code files must contain all copyright notices that are currently in this file,
* and this list of conditions without modification.
*/
package com.goxr3plus.streamplayer.stream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.BooleanControl;
import javax.sound.sampled.Control;
import javax.sound.sampled.Control.Type;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.tritonus.share.sampled.TAudioFormat;
import org.tritonus.share.sampled.file.TAudioFileFormat;
import com.goxr3plus.streamplayer.enums.AudioType;
import com.goxr3plus.streamplayer.enums.Status;
import com.goxr3plus.streamplayer.stream.StreamPlayerException.PlayerException;
import com.goxr3plus.streamplayer.tools.TimeTool;
import javazoom.spi.PropertiesContainer;
/**
* StreamPlayer is a class based on JavaSound API. It has been successfully tested under Java 10
*
* @author GOXR3PLUS (www.goxr3plus.co.nf)
* @author JavaZOOM (www.javazoom.net)
*/
public class StreamPlayer implements Callable<Void> {
/**
* Class logger
*/
private Logger logger;
// -------------------AUDIO---------------------
private volatile Status status = Status.NOT_SPECIFIED;
/** The data source. */
private Object dataSource;
/** The audio input stream. */
private volatile AudioInputStream audioInputStream;
/** The encoded audio input stream. */
private AudioInputStream encodedAudioInputStream;
/** The audio file format. */
private AudioFileFormat audioFileFormat;
/** The source data line. */
private SourceDataLine sourceDataLine;
// -------------------CONTROLS---------------------
/** The gain control. */
private FloatControl gainControl;
/** The pan control. */
private FloatControl panControl;
/** The balance control. */
private FloatControl balanceControl;
/** The sample rate control. */
// private FloatControl sampleRateControl
/** The mute control. */
private BooleanControl muteControl;
// -------------------LOCKS---------------------
/**
* It is used for synchronization in place of audioInputStream
*/
private volatile Object audioLock = new Object();
// -------------------VARIABLES---------------------
private String mixerName;
/** The current line buffer size. */
private int currentLineBufferSize = -1;
/** The line buffer size. */
private int lineBufferSize = -1;
/** The encoded audio length. */
private int encodedAudioLength = -1;
/**
* Speed Factor of the Audio
*/
private double speedFactor = 1;
/** The Constant EXTERNAL_BUFFER_SIZE. */
private static final int EXTERNAL_BUFFER_SIZE = 4096;
/** The Constant SKIP_INACCURACY_SIZE. */
// private static final int SKIP_INACCURACY_SIZE = 1200
byte[] trimBuffer;
// -------------------CLASSES---------------------
/**
* This is starting a Thread for StreamPlayer to Run
*/
private final ExecutorService streamPlayerExecutorService;
private Future<Void> future;
/**
* This executor service is used in order the playerState events to be executed
* in an order
*/
private final ExecutorService eventsExecutorService;
/** Holds a list of Linteners to be notified about Stream PlayerEvents */
private final ArrayList<StreamPlayerListener> listeners;
/** The empty map. */
private final Map<String, Object> emptyMap = new HashMap<>();
// Properties when the File/URL/InputStream is opened.
Map<String, Object> audioProperties;
// -------------------BEGIN OF CONSTRUCTOR---------------------
/**
* Default parameter less Constructor. A default logger will be used.
*/
public StreamPlayer() {
this(Logger.getLogger(StreamPlayer.class.getName()));
}
/**
* Constructor with a logger.
* @param logger The logger that will be used by the player
*/
public StreamPlayer(Logger logger) {
this(logger,
Executors.newSingleThreadExecutor(new ThreadFactoryWithNamePrefix("StreamPlayer")),
Executors.newSingleThreadExecutor(new ThreadFactoryWithNamePrefix("StreamPlayerEvent")));
}
/**
* Constructor with settable logger and executor services.
* @param logger The logger that will be used by the player
* @param streamPlayerExecutorService Executor service for the stream player
* @param eventsExecutorService Executor service for events.
*/
public StreamPlayer(Logger logger, ExecutorService streamPlayerExecutorService, ExecutorService eventsExecutorService) {
this.logger = logger;
this.streamPlayerExecutorService = streamPlayerExecutorService;
this.eventsExecutorService = eventsExecutorService;
listeners = new ArrayList<>();
reset();
}
/**
* Freeing the resources.
*/
public void reset() {
// Close the stream
synchronized (audioLock) {
closeStream();
}
// Source Data Line
if (sourceDataLine != null) {
sourceDataLine.flush();
sourceDataLine.close();
sourceDataLine = null;
}
// AudioFile
audioInputStream = null;
audioFileFormat = null;
encodedAudioInputStream = null;
encodedAudioLength = -1;
// Controls
gainControl = null;
panControl = null;
balanceControl = null;
// sampleRateControl = null
// Notify the Status
status = Status.NOT_SPECIFIED;
generateEvent(Status.NOT_SPECIFIED, AudioSystem.NOT_SPECIFIED, null);
}
/**
* Notify listeners about a BasicPlayerEvent.
*
* @param status event code.
* @param encodedStreamPosition in the stream when the event occurs.
* @param description the description
*
* @return A String Describing if any problem occurred
*/
private String generateEvent(final Status status, final int encodedStreamPosition, final Object description) {
try {
return eventsExecutorService
.submit(new StreamPlayerEventLauncher(this, status, encodedStreamPosition, description, listeners))
.get();
} catch (InterruptedException | ExecutionException ex) {
logger.log(Level.WARNING, "Problem in StreamPlayer generateEvent() method", ex);
}
return "Problem in StreamPlayer generateEvent() method";
}
/**
* Add a listener to be notified.
*
* @param streamPlayerListener the listener
*/
public void addStreamPlayerListener(final StreamPlayerListener streamPlayerListener) {
listeners.add(streamPlayerListener);
}
/**
* Remove registered listener.
*
* @param streamPlayerListener the listener
*/
public void removeStreamPlayerListener(final StreamPlayerListener streamPlayerListener) {
if (listeners != null)
listeners.remove(streamPlayerListener);
}
/**
* Open the specific object which can be File,URL or InputStream.
*
* @param object the object [File or URL or InputStream ]
*
* @throws StreamPlayerException the stream player exception
*/
public void open(final Object object) throws StreamPlayerException {
logger.info(() -> "open(" + object + ")\n");
if (object == null)
return;
dataSource = object;
initAudioInputStream();
}
/**
* Create AudioInputStream and AudioFileFormat from the data source.
*
* @throws StreamPlayerException the stream player exception
*/
private void initAudioInputStream() throws StreamPlayerException {
try {
logger.info("Entered initAudioInputStream\n");
// Reset
reset();
// Notify Status
status = Status.OPENING;
generateEvent(Status.OPENING, getEncodedStreamPosition(), dataSource);
// Audio resources from file||URL||inputStream.
if (dataSource instanceof URL) {
audioInputStream = AudioSystem.getAudioInputStream((URL) dataSource);
audioFileFormat = AudioSystem.getAudioFileFormat((URL) dataSource);
} else if (dataSource instanceof File) {
audioInputStream = AudioSystem.getAudioInputStream((File) dataSource);
audioFileFormat = AudioSystem.getAudioFileFormat((File) dataSource);
} else if (dataSource instanceof InputStream) {
audioInputStream = AudioSystem.getAudioInputStream((InputStream) dataSource);
audioFileFormat = AudioSystem.getAudioFileFormat((InputStream) dataSource);
}
// Create the Line
createLine();
// Determine Properties
determineProperties();
// Generate Open Event
status = Status.OPENED;
generateEvent(Status.OPENED, getEncodedStreamPosition(), null);
} catch (LineUnavailableException | UnsupportedAudioFileException | IOException 垄) {
logger.log(Level.INFO, 垄.getMessage(), 垄);
throw new StreamPlayerException(垄);
}
logger.info("Exited initAudioInputStream\n");
}
/**
* Determines Properties when the File/URL/InputStream is opened.
*/
private void determineProperties() {
logger.info("Entered determineProperties()!\n");
// Add AudioFileFormat properties.
// Expect if it is null(something bad happened).
if (audioFileFormat == null)
return;
if (!(audioFileFormat instanceof TAudioFileFormat))
audioProperties = new HashMap<>();
else {
// Tritonus SPI compliant audio file format.
audioProperties = ((TAudioFileFormat) audioFileFormat).properties();
// Clone the Map because it is not mutable.
audioProperties = deepCopy(audioProperties);
}
// Add JavaSound properties.
if (audioFileFormat.getByteLength() > 0)
audioProperties.put("audio.length.bytes", audioFileFormat.getByteLength());
if (audioFileFormat.getFrameLength() > 0)
audioProperties.put("audio.length.frames", audioFileFormat.getFrameLength());
if (audioFileFormat.getType() != null)
audioProperties.put("audio.type", audioFileFormat.getType());
// AudioFormat properties.
final AudioFormat audioFormat = audioFileFormat.getFormat();
if (audioFormat.getFrameRate() > 0)
audioProperties.put("audio.framerate.fps", audioFormat.getFrameRate());
if (audioFormat.getFrameSize() > 0)
audioProperties.put("audio.framesize.bytes", audioFormat.getFrameSize());
if (audioFormat.getSampleRate() > 0)
audioProperties.put("audio.samplerate.hz", audioFormat.getSampleRate());
if (audioFormat.getSampleSizeInBits() > 0)
audioProperties.put("audio.samplesize.bits", audioFormat.getSampleSizeInBits());
if (audioFormat.getChannels() > 0)
audioProperties.put("audio.channels", audioFormat.getChannels());
// Tritonus SPI compliant audio format.
if (audioFormat instanceof TAudioFormat)
audioProperties.putAll(((TAudioFormat) audioFormat).properties());
// Add SourceDataLine
audioProperties.put("basicplayer.sourcedataline", sourceDataLine);
// Keep this final reference for the lambda expression
final Map<String, Object> audioPropertiesCopy = audioProperties;
// Notify all registered StreamPlayerListeners
listeners.forEach(listener -> listener.opened(dataSource, audioPropertiesCopy));
logger.info("Exited determineProperties()!\n");
}
/**
* Initiating Audio resources from AudioSystem.<br>
*
* @throws LineUnavailableException the line unavailable exception
* @throws StreamPlayerException
*/
private void initLine() throws LineUnavailableException, StreamPlayerException {
logger.info("Initiating the line...");
if (sourceDataLine == null)
createLine();
if (!sourceDataLine.isOpen())
openLine();
else if (!sourceDataLine.getFormat().equals(audioInputStream == null ? null : audioInputStream.getFormat())) {
sourceDataLine.close();
openLine();
}
}
/** The frame size. */
// private int frameSize
/**
* Change the Speed Rate of the Audio , this variable affects the Sample Rate ,
* for example 1.0 is normal , 0.5 is half the speed and 2.0 is double the speed
* Note that you have to restart the audio for this to take effect
*
* @param speedFactor speedFactor
*/
public void setSpeedFactor(final double speedFactor) {
this.speedFactor = speedFactor;
}
/**
* Inits a DateLine.<br>
* <p>
* From the AudioInputStream, i.e. from the sound file, we fetch information
* about the format of the audio data. These information include the sampling
* frequency, the number of channels and the size of the samples. There
* information are needed to ask JavaSound for a suitable output line for this
* audio file. Furthermore, we have to give JavaSound a hint about how big the
* internal buffer for the line should be. Here, we say
* AudioSystem.NOT_SPECIFIED, signaling that we don't care about the exact size.
* JavaSound will use some default value for the buffer size.
*
* @throws LineUnavailableException the line unavailable exception
* @throws StreamPlayerException
*/
private void createLine() throws LineUnavailableException, StreamPlayerException {
logger.info("Entered CreateLine()!:\n");
if (sourceDataLine != null)
logger.warning("Warning Source DataLine is not null!\n");
else {
final AudioFormat sourceFormat = audioInputStream.getFormat();
logger.info(() -> "Create Line : Source format : " + sourceFormat + "\n");
// Calculate the Sample Size in bits
int nSampleSizeInBits = sourceFormat.getSampleSizeInBits();
if (sourceFormat.getEncoding() == AudioFormat.Encoding.ULAW || sourceFormat.getEncoding() == AudioFormat.Encoding.ALAW
|| nSampleSizeInBits <= 0 || nSampleSizeInBits != 8)
nSampleSizeInBits = 16;
final AudioFormat targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
(float) (sourceFormat.getSampleRate() * speedFactor), nSampleSizeInBits, sourceFormat.getChannels(),
nSampleSizeInBits / 8 * sourceFormat.getChannels(), sourceFormat.getSampleRate(), false);
// int frameSize = sourceFormat.getChannels() * (nSampleSizeInBits / 8)
logger.info(() -> "Sample Rate =" + targetFormat.getSampleRate() + ",Frame Rate="
+ targetFormat.getFrameRate() + ",Bit Rate=" + targetFormat.getSampleSizeInBits()
+ "Target format: " + targetFormat + "\n");
// Keep a reference on encoded stream to progress notification.
encodedAudioInputStream = audioInputStream;
try {
// Get total length in bytes of the encoded stream.
encodedAudioLength = encodedAudioInputStream.available();
} catch (final IOException e) {
logger.warning("Cannot get m_encodedaudioInputStream.available()\n" + e);
}
// Create decoded Stream
audioInputStream = AudioSystem.getAudioInputStream(targetFormat, audioInputStream);
final DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, audioInputStream.getFormat(),
AudioSystem.NOT_SPECIFIED);
if (!AudioSystem.isLineSupported(lineInfo))
throw new StreamPlayerException(PlayerException.LINE_NOT_SUPPORTED);
// ----------About the mixer
if (mixerName == null)
// Primary Sound Driver
mixerName = getMixers().get(0);
// Continue
final Mixer mixer = getMixer(mixerName);
if (mixer == null) {
sourceDataLine = (SourceDataLine) AudioSystem.getLine(lineInfo);
mixerName = null;
} else {
logger.info("Mixer: " + mixer.getMixerInfo());
sourceDataLine = (SourceDataLine) mixer.getLine(lineInfo);
}
sourceDataLine = (SourceDataLine) AudioSystem.getLine(lineInfo);
// --------------------------------------------------------------------------------
logger.info(() -> "Line : " + sourceDataLine);
logger.info(() -> "Line Info : " + sourceDataLine.getLineInfo());
logger.info(() -> "Line AudioFormat: " + sourceDataLine.getFormat() + "\n");
logger.info("Exited CREATELINE()!:\n");
}
}
/**
* Open the line.
*
* @throws LineUnavailableException the line unavailable exception
*/
private void openLine() throws LineUnavailableException {
logger.info("Entered OpenLine()!:\n");
if (sourceDataLine != null) {
final AudioFormat audioFormat = audioInputStream.getFormat();
currentLineBufferSize = lineBufferSize >= 0 ? lineBufferSize : sourceDataLine.getBufferSize();
sourceDataLine.open(audioFormat, currentLineBufferSize);
// opened?
if (sourceDataLine.isOpen()) {
// logger.info(() -> "Open Line Buffer Size=" + bufferSize + "\n");
/*-- Display supported controls --*/
// Control[] c = m_line.getControls()
// Master_Gain Control?
gainControl = sourceDataLine.isControlSupported(FloatControl.Type.MASTER_GAIN)
? (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN)
: null;
// PanControl?
panControl = sourceDataLine.isControlSupported(FloatControl.Type.PAN)
? (FloatControl) sourceDataLine.getControl(FloatControl.Type.PAN)
: null;
// SampleRate?
// if (sourceDataLine.isControlSupported(FloatControl.Type.SAMPLE_RATE))
// sampleRateControl = (FloatControl)
// sourceDataLine.getControl(FloatControl.Type.SAMPLE_RATE);
// else
// sampleRateControl = null
// Mute?
muteControl = sourceDataLine.isControlSupported(BooleanControl.Type.MUTE)
? (BooleanControl) sourceDataLine.getControl(BooleanControl.Type.MUTE)
: null;
// Speakers Balance?
balanceControl = sourceDataLine.isControlSupported(FloatControl.Type.BALANCE)
? (FloatControl) sourceDataLine.getControl(FloatControl.Type.BALANCE)
: null;
}
}
logger.info("Exited OpenLine()!:\n");
}
/**
* Starts the play back.
*
* @throws StreamPlayerException the stream player exception
*/
public void play() throws StreamPlayerException {
if (status == Status.STOPPED)
initAudioInputStream();
if (status != Status.OPENED)
return;
// Shutdown previous Thread Running
awaitTermination();
// Open SourceDataLine.
try {
initLine();
} catch (final LineUnavailableException ex) {
throw new StreamPlayerException(StreamPlayerException.PlayerException.CAN_NOT_INIT_LINE, ex);
}
// Open the sourceDataLine
if (sourceDataLine != null && !sourceDataLine.isRunning()) {
sourceDataLine.start();
// Proceed only if we have not problems
logger.info("Submitting new StreamPlayer Thread");
streamPlayerExecutorService.submit(this);
// Update the status
status = Status.PLAYING;
generateEvent(Status.PLAYING, getEncodedStreamPosition(), null);
}
}
/**
* Pauses the play back.<br>
* <p>
* Player Status = PAUSED. * @return False if failed(so simple...)
*
* @return true, if successful
*/
public boolean pause() {
if (sourceDataLine == null || status != Status.PLAYING)
return false;
status = Status.PAUSED;
logger.info("pausePlayback() completed");
generateEvent(Status.PAUSED, getEncodedStreamPosition(), null);
return true;
}
/**
* Stops the play back.<br>
* <p>
* Player Status = STOPPED.<br>
* Thread should free Audio resources.
*/
public void stop() {
if (status == Status.STOPPED)
return;
if (isPlaying())
pause();
status = Status.STOPPED;
// generateEvent(Status.STOPPED, getEncodedStreamPosition(), null);
logger.info("StreamPlayer stopPlayback() completed");
}
/**
* Resumes the play back.<br>
* <p>
* Player Status = PLAYING*
*
* @return False if failed(so simple...)
*/
public boolean resume() {
if (sourceDataLine == null || status != Status.PAUSED)
return false;
sourceDataLine.start();
status = Status.PLAYING;
generateEvent(Status.RESUMED, getEncodedStreamPosition(), null);
logger.info("resumePlayback() completed");
return true;
}
/**
* Await for the termination of StreamPlayerExecutorService Thread
*/
private void awaitTermination() {
if (future != null && !future.isDone()) {
try {
// future.get() [Don't use this cause it may hang forever and ever...]
// Wait ~1 second and then cancel the future
final Thread delay = new Thread(() -> {
try {
for (int i = 0; i < 50; i++) {
if (!future.isDone())
Thread.sleep(20);
else
break;
System.out.println("StreamPlayer Future is not yet done...");
}
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
logger.log(Level.INFO, ex.getMessage(), ex);
}
});
// Start the delay Thread
delay.start();
// Join until delay Thread is finished
delay.join();
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
logger.log(Level.WARNING, ex.getMessage(), ex);
} finally {
// Harmless if task already completed
future.cancel(true); // interrupt if running
}
}
}
/**
* Skip bytes in the File input stream. It will skip N frames matching to bytes,
* so it will never skip given bytes len
*
* @param bytes the bytes
*
* @return value bigger than 0 for File and value = 0 for URL and InputStream
*
* @throws StreamPlayerException the stream player exception
*/
public long seekBytes(final long bytes) throws StreamPlayerException {
long totalSkipped = 0;
// If it is File
if (dataSource instanceof File) {
// Check if the requested bytes are more than totalBytes of Audio
final long bytesLength = getTotalBytes();
System.out.println("Bytes: " + bytes + " BytesLength: " + bytesLength);
if ((bytesLength <= 0) || (bytes >= bytesLength)) {
generateEvent(Status.EOM, getEncodedStreamPosition(), null);
return totalSkipped;
}
logger.info(() -> "Bytes to skip : " + bytes);
final Status previousStatus = status;
status = Status.SEEKING;
try {
synchronized (audioLock) {
generateEvent(Status.SEEKING, AudioSystem.NOT_SPECIFIED, null);
initAudioInputStream();
if (audioInputStream != null) {
long skipped;
// Loop until bytes are really skipped.
while (totalSkipped < bytes) { // totalSkipped < (bytes-SKIP_INACCURACY_SIZE)))
skipped = audioInputStream.skip(bytes - totalSkipped);
if (skipped == 0)
break;
totalSkipped += skipped;
logger.info("Skipped : " + totalSkipped + "/" + bytes);
if (totalSkipped == -1)
throw new StreamPlayerException(
StreamPlayerException.PlayerException.SKIP_NOT_SUPPORTED);
logger.info("Skeeping:" + totalSkipped);
}
}
}
generateEvent(Status.SEEKED, getEncodedStreamPosition(), null);
status = Status.OPENED;
if (previousStatus == Status.PLAYING)
play();
else if (previousStatus == Status.PAUSED) {
play();
pause();
}
} catch (final IOException ex) {
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return totalSkipped;
}
/**
* Skip x seconds of audio
* See {@link #seekBytes(long)}
*
* @param seconds Seconds to Skip
*/
//todo not finished needs more validations
public long seekSeconds(int seconds) throws StreamPlayerException {
int durationInSeconds = this.getDurationInSeconds();
//Validate
validateSeconds(seconds, durationInSeconds);
//Calculate Bytes
long totalBytes = getTotalBytes();
double percentage = (seconds * 100) / durationInSeconds;
long bytes = (long) (totalBytes * (percentage / 100));
return seekBytes(this.getEncodedStreamPosition() + bytes);
}
// /**
// * Skip seconds of audio based on the pattern
// * See {@link #seek(long)}
// *
// * @param pattern A string in the format (HH:MM:SS) WHERE h = HOURS , M = minutes , S = seconds
// */
// public void seek(String pattern) throws StreamPlayerException {
// long bytes = 0;
//
// seek(bytes);
// }
/**
* Go to X time of the Audio
* See {@link #seekBytes(long)}
*
* @param seconds Seconds to Skip
*/
public long seekTo(int seconds) throws StreamPlayerException {
int durationInSeconds = this.getDurationInSeconds();
//Validate
validateSeconds(seconds, durationInSeconds);
//Calculate Bytes
long totalBytes = getTotalBytes();
double percentage = (seconds * 100) / durationInSeconds;
long bytes = (long) (totalBytes * (percentage / 100));
return seekBytes(bytes);
}
// /**
// * Go to X time of the Audio
// * See {@link #seek(long)}
// *
// * @param pattern A string in the format (HH:MM:SS) WHERE h = HOURS , M = minutes , S = seconds
// */
// public void seekTo(String pattern) throws StreamPlayerException {
// long bytes = 0;
//
// seek(bytes);
// }
private void validateSeconds(int seconds, int durationInSeconds) {
if (seconds < 0) {
throw new UnsupportedOperationException("Trying to skip negative seconds ");
} else if (seconds >= durationInSeconds) {
throw new UnsupportedOperationException("Trying to skip with seconds {" + seconds + "} > maximum {" + durationInSeconds + "}");
}
}
public int getDurationInSeconds() {
// Audio resources from file||URL||inputStream.
if (dataSource instanceof File) {
return TimeTool.durationInSeconds(((File) dataSource).getAbsolutePath(), AudioType.FILE);
} else if (dataSource instanceof URL) { //todo
return -1;
} else if (dataSource instanceof InputStream) { //todo
return -1;
}
return -1;
}
/**
* Main loop.
* <p>
* Player Status == STOPPED || SEEKING = End of Thread + Freeing Audio
* Resources.<br>
* Player Status == PLAYING = Audio stream data sent to Audio line.<br>
* Player Status == PAUSED = Waiting for another status.
*/
@Override
public Void call() {
int nBytesRead = 0;
final int audioDataLength = EXTERNAL_BUFFER_SIZE;
final ByteBuffer audioDataBuffer = ByteBuffer.allocate(audioDataLength);
audioDataBuffer.order(ByteOrder.LITTLE_ENDIAN);
// Lock stream while playing.
synchronized (audioLock) {
// Main play/pause loop.
while ((nBytesRead != -1) && status != Status.STOPPED && status != Status.NOT_SPECIFIED
&& status != Status.SEEKING) {
// if (status == Status.SEEKING) {
// try {
// System.out.println("Audio Seeking ...");
// Thread.sleep(50);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
try {
// Playing?
if (status == Status.PLAYING) {
// System.out.println("Inside Stream Player Run method")
int toRead = audioDataLength;
int totalRead = 0;
// Reads up a specified maximum number of bytes from audio stream
// wtf i have written here omg //to fix! cause it is complicated
for (; toRead > 0 && (nBytesRead = audioInputStream.read(audioDataBuffer.array(), totalRead,
toRead)) != -1; toRead -= nBytesRead, totalRead += nBytesRead)
// Check for under run
if (sourceDataLine.available() >= sourceDataLine.getBufferSize())
logger.info(() -> "Underrun> Available=" + sourceDataLine.available()
+ " , SourceDataLineBuffer=" + sourceDataLine.getBufferSize());
// Check if anything has been read
if (totalRead > 0) {
trimBuffer = audioDataBuffer.array();
if (totalRead < trimBuffer.length) {
trimBuffer = new byte[totalRead];
// Copies an array from the specified source array, beginning at the specified
// position, to the specified position of the destination array
// The number of components copied is equal to the length argument.
System.arraycopy(audioDataBuffer.array(), 0, trimBuffer, 0, totalRead);
}
// Writes audio data to the mixer via this source data line
sourceDataLine.write(trimBuffer, 0, totalRead);
// Compute position in bytes in encoded stream.
final int nEncodedBytes = getEncodedStreamPosition();
// System.err.println(trimBuffer[0] + " , Data Length :" + trimBuffer.length)
// Notify all registered Listeners
listeners.forEach(listener -> {
if (audioInputStream instanceof PropertiesContainer) {
// Pass audio parameters such as instant
// bit rate, ...
listener.progress(nEncodedBytes, sourceDataLine.getMicrosecondPosition(),
trimBuffer, ((PropertiesContainer) audioInputStream).properties());
} else
// Pass audio parameters
listener.progress(nEncodedBytes, sourceDataLine.getMicrosecondPosition(),
trimBuffer, emptyMap);
});
}
} else if (status == Status.PAUSED) {
// Flush and stop the source data line
if (sourceDataLine != null && sourceDataLine.isRunning()) {
sourceDataLine.flush();
sourceDataLine.stop();
}
try {
while (status == Status.PAUSED) {
Thread.sleep(50);
}
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
logger.warning("Thread cannot sleep.\n" + ex);
}
}
} catch (final IOException ex) {
logger.log(Level.WARNING, "\"Decoder Exception: \" ", ex);
status = Status.STOPPED;
generateEvent(Status.STOPPED, getEncodedStreamPosition(), null);
}
}
// Free audio resources.
if (sourceDataLine != null) {
sourceDataLine.drain();
sourceDataLine.stop();
sourceDataLine.close();
sourceDataLine = null;
}
// Close stream.
closeStream();
// Notification of "End Of Media"
if (nBytesRead == -1)
generateEvent(Status.EOM, AudioSystem.NOT_SPECIFIED, null);
}
// Generate Event
status = Status.STOPPED;
generateEvent(Status.STOPPED, AudioSystem.NOT_SPECIFIED, null);
// Log
logger.info("Decoding thread completed");
return null;
}
/**
* Calculates the current position of the encoded audio based on <br>
* <b>nEncodedBytes = encodedAudioLength -
* encodedAudioInputStream.available();</b>
*
* @return The Position of the encoded stream in term of bytes
*/
public int getEncodedStreamPosition() {
int position = -1;
if (dataSource instanceof File && encodedAudioInputStream != null)
try {
position = encodedAudioLength - encodedAudioInputStream.available();
} catch (final IOException ex) {
logger.log(Level.WARNING, "Cannot get m_encodedaudioInputStream.available()", ex);
stop();
}
return position;
}
/**
* Close stream.
*/
private void closeStream() {