This repository has been archived by the owner on Feb 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 227
/
FFMpegVideo.java
1229 lines (1037 loc) · 38.3 KB
/
FFMpegVideo.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.encoders;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.DLNAMediaInfo;
import net.pms.dlna.DLNAMediaSubtitle;
import net.pms.dlna.DLNAResource;
import net.pms.dlna.InputFile;
import net.pms.formats.Format;
import net.pms.formats.v2.SubtitleUtils;
import net.pms.io.*;
import net.pms.network.HTTPResource;
import net.pms.util.FileUtil;
import net.pms.util.ProcessUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.apache.commons.io.FilenameUtils.getBaseName;
import static org.apache.commons.io.FilenameUtils.getExtension;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/*
* Pure FFmpeg video player.
*
* Design note:
*
* Helper methods that return lists of <code>String</code>s representing
* options are public to facilitate composition e.g. a custom engine (plugin)
* that uses tsMuxeR for videos without subtitles and FFmpeg otherwise needs to
* compose and call methods on both players.
*
* To avoid API churn, and to provide wiggle room for future functionality, all
* of these methods take the same arguments as launchTranscode (and the same
* first four arguments as finalizeTranscoderArgs) even if one or more of the
* parameters are unused e.g.:
*
* public List<String> getAudioBitrateOptions(
* String filename,
* DLNAResource dlna,
* DLNAMediaInfo media,
* OutputParams params
* )
*/
public class FFMpegVideo extends Player {
private static final Logger LOGGER = LoggerFactory.getLogger(FFMpegVideo.class);
private static final String DEFAULT_QSCALE = "3";
private static final String SUB_DIR = "subs";
protected static PmsConfiguration configuration;
private boolean dtsRemux;
private boolean ac3Remux;
private boolean videoRemux;
private JCheckBox multiThreadingCheckBox;
private JCheckBox videoRemuxCheckBox;
@Deprecated
public FFMpegVideo() {
this(PMS.getConfiguration());
}
public FFMpegVideo(PmsConfiguration configuration) {
FFMpegVideo.configuration = configuration;
}
// FIXME we have an id() accessor for this; no need for the field to be public
@Deprecated
public static final String ID = "ffmpegvideo";
/**
* Returns a list of strings representing the rescale options for this transcode i.e. the ffmpeg -vf
* options used to show subtitles in SSA/ASS format and resize a video that's too wide and/or high for the specified renderer.
* If the renderer has no size limits, or there's no media metadata, or the video is within the renderer's
* size limits, an empty list is returned.
*
* @param tempSubs the substrings filename
* @param renderer the DLNA renderer the video is being streamed to
* @param media metadata for the DLNA resource which is being transcoded
* @return a {@link List} of <code>String</code>s representing the rescale options for this video,
* or an empty list if the video doesn't need to be resized.
*/
public List<String> getVideoFilterOptions(DLNAMediaSubtitle tempSubs, RendererConfiguration renderer, DLNAMediaInfo media) throws IOException {
List<String> videoFilterOptions = new ArrayList<String>();
String subsOption = null;
String padding = null;
final boolean isResolutionTooHighForRenderer = renderer.isVideoRescale() // renderer defines a max width/height
&& (media != null && media.isMediaparsed())
&& ((media.getWidth() > renderer.getMaxVideoWidth())
|| (media.getHeight() > renderer.getMaxVideoHeight()));
if (tempSubs != null) {
StringBuilder s = new StringBuilder();
CharacterIterator it = new StringCharacterIterator(tempSubs.getExternalFile().getAbsolutePath());
for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
switch (ch) {
case ':':
s.append("\\\\:");
break;
case '\\':
s.append("/");
break;
case ']':
s.append("\\]");
break;
case '[':
s.append("\\[");
break;
default:
s.append(ch);
}
}
String subsFile = s.toString();
subsFile = subsFile.replace(",", "\\,");
subsOption = "subtitles=" + subsFile;
}
if (renderer.isPadVideoWithBlackBordersTo169AR() && renderer.isRescaleByRenderer()) {
if (media != null
&& media.isMediaparsed()
&& media.getHeight() != 0
&& (media.getWidth() / (double) media.getHeight()) >= (16 / (double) 9)) {
padding = "pad=iw:iw/(16/9):0:(oh-ih)/2";
} else {
padding = "pad=ih*(16/9):ih:(ow-iw)/2:0";
}
}
String rescaleSpec = null;
if (isResolutionTooHighForRenderer || (renderer.isPadVideoWithBlackBordersTo169AR() && !renderer.isRescaleByRenderer())) {
rescaleSpec = String.format(
// http://stackoverflow.com/a/8351875
"scale=iw*min(%1$d/iw\\,%2$d/ih):ih*min(%1$d/iw\\,%2$d/ih),pad=%1$d:%2$d:(%1$d-iw)/2:(%2$d-ih)/2",
renderer.getMaxVideoWidth(),
renderer.getMaxVideoHeight()
);
}
String overrideVF = renderer.getFFmpegVideoFilterOverride();
if (rescaleSpec != null || padding != null || overrideVF != null || subsOption != null) {
videoFilterOptions.add("-vf");
StringBuilder filterParams = new StringBuilder();
if (overrideVF != null) {
filterParams.append(overrideVF);
if (subsOption != null) {
filterParams.append(", ");
}
} else {
if (rescaleSpec != null) {
filterParams.append(rescaleSpec);
if (subsOption != null || padding != null) {
filterParams.append(", ");
}
}
if (padding != null && rescaleSpec == null) {
filterParams.append(padding);
if (subsOption != null) {
filterParams.append(", ");
}
}
}
if (subsOption != null) {
filterParams.append(subsOption);
}
videoFilterOptions.add(filterParams.toString());
}
return videoFilterOptions;
}
@Deprecated
public List<String> getTranscodeVideoOptions(RendererConfiguration renderer, DLNAMediaInfo media, OutputParams params) {
return getTranscodeVideoOptions(renderer, media, params, null);
}
/**
* Returns a list of <code>String</code>s representing ffmpeg output
* options (i.e. options that define the output file's video codec,
* audio codec and container) compatible with the renderer's
* <code>TranscodeVideo</code> profile.
*
* @param renderer The {@link RendererConfiguration} instance whose <code>TranscodeVideo</code> profile is to be processed.
* @param media the media metadata for the video being streamed. May contain unset/null values (e.g. for web videos).
* @param params output parameters
* @param fileName the name of the file
*
* @return a {@link List} of <code>String</code>s representing the FFmpeg output parameters for the renderer according
* to its <code>TranscodeVideo</code> profile.
*/
public List<String> getTranscodeVideoOptions(RendererConfiguration renderer, DLNAMediaInfo media, OutputParams params, String fileName) {
List<String> transcodeOptions = new ArrayList<String>();
if (renderer.isTranscodeToWMV() && !renderer.isXBOX()) { // WMV
transcodeOptions.add("-c:v");
transcodeOptions.add("wmv2");
transcodeOptions.add("-c:a");
transcodeOptions.add("wmav2");
transcodeOptions.add("-f");
transcodeOptions.add("asf");
} else { // MPEGPSAC3, MPEGTSAC3 or H264TSAC3
final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TSMuxerVideo.ID);
// Output audio codec
dtsRemux = isTsMuxeRVideoEngineEnabled
&& configuration.isDTSEmbedInPCM()
&& params.aid != null
&& params.aid.isDTS()
&& renderer.isDTSPlayable();
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && renderer.isTranscodeToAC3()) {
// AC-3 remux
transcodeOptions.add("-c:a");
transcodeOptions.add("copy");
} else {
if (dtsRemux) {
// Audio is added in a separate process later
transcodeOptions.add("-an");
} else if (type() == Format.AUDIO) {
// Skip
} else {
transcodeOptions.add("-c:a");
transcodeOptions.add("ac3");
}
}
InputFile newInput = null;
if (fileName != null) {
newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
}
// Output video codec
if (media.isMediaparsed()
&& params.sid == null
&& ((newInput != null && media.isVideoWithinH264LevelLimits(newInput, params.mediaRenderer))
|| !params.mediaRenderer.isH264Level41Limited())
&& media.isMuxable(params.mediaRenderer)
&& configuration.isFFmpegMuxWhenCompatible()
&& params.mediaRenderer.isMuxH264MpegTS()) {
transcodeOptions.add("-c:v");
transcodeOptions.add("copy");
transcodeOptions.add("-bsf");
transcodeOptions.add("h264_mp4toannexb");
transcodeOptions.add("-fflags");
transcodeOptions.add("+genpts");
// Set correct container Aspect Ratio if remuxed video track has different AR
// TODO does not work with ffmpeg 1.2
// https://ffmpeg.org/trac/ffmpeg/ticket/2046
// possible solution http://forum.doom9.org/showthread.php?t=152419
//
// if (media.isAspectRatioMismatch()) {
// transcodeOptions.add("-aspect");
// transcodeOptions.add(media.getAspectRatioContainer());
// }
videoRemux = true;
} else if (renderer.isTranscodeToH264TSAC3()) {
transcodeOptions.add("-c:v");
transcodeOptions.add("libx264");
transcodeOptions.add("-crf");
transcodeOptions.add("20");
transcodeOptions.add("-preset");
transcodeOptions.add("superfast");
} else if (!dtsRemux) {
transcodeOptions.add("-c:v");
transcodeOptions.add("mpeg2video");
}
// Output file format
transcodeOptions.add("-f");
if (dtsRemux) {
if (videoRemux) {
transcodeOptions.add("rawvideo");
} else {
transcodeOptions.add("mpeg2video");
}
} else if (renderer.isTranscodeToMPEGTSAC3() || renderer.isTranscodeToH264TSAC3() || videoRemux) { // MPEGTSAC3
transcodeOptions.add("mpegts");
} else { // default: MPEGPSAC3
transcodeOptions.add("vob");
}
}
return transcodeOptions;
}
/**
* Returns the video bitrate spec for the current transcode according
* to the limits/requirements of the renderer.
*
* @param renderer a {@link RendererConfiguration} instance representing the renderer being streamed to
* @param media the media metadata for the video being streamed. May contain unset/null values (e.g. for web videos).
* @return a {@link List} of <code>String</code>s representing the video bitrate options for this transcode
*/
public List<String> getVideoBitrateOptions(RendererConfiguration renderer, DLNAMediaInfo media) { // media is currently unused
List<String> videoBitrateOptions = new ArrayList<String>();
String sMaxVideoBitrate = renderer.getMaxVideoBitrate(); // currently Mbit/s
int iMaxVideoBitrate = 0;
if (sMaxVideoBitrate != null) {
try {
iMaxVideoBitrate = Integer.parseInt(sMaxVideoBitrate);
} catch (NumberFormatException nfe) {
LOGGER.error("Can't parse max video bitrate", nfe); // XXX this should be handled in RendererConfiguration
}
}
if (iMaxVideoBitrate == 0) { // unlimited: try to preserve the bitrate
videoBitrateOptions.add("-q:v"); // video qscale
videoBitrateOptions.add(DEFAULT_QSCALE);
} else { // limit the bitrate FIXME untested
// convert megabits-per-second (as per the current option name: MaxVideoBitrateMbps) to bps
// FIXME rather than dealing with megabit vs mebibit issues here, this should be left up to the client i.e.
// the renderer.conf unit should be bits-per-second (and the option should be renamed: MaxVideoBitrateMbps -> MaxVideoBitrate)
videoBitrateOptions.add("-maxrate");
videoBitrateOptions.add("" + iMaxVideoBitrate * 1000 * 1000);
}
return videoBitrateOptions;
}
/**
* Returns the audio bitrate spec for the current transcode according
* to the limits/requirements of the renderer.
*
* @param renderer a {@link RendererConfiguration} instance representing the renderer being streamed to
* @param media the media metadata for the video being streamed. May contain unset/null values (e.g. for web videos).
* @return a {@link List} of <code>String</code>s representing the audio bitrate options for this transcode
*/
public List<String> getAudioBitrateOptions(RendererConfiguration renderer, DLNAMediaInfo media) {
List<String> audioBitrateOptions = new ArrayList<String>();
audioBitrateOptions.add("-q:a");
audioBitrateOptions.add(DEFAULT_QSCALE);
return audioBitrateOptions;
}
/**
* Returns options for burning in subtitles, if enabled and available.
*
* @param filename The name of the file being transcoded.
* @param dlna The DLNA resource representing the file being transcoded.
* @param media the media metadata for the file being transcoded. May contain null fields (e.g. for web videos).
* @param params The {@link OutputParams} context object used to store miscellaneous parameters for this request.
* @return The list of subtitle options.
* @since 1.81.0
*/
public List<String> getVideoSubtitleOptions(String filename, DLNAResource dlna, DLNAMediaInfo media, OutputParams params) {
RendererConfiguration renderer = params.mediaRenderer;
List<String> subtitleOptions = new ArrayList<String>();
String externalSubtitlesFileName = null;
if (params.sid != null) {
if (params.sid.isExternal()) {
// External subtitle file
if (params.sid.isExternalFileUtf16()) {
try {
// Convert UTF-16 -> UTF-8
File convertedSubtitles = new File(configuration.getTempFolder(), "utf8_" + params.sid.getExternalFile().getName());
FileUtil.convertFileFromUtf16ToUtf8(params.sid.getExternalFile(), convertedSubtitles);
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(convertedSubtitles.getAbsolutePath());
} catch (IOException e) {
LOGGER.debug("Error converting file from UTF-16 to UTF-8", e);
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(params.sid.getExternalFile().getAbsolutePath());
}
} else {
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(params.sid.getExternalFile().getAbsolutePath());
}
// Burn in subtitles with the subtitles filter (available since ffmpeg 1.1)
subtitleOptions.add("-vf");
subtitleOptions.add("subtitles=" + externalSubtitlesFileName);
}
// TODO: Handle embedded subtitles
}
return subtitleOptions;
}
/**
* Returns the audio channel (-ac) options.
*
* @param filename The name of the file being transcoded.
* @param dlna The DLNA resource representing the file being transcoded.
* @param media the media metadata for the file being transcoded. May contain null fields (e.g. for web videos).
* @param params The {@link OutputParams} context object used to store miscellaneous parameters for this request.
* @return The list of audio channel options.
* @since 1.81.0
*/
public List<String> getAudioChannelOptions(String filename, DLNAResource dlna, DLNAMediaInfo media, OutputParams params) {
List<String> audioChannelOptions = new ArrayList<String>();
int ac = -1; // -1: don't change the number of audio channels
int nChannels = params.aid == null ? -1 : params.aid.getAudioProperties().getNumberOfChannels();
if (nChannels == -1) { // unknown (e.g. web video)
ac = 2; // works fine if the video has < 2 channels
} else if (nChannels > 2) {
int maxOutputChannels = configuration.getAudioChannelCount();
if (maxOutputChannels <= 2) {
ac = maxOutputChannels;
} else if (params.mediaRenderer.isTranscodeToWMV()) {
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=16590
// XXX WMA Pro (wmapro) supports > 2 channels, but ffmpeg doesn't have an encoder for it
ac = 2;
}
}
if (ac != -1) {
audioChannelOptions.add("-ac");
audioChannelOptions.add("" + ac);
}
return audioChannelOptions;
}
@Override
public int purpose() {
return VIDEO_SIMPLEFILE_PLAYER;
}
@Override
// TODO make this static so it can replace ID, instead of having both
public String id() {
return ID;
}
@Override
public boolean isTimeSeekable() {
return true;
}
@Override
@Deprecated
public boolean avisynth() {
return false;
}
public String initialString() {
String threads = "";
if (configuration.isFfmpegMultithreading()) {
threads = " -threads " + configuration.getNumberOfCpuCores();
}
return threads;
}
@Override
public String name() {
return "FFmpeg";
}
@Override
public int type() {
return Format.VIDEO;
}
// unused; return this array for backwards-compatibility
@Deprecated
protected String[] getDefaultArgs() {
List<String> defaultArgsList = new ArrayList<String>();
defaultArgsList.add("-loglevel");
defaultArgsList.add("warning");
String[] defaultArgsArray = new String[defaultArgsList.size()];
defaultArgsList.toArray(defaultArgsArray);
return defaultArgsArray;
}
private int[] getVideoBitrateConfig(String bitrate) {
int bitrates[] = new int[2];
if (bitrate.contains("(") && bitrate.contains(")")) {
bitrates[1] = Integer.parseInt(bitrate.substring(bitrate.indexOf("(") + 1, bitrate.indexOf(")")));
}
if (bitrate.contains("(")) {
bitrate = bitrate.substring(0, bitrate.indexOf("(")).trim();
}
if (isBlank(bitrate)) {
bitrate = "0";
}
bitrates[0] = (int) Double.parseDouble(bitrate);
return bitrates;
}
@Override
@Deprecated
public String[] args() {
return getDefaultArgs(); // unused; return this array for for backwards compatibility
}
// XXX hardwired to false and not referenced anywhere else in the codebase
@Deprecated
public boolean mplayer() {
return false;
}
@Override
public String mimeType() {
return HTTPResource.VIDEO_TRANSCODE;
}
@Override
public String executable() {
return configuration.getFfmpegPath();
}
@Override
public ProcessWrapper launchTranscode(
String filename,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
int nThreads = configuration.getNumberOfCpuCores();
List<String> cmdList = new ArrayList<String>();
RendererConfiguration renderer = params.mediaRenderer;
setAudioAndSubs(filename, media, params, configuration);
DLNAMediaSubtitle tempSubs = null;
// params.waitbeforestart = 1000;
if (!isDisableSubtitles(params)) {
tempSubs = getSubtitles(filename, media, params);
}
cmdList.add(executable());
// Prevent FFmpeg timeout
cmdList.add("-y");
cmdList.add("-loglevel");
if (LOGGER.isTraceEnabled()) { // Set -loglevel in accordance with LOGGER setting
cmdList.add("info"); // Could be changed to "verbose" or "debug" if "info" level is not enough
} else {
cmdList.add("fatal");
}
if (params.timeseek > 0) {
cmdList.add("-ss");
cmdList.add("" + params.timeseek);
}
// decoder threads
cmdList.add("-threads");
cmdList.add("" + nThreads);
final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TSMuxerVideo.ID);
ac3Remux = false;
dtsRemux = false;
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && renderer.isTranscodeToAC3()) {
// AC-3 remux takes priority
ac3Remux = true;
} else {
// Now check for DTS remux and LPCM streaming
dtsRemux = isTsMuxeRVideoEngineEnabled &&
configuration.isDTSEmbedInPCM() &&
params.aid != null &&
params.aid.isDTS() &&
params.mediaRenderer.isDTSPlayable();
}
String frameRateRatio = media.getValidFps(true);
String frameRateNumber = media.getValidFps(false);
// Input filename
cmdList.add("-i");
cmdList.add(filename);
if (media.getAudioTracksList().size() > 1) {
// Set the video stream
cmdList.add("-map");
cmdList.add("0:v");
// Set the proper audio stream
cmdList.add("-map");
cmdList.add("0:a:" + (media.getAudioTracksList().indexOf(params.aid)));
}
// Encoder threads
cmdList.add("-threads");
cmdList.add("" + nThreads);
if (params.timeend > 0) {
cmdList.add("-t");
cmdList.add("" + params.timeend);
}
// add video bitrate options (-b:a)
// cmdList.addAll(getVideoBitrateOptions(filename, dlna, media, params));
// add audio bitrate options (-b:v)
// cmdList.addAll(getAudioBitrateOptions(filename, dlna, media, params));
// if the source is too large for the renderer, resize it
// and/or add subtitles to video filter
// FFmpeg must be compiled with --enable-libass parameter
cmdList.addAll(getVideoFilterOptions(tempSubs, renderer, media));
int defaultMaxBitrates[] = getVideoBitrateConfig(configuration.getMaximumBitrate());
int rendererMaxBitrates[] = new int[2];
if (renderer.getMaxVideoBitrate() != null) {
rendererMaxBitrates = getVideoBitrateConfig(renderer.getMaxVideoBitrate());
}
// Give priority to the renderer's maximum bitrate setting over the user's setting
if (rendererMaxBitrates[0] > 0 && rendererMaxBitrates[0] < defaultMaxBitrates[0]) {
defaultMaxBitrates = rendererMaxBitrates;
}
if (params.mediaRenderer.getCBRVideoBitrate() == 0) {
// Convert value from Mb to Kb
defaultMaxBitrates[0] = 1000 * defaultMaxBitrates[0];
// Halve it since it seems to send up to 1 second of video in advance
defaultMaxBitrates[0] = defaultMaxBitrates[0] / 2;
int bufSize = 1835;
// x264 uses different buffering math than MPEG-2
if (!renderer.isTranscodeToH264TSAC3()) {
if (media.isHDVideo()) {
bufSize = defaultMaxBitrates[0] / 3;
}
if (bufSize > 7000) {
bufSize = 7000;
}
if (defaultMaxBitrates[1] > 0) {
bufSize = defaultMaxBitrates[1];
}
if (params.mediaRenderer.isDefaultVBVSize() && rendererMaxBitrates[1] == 0) {
bufSize = 1835;
}
}
// Make room for audio
if (dtsRemux) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - 1510;
} else {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - configuration.getAudioBitrate();
}
// Round down to the nearest Mb
defaultMaxBitrates[0] = defaultMaxBitrates[0] / 1000 * 1000;
// FFmpeg uses bytes for inputs instead of kbytes like MEncoder
bufSize = bufSize * 1000;
defaultMaxBitrates[0] = defaultMaxBitrates[0] * 1000;
/**
* Level 4.1-limited renderers like the PS3 can stutter when H.264 video exceeds
* this bitrate
*/
if (renderer.isTranscodeToH264TSAC3() || videoRemux) {
if (
params.mediaRenderer.isH264Level41Limited() &&
defaultMaxBitrates[0] > 31250000
) {
defaultMaxBitrates[0] = 31250000;
}
bufSize = defaultMaxBitrates[0];
}
cmdList.add("-bufsize");
cmdList.add("" + bufSize);
cmdList.add("-maxrate");
cmdList.add("" + defaultMaxBitrates[0]);
}
// Audio bitrate
if (!ac3Remux && !dtsRemux && !(type() == Format.AUDIO)) {
int channels;
if (renderer.isTranscodeToWMV() && !renderer.isXBOX()) {
channels = 2;
} else {
channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding
}
cmdList.add("-ac");
cmdList.add("" + channels);
cmdList.add("-ab");
cmdList.add(configuration.getAudioBitrate() + "k");
}
if (params.timeseek > 0) {
cmdList.add("-copypriorss");
cmdList.add("0");
cmdList.add("-avoid_negative_ts");
cmdList.add("1");
}
// Add MPEG-2 quality settings
if (!renderer.isTranscodeToH264TSAC3() && !videoRemux) {
String mpeg2Options = configuration.getMPEG2MainSettingsFFmpeg();
String mpeg2OptionsRenderer = params.mediaRenderer.getCustomFFmpegMPEG2Options();
// Renderer settings take priority over user settings
if (isNotBlank(mpeg2OptionsRenderer)) {
mpeg2Options = mpeg2OptionsRenderer;
} else {
if (mpeg2Options.contains("Automatic")) {
mpeg2Options = "-g 5 -q:v 1 -qmin 2 -qmax 3";
// It has been reported that non-PS3 renderers prefer keyint 5 but prefer it for PS3 because it lowers the average bitrate
if (params.mediaRenderer.isPS3()) {
mpeg2Options = "-g 25 -q:v 1 -qmin 2 -qmax 3";
}
if (mpeg2Options.contains("Wireless") || defaultMaxBitrates[0] < 70) {
// Lower quality for 720p+ content
if (media.getWidth() > 1280) {
mpeg2Options = "-g 25 -qmax 7 -qmin 2";
} else if (media.getWidth() > 720) {
mpeg2Options = "-g 25 -qmax 5 -qmin 2";
}
}
}
}
String[] customOptions = StringUtils.split(mpeg2Options);
cmdList.addAll(new ArrayList<String>(Arrays.asList(customOptions)));
}
// Add the output options (-f, -c:a, -c:v, etc.)
cmdList.addAll(getTranscodeVideoOptions(renderer, media, params, filename));
// Add custom options
if (StringUtils.isNotEmpty(renderer.getCustomFFmpegOptions())) {
parseOptions(renderer.getCustomFFmpegOptions(), cmdList);
}
if (!dtsRemux) {
cmdList.add("pipe:");
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
cmdArray = finalizeTranscoderArgs(
filename,
dlna,
media,
params,
cmdArray
);
ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params);
if (dtsRemux) {
PipeProcess pipe;
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TSMuxerVideo ts = new TSMuxerVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() };
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdList.add(ffVideoPipe.getInputPipe());
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
String[] cmdArrayDts = new String[cmdList.size()];
cmdList.toArray(cmdArrayDts);
cmdArrayDts = finalizeTranscoderArgs(
filename,
dlna,
media,
params,
cmdArrayDts
);
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArrayDts, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(false);
sm.setDtsEmbed(dtsRemux);
sm.setSampleFrequency(48000);
sm.setBitsPerSample(16);
sm.setNbChannels(2);
List<String> cmdListDTS = new ArrayList<String>();
cmdListDTS.add(executable());
cmdListDTS.add("-y");
cmdListDTS.add("-ss");
if (params.timeseek > 0) {
cmdListDTS.add("" + params.timeseek);
} else {
cmdListDTS.add("0");
}
if (params.stdin == null) {
cmdListDTS.add("-i");
} else {
cmdListDTS.add("-");
}
cmdListDTS.add(filename);
if (params.timeseek > 0) {
cmdListDTS.add("-copypriorss");
cmdListDTS.add("0");
cmdListDTS.add("-avoid_negative_ts");
cmdListDTS.add("1");
}
cmdListDTS.add("-ac");
cmdListDTS.add("2");
cmdListDTS.add("-f");
cmdListDTS.add("dts");
cmdListDTS.add("-c:a");
cmdListDTS.add("copy");
cmdListDTS.add(ffAudioPipe.getInputPipe());
String[] cmdArrayDTS = new String[cmdListDTS.size()];
cmdListDTS.toArray(cmdArrayDTS);
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(cmdArrayDTS, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (videoRemux) {
videoType = "V_MPEG4/ISO/AVC";
}
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType = "A_AC3";
if (dtsRemux) {
if (params.mediaRenderer.isMuxDTSToMpeg()) {
// Renderer can play proper DTS track
audioType = "A_DTS";
} else {
// DTS padded in LPCM trick
audioType = "A_LPCM";
}
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
pw.runInNewThread();
return pw;
}
@Override
public JComponent config() {
return config("NetworkTab.5");
}
protected JComponent config(String languageLabel) {
FormLayout layout = new FormLayout(
"left:pref, 0:grow",
"p, 3dlu, p, 3dlu, p, 3dlu, p"
);
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
JComponent cmp = builder.addSeparator(Messages.getString(languageLabel), cc.xyw(2, 1, 1));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
multiThreadingCheckBox = new JCheckBox(Messages.getString("MEncoderVideo.35"));
multiThreadingCheckBox.setContentAreaFilled(false);
if (configuration.isFfmpegMultithreading()) {
multiThreadingCheckBox.setSelected(true);
}
multiThreadingCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setFfmpegMultithreading(e.getStateChange() == ItemEvent.SELECTED);
}