This repository has been archived by the owner on Feb 9, 2018. It is now read-only.
/
DLNAMediaInfo.java
1849 lines (1589 loc) · 50.5 KB
/
DLNAMediaInfo.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
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.dlna;
import com.sun.jna.Platform;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.Thumbnails;
import net.pms.PMS;
import net.pms.configuration.RendererConfiguration;
import net.pms.formats.AudioAsVideo;
import net.pms.formats.Format;
import net.pms.formats.v2.SubtitleType;
import net.pms.io.OutputParams;
import net.pms.io.ProcessWrapperImpl;
import net.pms.network.HTTPResource;
import net.pms.util.AVCHeader;
import net.pms.util.CoverUtil;
import net.pms.util.FileUtil;
import net.pms.util.MpegUtil;
import net.pms.util.ProcessUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.sanselan.ImageInfo;
import org.apache.sanselan.Sanselan;
import org.apache.sanselan.common.IImageMetadata;
import org.apache.sanselan.formats.jpeg.JpegImageMetadata;
import org.apache.sanselan.formats.tiff.TiffField;
import org.apache.sanselan.formats.tiff.constants.TiffConstants;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class keeps track of media file metadata scanned by the MediaInfo library.
*
* TODO: Change all instance variables to private. For backwards compatibility
* with external plugin code the variables have all been marked as deprecated
* instead of changed to private, but this will surely change in the future.
* When everything has been changed to private, the deprecated note can be
* removed.
*/
public class DLNAMediaInfo implements Cloneable {
private static final Logger LOGGER = LoggerFactory.getLogger(DLNAMediaInfo.class);
private static final String THUMBNAIL_DIRECTORY_NAME = "thumbs";
public static final long ENDFILE_POS = 99999475712L;
public static final long TRANS_SIZE = 100000000000L;
private boolean h264_parsed;
// Stored in database
private Double durationSec;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public int bitrate;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public int width;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public int height;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public long size;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public String codecV;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public String frameRate;
private String frameRateMode;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public String aspect;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public byte thumb[];
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public String mimeType;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public int bitsPerPixel;
private List<DLNAMediaAudio> audioTracks = new ArrayList<DLNAMediaAudio>();
private List<DLNAMediaSubtitle> subtitleTracks = new ArrayList<DLNAMediaSubtitle>();
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public String model;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public int exposure;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public int orientation;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public int iso;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public String muxingMode;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public String muxingModeAudio;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public String container;
/**
* @deprecated Use {@link #getH264AnnexB()} and {@link #setH264AnnexB(byte[])} to access this variable.
*/
@Deprecated
public byte[] h264_annexB;
/**
* Not stored in database.
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public boolean mediaparsed;
/**
* isMediaParserV2 related, used to manage thumbnail management separated
* from the main parsing process.
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public boolean thumbready;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public int dvdtrack;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public boolean secondaryFormatValid = true;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public boolean parsing = false;
private boolean ffmpeg_failure;
private boolean ffmpeg_annexb_failure;
private boolean muxable;
private Map<String, String> extras;
/**
* @deprecated Use standard getter and setter to access this variable.
*/
@Deprecated
public boolean encrypted;
public boolean isMuxable(RendererConfiguration mediaRenderer) {
// temporary fix: MediaInfo support will take care of this in the future
// for now, http://ps3mediaserver.org/forum/viewtopic.php?f=11&t=6361&start=0
if (mediaRenderer.isBRAVIA() && getCodecV() != null && getCodecV().startsWith("mpeg2")) {
muxable = true;
}
if (mediaRenderer.isBRAVIA() && getHeight() < 288) { // not supported for these small heights
muxable = false;
}
return muxable;
}
public Map<String, String> getExtras() {
return extras;
}
public void putExtra(String key, String value) {
if (extras == null) {
extras = new HashMap<String, String>();
}
extras.put(key, value);
}
public String getExtrasAsString() {
if (extras == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : extras.entrySet()) {
sb.append(entry.getKey());
sb.append("|");
sb.append(entry.getValue());
sb.append("|");
}
return sb.toString();
}
public void setExtrasAsString(String value) {
if (value != null) {
StringTokenizer st = new StringTokenizer(value, "|");
while (st.hasMoreTokens()) {
try {
putExtra(st.nextToken(), st.nextToken());
} catch (NoSuchElementException nsee) {
LOGGER.debug("Caught exception", nsee);
}
}
}
}
public DLNAMediaInfo() {
setThumbready(true); // this class manages thumbnails by default with the parser_v1 method
}
public void generateThumbnail(InputFile input, Format ext, int type) {
DLNAMediaInfo forThumbnail = new DLNAMediaInfo();
forThumbnail.durationSec = durationSec;
forThumbnail.parse(input, ext, type, true);
setThumb(forThumbnail.getThumb());
}
private ProcessWrapperImpl getFFMpegThumbnail(InputFile media) {
String args[] = new String[14];
args[0] = getFfmpegPath();
boolean dvrms = media.getFile() != null && media.getFile().getAbsolutePath().toLowerCase().endsWith("dvr-ms");
if (dvrms && StringUtils.isNotBlank(PMS.getConfiguration().getFfmpegAlternativePath())) {
args[0] = PMS.getConfiguration().getFfmpegAlternativePath();
}
args[1] = "-ss";
args[2] = "" + PMS.getConfiguration().getThumbnailSeekPos();
args[3] = "-i";
if (media.getFile() != null) {
args[4] = ProcessUtil.getShortFileNameIfWideChars(media.getFile().getAbsolutePath());
} else {
args[4] = "-";
}
args[5] = "-an";
args[6] = "-an";
args[7] = "-s";
args[8] = "320x180";
args[9] = "-vframes";
args[10] = "1";
args[11] = "-f";
args[12] = "image2";
args[13] = "pipe:";
// FIXME MPlayer should not be used if thumbnail generation is disabled (and it should be disabled in the GUI)
if (!PMS.getConfiguration().isThumbnailGenerationEnabled() || (PMS.getConfiguration().isUseMplayerForVideoThumbs() && !dvrms)) {
args[2] = "0";
for (int i = 5; i <= 13; i++) {
args[i] = "-an";
}
}
OutputParams params = new OutputParams(PMS.getConfiguration());
params.maxBufferSize = 1;
params.stdin = media.getPush();
params.noexitcheck = true; // not serious if anything happens during the thumbnailer
// true: consume stderr on behalf of the caller i.e. parse()
final ProcessWrapperImpl pw = new ProcessWrapperImpl(args, params, false, true);
// FAILSAFE
setParsing(true);
Runnable r = new Runnable() {
public void run() {
try {
Thread.sleep(10000);
ffmpeg_failure = true;
} catch (InterruptedException e) { }
pw.stopProcess();
setParsing(false);
}
};
Thread failsafe = new Thread(r, "FFMpeg Thumbnail Failsafe");
failsafe.start();
pw.runInSameThread();
setParsing(false);
return pw;
}
private ProcessWrapperImpl getMplayerThumbnail(InputFile media) throws IOException {
String args[] = new String[14];
args[0] = PMS.getConfiguration().getMplayerPath();
args[1] = "-ss";
boolean toolong = getDurationInSeconds() < PMS.getConfiguration().getThumbnailSeekPos();
args[2] = "" + (toolong ? (getDurationInSeconds() / 2) : PMS.getConfiguration().getThumbnailSeekPos());
args[3] = "-quiet";
if (media.getFile() != null) {
args[4] = ProcessUtil.getShortFileNameIfWideChars(media.getFile().getAbsolutePath());
} else {
args[4] = "-";
}
args[5] = "-msglevel";
args[6] = "all=4";
args[7] = "-vf";
args[8] = "scale=320:-2,expand=:180";
args[9] = "-frames";
args[10] = "1";
args[11] = "-vo";
String frameName = "" + media.hashCode();
frameName = "mplayer_thumbs:subdirs=\"" + frameName + "\"";
frameName = frameName.replace(',', '_');
args[12] = "jpeg:outdir=" + frameName;
args[13] = "-nosound";
OutputParams params = new OutputParams(PMS.getConfiguration());
params.workDir = PMS.getConfiguration().getTempFolder();
params.maxBufferSize = 1;
params.stdin = media.getPush();
params.log = true;
params.noexitcheck = true; // not serious if anything happens during the thumbnailer
final ProcessWrapperImpl pw = new ProcessWrapperImpl(args, params);
// FAILSAFE
setParsing(true);
Runnable r = new Runnable() {
public void run() {
try {
Thread.sleep(3000);
//mplayer_thumb_failure = true;
} catch (InterruptedException e) { }
pw.stopProcess();
setParsing(false);
}
};
Thread failsafe = new Thread(r, "MPlayer Thumbnail Failsafe");
failsafe.start();
pw.runInSameThread();
setParsing(false);
return pw;
}
private String getFfmpegPath() {
String value = PMS.getConfiguration().getFfmpegPath();
if (value == null) {
LOGGER.info("No ffmpeg - unable to thumbnail");
throw new RuntimeException("No ffmpeg - unable to thumbnail");
} else {
return value;
}
}
public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly) {
int i = 0;
while (isParsing()) {
if (i == 5) {
setMediaparsed(true);
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
i++;
}
if (isMediaparsed()) {
return;
}
if (inputFile != null) {
if (inputFile.getFile() != null) {
setSize(inputFile.getFile().length());
} else {
setSize(inputFile.getSize());
}
ProcessWrapperImpl pw = null;
boolean ffmpeg_parsing = true;
if (type == Format.AUDIO || ext instanceof AudioAsVideo) {
ffmpeg_parsing = false;
DLNAMediaAudio audio = new DLNAMediaAudio();
if (inputFile.getFile() != null) {
try {
AudioFile af = AudioFileIO.read(inputFile.getFile());
AudioHeader ah = af.getAudioHeader();
if (ah != null && !thumbOnly) {
int length = ah.getTrackLength();
int rate = ah.getSampleRateAsNumber();
if (ah.getEncodingType().toLowerCase().contains("flac 24")) {
audio.setBitsperSample(24);
}
audio.setSampleFrequency("" + rate);
setDuration((double) length);
setBitrate((int) ah.getBitRateAsNumber());
audio.getAudioProperties().setNumberOfChannels(2);
if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("mono")) {
audio.getAudioProperties().setNumberOfChannels(1);
} else if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("stereo")) {
audio.getAudioProperties().setNumberOfChannels(2);
} else if (ah.getChannels() != null) {
audio.getAudioProperties().setNumberOfChannels(Integer.parseInt(ah.getChannels()));
}
audio.setCodecA(ah.getEncodingType().toLowerCase());
if (audio.getCodecA().contains("(windows media")) {
audio.setCodecA(audio.getCodecA().substring(0, audio.getCodecA().indexOf("(windows media")).trim());
}
}
Tag t = af.getTag();
if (t != null) {
if (t.getArtworkList().size() > 0) {
setThumb(t.getArtworkList().get(0).getBinaryData());
} else {
if (PMS.getConfiguration().getAudioThumbnailMethod() > 0) {
setThumb(
CoverUtil.get().getThumbnailFromArtistAlbum(
PMS.getConfiguration().getAudioThumbnailMethod() == 1 ?
CoverUtil.AUDIO_AMAZON :
CoverUtil.AUDIO_DISCOGS,
audio.getArtist(), audio.getAlbum()
)
);
}
}
if (!thumbOnly) {
audio.setAlbum(t.getFirst(FieldKey.ALBUM));
audio.setArtist(t.getFirst(FieldKey.ARTIST));
audio.setSongname(t.getFirst(FieldKey.TITLE));
String y = t.getFirst(FieldKey.YEAR);
try {
if (y.length() > 4) {
y = y.substring(0, 4);
}
audio.setYear(Integer.parseInt(((y != null && y.length() > 0) ? y : "0")));
y = t.getFirst(FieldKey.TRACK);
audio.setTrack(Integer.parseInt(((y != null && y.length() > 0) ? y : "1")));
audio.setGenre(t.getFirst(FieldKey.GENRE));
} catch (Throwable e) {
LOGGER.debug("Error parsing unimportant metadata: " + e.getMessage());
}
}
}
} catch (Throwable e) {
LOGGER.debug("Error parsing audio file: {} - {}", e.getMessage(), e.getCause() != null ? e.getCause().getMessage() : "");
ffmpeg_parsing = false;
}
if (audio.getSongname() == null || audio.getSongname().length() == 0) {
audio.setSongname(inputFile.getFile().getName());
}
if (!ffmpeg_parsing) {
getAudioTracksList().add(audio);
}
}
}
if (type == Format.IMAGE && inputFile.getFile() != null) {
try {
ffmpeg_parsing = false;
ImageInfo info = Sanselan.getImageInfo(inputFile.getFile());
setWidth(info.getWidth());
setHeight(info.getHeight());
setBitsPerPixel(info.getBitsPerPixel());
String formatName = info.getFormatName();
if (formatName.startsWith("JPEG")) {
setCodecV("jpg");
IImageMetadata meta = Sanselan.getMetadata(inputFile.getFile());
if (meta != null && meta instanceof JpegImageMetadata) {
JpegImageMetadata jpegmeta = (JpegImageMetadata) meta;
TiffField tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_MODEL);
if (tf != null) {
setModel(tf.getStringValue().trim());
}
tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_EXPOSURE_TIME);
if (tf != null) {
setExposure((int) (1000 * tf.getDoubleValue()));
}
tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ORIENTATION);
if (tf != null) {
setOrientation(tf.getIntValue());
}
tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ISO);
if (tf != null) {
// Galaxy Nexus jpg pictures may contain multiple values, take the first
int[] isoValues = tf.getIntArrayValue();
setIso(isoValues[0]);
}
}
} else if (formatName.startsWith("PNG")) {
setCodecV("png");
} else if (formatName.startsWith("GIF")) {
setCodecV("gif");
} else if (formatName.startsWith("TIF")) {
setCodecV("tiff");
}
setContainer(getCodecV());
} catch (Throwable e) {
// ffmpeg_parsing = true;
LOGGER.info("Error parsing image ({}) with Sanselan, switching to FFmpeg", inputFile.getFile().getAbsolutePath(), e);
}
}
if (PMS.getConfiguration().getImageThumbnailsEnabled()) {
try {
File thumbDir = new File(PMS.getConfiguration().getTempFolder(), THUMBNAIL_DIRECTORY_NAME);
LOGGER.trace("Generating thumbnail for: {}", inputFile.getFile().getAbsolutePath());
if (!thumbDir.exists() && !thumbDir.mkdirs()) {
LOGGER.warn("Could not create thumbnail directory: {}", thumbDir.getAbsolutePath());
} else {
File thumbFile = new File(thumbDir, inputFile.getFile().getName() + ".jpg");
String thumbFilename = thumbFile.getAbsolutePath();
LOGGER.trace("Creating (temporary) thumbnail: {}", thumbFilename);
// Create the thumbnail image using the Thumbnailator library
final Builder<File> thumbnail = Thumbnails.of(inputFile.getFile());
thumbnail.size(320, 180);
thumbnail.outputFormat("jpg");
thumbnail.outputQuality(1.0f);
thumbnail.toFile(thumbFilename);
File jpg = new File(thumbFilename);
if (jpg.exists()) {
InputStream is = new FileInputStream(jpg);
int sz = is.available();
if (sz > 0) {
setThumb(new byte[sz]);
is.read(getThumb());
}
is.close();
if (!jpg.delete()) {
jpg.deleteOnExit();
}
}
}
} catch (UnsupportedFormatException ufe) {
LOGGER.warn("Can't create thumbnail for {}: {}", inputFile.getFile().getAbsolutePath(), ufe.getMessage());
} catch (Exception e) {
LOGGER.warn("Error generating thumbnail for: {}", inputFile.getFile().getAbsolutePath(), e);
}
}
if (ffmpeg_parsing) {
if (!thumbOnly || !PMS.getConfiguration().isUseMplayerForVideoThumbs()) {
pw = getFFMpegThumbnail(inputFile);
}
String input = "-";
boolean dvrms = false;
if (inputFile.getFile() != null) {
input = ProcessUtil.getShortFileNameIfWideChars(inputFile.getFile().getAbsolutePath());
dvrms = inputFile.getFile().getAbsolutePath().toLowerCase().endsWith("dvr-ms");
}
if (!ffmpeg_failure && !thumbOnly) {
if (input.equals("-")) {
input = "pipe:";
}
boolean matchs = false;
ArrayList<String> lines = (ArrayList<String>) pw.getResults();
int langId = 0;
int subId = 0;
ListIterator<String> FFmpegMetaData = lines.listIterator();
for (String line : lines) {
FFmpegMetaData.next();
line = line.trim();
if (line.startsWith("Output")) {
matchs = false;
} else if (line.startsWith("Input")) {
if (line.indexOf(input) > -1) {
matchs = true;
setContainer(line.substring(10, line.indexOf(",", 11)).trim());
} else {
matchs = false;
}
} else if (matchs) {
if (line.indexOf("Duration") > -1) {
StringTokenizer st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (token.startsWith("Duration: ")) {
String durationStr = token.substring(10);
int l = durationStr.substring(durationStr.indexOf(".") + 1).length();
if (l < 4) {
durationStr = durationStr + "00".substring(0, 3 - l);
}
if (durationStr.indexOf("N/A") > -1) {
setDuration(null);
} else {
setDuration(parseDurationString(durationStr));
}
} else if (token.startsWith("bitrate: ")) {
String bitr = token.substring(9);
int spacepos = bitr.indexOf(" ");
if (spacepos > -1) {
String value = bitr.substring(0, spacepos);
String unit = bitr.substring(spacepos + 1);
setBitrate(Integer.parseInt(value));
if (unit.equals("kb/s")) {
setBitrate(1024 * getBitrate());
}
if (unit.equals("mb/s")) {
setBitrate(1048576 * getBitrate());
}
}
}
}
} else if (line.indexOf("Audio:") > -1) {
StringTokenizer st = new StringTokenizer(line, ",");
int a = line.indexOf("(");
int b = line.indexOf("):", a);
DLNAMediaAudio audio = new DLNAMediaAudio();
audio.setId(langId++);
if (a > -1 && b > a) {
audio.setLang(line.substring(a + 1, b));
} else {
audio.setLang(DLNAMediaLang.UND);
}
// Get TS IDs
a = line.indexOf("[0x");
b = line.indexOf("]", a);
if (a > -1 && b > a + 3) {
String idString = line.substring(a + 3, b);
try {
audio.setId(Integer.parseInt(idString, 16));
} catch (NumberFormatException nfe) {
LOGGER.debug("Error parsing Stream ID: " + idString);
}
}
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (token.startsWith("Stream")) {
audio.setCodecA(token.substring(token.indexOf("Audio: ") + 7));
} else if (token.endsWith("Hz")) {
audio.setSampleFrequency(token.substring(0, token.indexOf("Hz")).trim());
} else if (token.equals("mono")) {
audio.getAudioProperties().setNumberOfChannels(1);
} else if (token.equals("stereo")) {
audio.getAudioProperties().setNumberOfChannels(2);
} else if (token.equals("5:1") || token.equals("5.1") || token.equals("6 channels")) {
audio.getAudioProperties().setNumberOfChannels(6);
} else if (token.equals("5 channels")) {
audio.getAudioProperties().setNumberOfChannels(5);
} else if (token.equals("4 channels")) {
audio.getAudioProperties().setNumberOfChannels(4);
} else if (token.equals("2 channels")) {
audio.getAudioProperties().setNumberOfChannels(2);
} else if (token.equals("s32")) {
audio.setBitsperSample(32);
} else if (token.equals("s24")) {
audio.setBitsperSample(24);
} else if (token.equals("s16")) {
audio.setBitsperSample(16);
}
}
int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();
if (FFmpegMetaDataNr > -1) line = lines.get(FFmpegMetaDataNr);
if (line.indexOf("Metadata:") > -1) {
FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
line = lines.get(FFmpegMetaDataNr);
while (line.indexOf(" ") == 0) {
if (line.toLowerCase().indexOf("title :") > -1) {
int aa = line.indexOf(": ");
int bb = line.length();
if (aa > -1 && bb > aa) {
audio.setFlavor(line.substring(aa+2, bb));
break;
}
} else {
FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
line = lines.get(FFmpegMetaDataNr);
}
}
}
getAudioTracksList().add(audio);
} else if (line.indexOf("Video:") > -1) {
StringTokenizer st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (token.startsWith("Stream")) {
setCodecV(token.substring(token.indexOf("Video: ") + 7));
} else if ((token.indexOf("tbc") > -1 || token.indexOf("tb(c)") > -1)) {
// A/V sync issues with newest FFmpeg, due to the new tbr/tbn/tbc outputs
// Priority to tb(c)
String frameRateDoubleString = token.substring(0, token.indexOf("tb")).trim();
try {
if (!frameRateDoubleString.equals(getFrameRate())) {// tbc taken into account only if different than tbr
Double frameRateDouble = Double.parseDouble(frameRateDoubleString);
setFrameRate(String.format(Locale.ENGLISH, "%.2f", frameRateDouble / 2));
}
} catch (NumberFormatException nfe) {
// Could happen if tbc is "1k" or something like that, no big deal
LOGGER.debug("Could not parse frame rate \"" + frameRateDoubleString + "\"");
}
} else if ((token.indexOf("tbr") > -1 || token.indexOf("tb(r)") > -1) && getFrameRate() == null) {
setFrameRate(token.substring(0, token.indexOf("tb")).trim());
} else if ((token.indexOf("fps") > -1 || token.indexOf("fps(r)") > -1) && getFrameRate() == null) { // dvr-ms ?
setFrameRate(token.substring(0, token.indexOf("fps")).trim());
} else if (token.indexOf("x") > -1) {
String resolution = token.trim();
if (resolution.indexOf(" [") > -1) {
resolution = resolution.substring(0, resolution.indexOf(" ["));
}
try {
setWidth(Integer.parseInt(resolution.substring(0, resolution.indexOf("x"))));
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse width from \"" + resolution.substring(0, resolution.indexOf("x")) + "\"");
}
try {
setHeight(Integer.parseInt(resolution.substring(resolution.indexOf("x") + 1)));
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse height from \"" + resolution.substring(resolution.indexOf("x") + 1) + "\"");
}
}
}
} else if (line.indexOf("Subtitle:") > -1 && !line.contains("tx3g")) {
DLNAMediaSubtitle lang = new DLNAMediaSubtitle();
lang.setType((line.contains("dvdsub") && Platform.isWindows() ? SubtitleType.VOBSUB : SubtitleType.UNKNOWN));
int a = line.indexOf("(");
int b = line.indexOf("):", a);
if (a > -1 && b > a) {
lang.setLang(line.substring(a + 1, b));
} else {
lang.setLang(DLNAMediaLang.UND);
}
lang.setId(subId++);
int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();
if (FFmpegMetaDataNr > -1) {
line = lines.get(FFmpegMetaDataNr);
}
if (line.indexOf("Metadata:") > -1) {
FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
line = lines.get(FFmpegMetaDataNr);
while (line.indexOf(" ") == 0) {
if (line.toLowerCase().indexOf("title :") > -1) {
int aa = line.indexOf(": ");
int bb = line.length();
if (aa > -1 && bb > aa) {
lang.setFlavor(line.substring(aa+2, bb));
break;
}
} else {
FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
line = lines.get(FFmpegMetaDataNr);
}
}
}
getSubtitleTracksList().add(lang);
}
}
}
}
if (!thumbOnly && getContainer() != null && inputFile.getFile() != null && getContainer().equals("mpegts") && isH264() && getDurationInSeconds() == 0) {
// let's do the parsing for getting the duration...
try {
int length = MpegUtil.getDurationFromMpeg(inputFile.getFile());
if (length > 0) {
setDuration((double) length);
}
} catch (IOException e) {
LOGGER.trace("Error retrieving length: " + e.getMessage());
}
}
if (PMS.getConfiguration().isUseMplayerForVideoThumbs() && type == Format.VIDEO && !dvrms) {
try {
getMplayerThumbnail(inputFile);
String frameName = "" + inputFile.hashCode();
frameName = PMS.getConfiguration().getTempFolder() + "/mplayer_thumbs/" + frameName + "00000001/00000001.jpg";
frameName = frameName.replace(',', '_');
File jpg = new File(frameName);
if (jpg.exists()) {
InputStream is = new FileInputStream(jpg);
int sz = is.available();
if (sz > 0) {
setThumb(new byte[sz]);
is.read(getThumb());
}
is.close();
if (!jpg.delete()) {
jpg.deleteOnExit();
}
// Try and retry
if (!jpg.getParentFile().delete() && !jpg.getParentFile().delete()) {
LOGGER.debug("Failed to delete \"" + jpg.getParentFile().getAbsolutePath() + "\"");
}
}
} catch (IOException e) {
LOGGER.debug("Caught exception", e);
}
}
if (type == Format.VIDEO && pw != null && getThumb() == null) {
InputStream is;
try {
is = pw.getInputStream(0);
int sz = is.available();
if (sz > 0) {
setThumb(new byte[sz]);
is.read(getThumb());
}
is.close();
if (sz > 0 && !java.awt.GraphicsEnvironment.isHeadless()) {
BufferedImage image = ImageIO.read(new ByteArrayInputStream(getThumb()));
if (image != null) {
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.PLAIN, 14));
int low = 0;
if (getWidth() > 0) {
if (getWidth() == 1920 || getWidth() == 1440) {
g.drawString("1080p", 0, low += 18);
} else if (getWidth() == 1280) {
g.drawString("720p", 0, low += 18);
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", out);
setThumb(out.toByteArray());
}
}
} catch (IOException e) {
LOGGER.debug("Error while decoding thumbnail: " + e.getMessage());
}
}
}
finalize(type, inputFile);
setMediaparsed(true);
}
}
public boolean isH264() {
return getCodecV() != null && getCodecV().contains("264");
}
public int getFrameNumbers() {
double fr = Double.parseDouble(getFrameRate());
return (int) (getDurationInSeconds() * fr);
}
public void setDuration(Double d) {
this.durationSec = d;
}
public Double getDuration() {
return durationSec;
}
/**
*
* @return 0 if nothing is specified, otherwise the duration