-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathConverter.java
More file actions
1540 lines (1383 loc) · 49.3 KB
/
Converter.java
File metadata and controls
1540 lines (1383 loc) · 49.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
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
/*******************************************************************************
* Copyright (c) 2008, 2010 Xuggle Inc. All rights reserved.
*
* This file is part of Xuggle-Xuggler-Main.
*
* Xuggle-Xuggler-Main is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Xuggle-Xuggler-Main 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Xuggle-Xuggler-Main. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package com.xuggle.xuggler;
import java.util.List;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xuggle.xuggler.Global;
import com.xuggle.xuggler.IAudioResampler;
import com.xuggle.xuggler.IAudioSamples;
import com.xuggle.xuggler.IAudioSamples.Format;
import com.xuggle.xuggler.ICodec;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IContainerFormat;
import com.xuggle.xuggler.IVideoPicture;
import com.xuggle.xuggler.IPacket;
import com.xuggle.xuggler.IRational;
import com.xuggle.xuggler.IStream;
import com.xuggle.xuggler.IStreamCoder;
import com.xuggle.xuggler.IVideoResampler;
import com.xuggle.xuggler.io.URLProtocolManager;
/**
* An example class that shows how to use the Xuggler library to open, decode,
* re-sample, encode and write media files.
*
* <p>
*
* This class is called by the {@link Xuggler} class to do all the heavy
* lifting. It is meant as a Demonstration class and implements a small subset
* of the functionality that the (much more full-featured) <code>ffmpeg</code>
* command line tool implements. It is really meant to show people how the
* Xuggler library is used from java.
*
* </p>
* <p>
*
* Read <a href="{@docRoot}/src-html/com/xuggle/xuggler/Converter.html">the
* Converter.java source</a> for a good example of a class exercising this
* library.
*
* </p>
* <p>
*
* <strong>It is not our intent to replicate all features in the
* <code>ffmpeg</code> command line tool in this class.</strong>
*
* </p>
* <p>
*
* If you are just trying to convert pre-existing media files from one format to
* another with a batch-processing program we strongly recommend you use the
* <code>ffmpeg</code> command-line tool to do it. Look, here's even the <a
* href="http://ffmpeg.org/ffmpeg-doc.html">documentation</a> for that program.
*
* </p>
* <p>
*
* If on the other hand you need to programatically decide when and how you do
* video processing, or process only parts of files, or do transcoding live
* within a Java server without calling out to another process, then by all
* means use Xuggler and use this class as an example of how to do conversion.
* But please recognize you will likely need to implement code specific to your
* application. <strong>This class is no substitute for actually understanding
* the how to use the Xuggler API within your specific use-case</strong>
*
* </p>
* <p>
*
* And if you haven't gotten the impression, please stop asking us to support
* <code>ffmpeg</code> options like "-re" in this class. This class is only
* meant as a teaching-aide for the underlying Xuggler API.
*
* </p>
* <p>
*
* Instead implement your own Java class based off of this that does real-time
* playback yourself. Really. Please. We'd appreciate it very much.
*
* </p>
* <p>
* Now, all that said, here's how to create a main class that uses this
* Converter class:
* </p>
*
* <pre>
* public static void main(String[] args)
* {
* Converter converter = new Converter();
* try
* {
* // first define options
* Options options = converter.defineOptions();
* // And then parse them.
* CommandLine cmdLine = converter.parseOptions(options, args);
* // Finally, run the converter.
* converter.run(cmdLine);
* }
* catch (Exception exception)
* {
* System.err.printf("Error: %s\n", exception.getMessage());
* }
* }
* </pre>
*
* <p>
*
* Pass "--help" to your main class as the argument to see the list of
* accepted options.
*
* </p>
*
* @author aclarke
*
*/
public class Converter
{
static
{
// this forces the FFMPEG io library to be loaded which means we can bypass
// FFMPEG's file io if needed
URLProtocolManager.getManager();
}
/**
* Create a new Converter object.
*/
public Converter()
{
}
private final Logger log = LoggerFactory.getLogger(this.getClass());
/**
* A container we'll use to read data from.
*/
private IContainer mIContainer = null;
/**
* A container we'll use to write data from.
*/
private IContainer mOContainer = null;
/**
* A set of {@link IStream} values for each stream in the input
* {@link IContainer}.
*/
private IStream[] mIStreams = null;
/**
* A set of {@link IStreamCoder} objects we'll use to decode audio and video.
*/
private IStreamCoder[] mICoders = null;
/**
* A set of {@link IStream} objects for each stream we'll output to the output
* {@link IContainer}.
*/
private IStream[] mOStreams = null;
/**
* A set of {@link IStreamCoder} objects we'll use to encode audio and video.
*/
private IStreamCoder[] mOCoders = null;
/**
* A set of {@link IVideoPicture} objects that we'll use to hold decoded video
* data.
*/
private IVideoPicture[] mIVideoPictures = null;
/**
* A set of {@link IVideoPicture} objects we'll use to hold
* potentially-resampled video data before we encode it.
*/
private IVideoPicture[] mOVideoPictures = null;
/**
* A set of {@link IAudioSamples} objects we'll use to hold decoded audio
* data.
*/
private IAudioSamples[] mISamples = null;
/**
* A set of {@link IAudioSamples} objects we'll use to hold
* potentially-resampled audio data before we encode it.
*/
private IAudioSamples[] mOSamples = null;
/**
* A set of {@link IAudioResampler} objects (one for each stream) we'll use to
* resample audio if needed.
*/
private IAudioResampler[] mASamplers = null;
/**
* A set of {@link IVideoResampler} objects (one for each stream) we'll use to
* resample video if needed.
*/
private IVideoResampler[] mVSamplers = null;
/**
* Should we convert audio
*/
private boolean mHasAudio = true;
/**
* Should we convert video
*/
private boolean mHasVideo = true;
/**
* Should we force an interleaving of the output
*/
private final boolean mForceInterleave = true;
/**
* Should we attempt to encode 'in real time'
*/
private boolean mRealTimeEncoder;
private Long mStartClockTime;
private Long mStartStreamTime;
/**
* Define all the command line options this program can take.
*
* @return The set of accepted options.
*/
public Options defineOptions()
{
Options options = new Options();
Option help = new Option("help", "print this message");
/*
* Output container options.
*/
OptionBuilder.withArgName("container-format");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("output container format to use (e.g. \"mov\")");
Option containerFormat = OptionBuilder.create("containerformat");
OptionBuilder.withArgName("icontainer-format");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("input container format to use (e.g. \"mov\")");
Option icontainerFormat = OptionBuilder.create("icontainerformat");
OptionBuilder.withArgName("file");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("container option presets file");
Option cpreset = OptionBuilder.create("cpreset");
/*
* Audio options
*/
OptionBuilder.hasArg(false);
OptionBuilder.withDescription("no audio");
Option ano = OptionBuilder.create("ano");
OptionBuilder.withArgName("file");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("audio option presets file");
Option apreset = OptionBuilder.create("apreset");
OptionBuilder.withArgName("codec");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("audio codec to encode with (e.g. \"libmp3lame\")");
Option acodec = OptionBuilder.create("acodec");
OptionBuilder.withArgName("icodec");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("input audio codec (e.g. \"libmp3lame\")");
Option iacodec = OptionBuilder.create("iacodec");
OptionBuilder.withArgName("sample-rate");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("audio sample rate to (up/down) encode with (in hz) (e.g. \"22050\")");
Option asamplerate = OptionBuilder.create("asamplerate");
OptionBuilder.withArgName("isample-rate");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("input audio sample rate to (up/down) encode with (in hz) (e.g. \"22050\")");
Option iasamplerate = OptionBuilder.create("iasamplerate");
OptionBuilder.withArgName("channels");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("number of audio channels (1 or 2) to encode with (e.g. \"2\")");
Option achannels = OptionBuilder.create("achannels");
OptionBuilder.withArgName("ichannels");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("input number of audio channels (1 or 2)");
Option iachannels = OptionBuilder.create("iachannels");
OptionBuilder.withArgName("abit-rate");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("bit rate to encode audio with (in bps) (e.g. \"60000\")");
Option abitrate = OptionBuilder.create("abitrate");
OptionBuilder.withArgName("stream");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("if multiple audio streams of a given type, this is the stream you want to output");
Option astream = OptionBuilder.create("astream");
OptionBuilder.withArgName("quality");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("quality setting to use for audio. 0 means same as source; higher numbers are (perversely) lower quality. Defaults to 0.");
Option aquality = OptionBuilder.create("aquality");
/*
* Video options
*/
OptionBuilder.hasArg(false);
OptionBuilder.withDescription("no video");
Option vno = OptionBuilder.create("vno");
OptionBuilder.withArgName("file");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("video option presets file");
Option vpreset = OptionBuilder.create("vpreset");
OptionBuilder.withArgName("codec");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("video codec to encode with (e.g. \"mpeg4\")");
Option vcodec = OptionBuilder.create("vcodec");
OptionBuilder.withArgName("factor");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("scaling factor to scale output video by (e.g. \"0.75\")");
Option vscaleFactor = OptionBuilder.create("vscalefactor");
OptionBuilder.withArgName("vbitrate");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("bit rate to encode video with (in bps) (e.g. \"60000\")");
Option vbitrate = OptionBuilder.create("vbitrate");
OptionBuilder.withArgName("vbitratetolerance");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("bit rate tolerance the bitstream is allowed to diverge from the reference (in bits) (e.g. \"1200000\")");
Option vbitratetolerance = OptionBuilder.create("vbitratetolerance");
OptionBuilder.withArgName("stream");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("if multiple video streams of a given type, this is the stream you want to output");
Option vstream = OptionBuilder.create("vstream");
OptionBuilder.withArgName("quality");
OptionBuilder.hasArg(true);
OptionBuilder
.withDescription("quality setting to use for video. 0 means same as source; higher numbers are (perversely) lower quality. Defaults to 0. If set, then bitrate flags are ignored.");
Option vquality = OptionBuilder.create("vquality");
OptionBuilder.withArgName("realtime");
OptionBuilder.hasArg(false);
OptionBuilder.withDescription("attempt to encode frames at the realtime rate -- i.e. it encodes when the picture should play");
Option realtime = OptionBuilder.create("realtime");
options.addOption(help);
options.addOption(containerFormat);
options.addOption(cpreset);
options.addOption(ano);
options.addOption(apreset);
options.addOption(acodec);
options.addOption(asamplerate);
options.addOption(achannels);
options.addOption(abitrate);
options.addOption(astream);
options.addOption(aquality);
options.addOption(vno);
options.addOption(vpreset);
options.addOption(vcodec);
options.addOption(vscaleFactor);
options.addOption(vbitrate);
options.addOption(vbitratetolerance);
options.addOption(vstream);
options.addOption(vquality);
options.addOption(icontainerFormat);
options.addOption(iacodec);
options.addOption(iachannels);
options.addOption(iasamplerate);
options.addOption(realtime);
return options;
}
/**
* Given a set of arguments passed into this object, return back a parsed
* command line.
*
* @param opt
* A set of options as defined by {@link #defineOptions()}.
* @param args
* A set of command line arguments passed into this class.
* @return A parsed command line.
* @throws ParseException
* If there is an error in the command line.
*/
public CommandLine parseOptions(Options opt, String[] args)
throws ParseException
{
CommandLine cmdLine = null;
CommandLineParser parser = new GnuParser();
cmdLine = parser.parse(opt, args);
if (cmdLine.hasOption("help"))
{
HelpFormatter help = new HelpFormatter();
help.printHelp("Xuggler [options] input_url output_url", opt);
System.exit(1);
}
// Make sure we have only two left over args
if (cmdLine.getArgs().length != 2)
throw new ParseException("missing input or output url");
return cmdLine;
}
/**
* Get an integer value from a command line argument.
*
* @param cmdLine
* A parsed command line (as returned from
* {@link #parseOptions(Options, String[])}
* @param key
* The key for an option you want.
* @param defaultVal
* The default value you want set if the key is not present in
* cmdLine.
* @return The value for the key in the cmdLine, or defaultVal if it's not
* there.
*/
private int getIntOptionValue(CommandLine cmdLine, String key, int defaultVal)
{
int retval = defaultVal;
String optValue = cmdLine.getOptionValue(key);
if (optValue != null)
{
try
{
retval = Integer.parseInt(optValue);
}
catch (Exception ex)
{
log
.warn(
"Option \"{}\" value \"{}\" cannot be converted to integer; using {} instead",
new Object[]
{
key, optValue, defaultVal
});
}
}
return retval;
}
/**
* Get a double value from a command line argument.
*
* @param cmdLine
* A parsed command line (as returned from
* {@link #parseOptions(Options, String[])}
* @param key
* The key for an option you want.
* @param defaultVal
* The default value you want set if the key is not present in
* cmdLine.
* @return The value for the key in the cmdLine, or defaultVal if it's not
* there.
*/
private double getDoubleOptionValue(CommandLine cmdLine, String key,
double defaultVal)
{
double retval = defaultVal;
String optValue = cmdLine.getOptionValue(key);
if (optValue != null)
{
try
{
retval = Double.parseDouble(optValue);
}
catch (Exception ex)
{
log
.warn(
"Option \"{}\" value \"{}\" cannot be converted to double; using {} instead",
new Object[]
{
key, optValue, defaultVal
});
}
}
return retval;
}
/**
* Open an initialize all Xuggler objects needed to encode and decode a video
* file.
*
* @param cmdLine
* A command line (as returned from
* {@link #parseOptions(Options, String[])}) that specifies what
* files we want to process and how to process them.
* @return Number of streams in the input file, or <= 0 on error.
*/
int setupStreams(CommandLine cmdLine)
{
String inputURL = cmdLine.getArgs()[0];
String outputURL = cmdLine.getArgs()[1];
mHasAudio = !cmdLine.hasOption("ano");
mHasVideo = !cmdLine.hasOption("vno");
mRealTimeEncoder = cmdLine.hasOption("realtime");
String acodec = cmdLine.getOptionValue("acodec");
String vcodec = cmdLine.getOptionValue("vcodec");
String containerFormat = cmdLine.getOptionValue("containerformat");
int astream = getIntOptionValue(cmdLine, "astream", -1);
int aquality = getIntOptionValue(cmdLine, "aquality", 0);
int sampleRate = getIntOptionValue(cmdLine, "asamplerate", 0);
int channels = getIntOptionValue(cmdLine, "achannels", 0);
int abitrate = getIntOptionValue(cmdLine, "abitrate", 0);
int vbitrate = getIntOptionValue(cmdLine, "vbitrate", 0);
int vbitratetolerance = getIntOptionValue(cmdLine, "vbitratetolerance", 0);
int vquality = getIntOptionValue(cmdLine, "vquality", -1);
int vstream = getIntOptionValue(cmdLine, "vstream", -1);
double vscaleFactor = getDoubleOptionValue(cmdLine, "vscalefactor", 1.0);
String icontainerFormat = cmdLine.getOptionValue("icontainerformat");
String iacodec = cmdLine.getOptionValue("iacodec");
int isampleRate = getIntOptionValue(cmdLine, "iasamplerate", 0);
int ichannels = getIntOptionValue(cmdLine, "iachannels", 0);
// Should have everything now!
int retval = 0;
/**
* Create one container for input, and one for output.
*/
mIContainer = IContainer.make();
mOContainer = IContainer.make();
String cpreset = cmdLine.getOptionValue("cpreset");
if (cpreset != null)
Configuration.configure(cpreset, mOContainer);
IContainerFormat iFmt = null;
IContainerFormat oFmt = null;
// override input format
if (icontainerFormat != null)
{
iFmt = IContainerFormat.make();
/**
* Try to find an output format based on what the user specified, or
* failing that, based on the outputURL (e.g. if it ends in .flv, we'll
* guess FLV).
*/
retval = iFmt.setInputFormat(icontainerFormat);
if (retval < 0)
throw new RuntimeException("could not find input container format: "
+ icontainerFormat);
}
// override the input codec
if (iacodec != null)
{
ICodec codec = null;
/**
* Looks like they did specify one; let's look it up by name.
*/
codec = ICodec.findDecodingCodecByName(iacodec);
if (codec == null || codec.getType() != ICodec.Type.CODEC_TYPE_AUDIO)
throw new RuntimeException("could not find decoder: " + iacodec);
/**
* Now, tell the output stream coder that it's to use that codec.
*/
mIContainer.setForcedAudioCodec(codec.getID());
}
/**
* Open the input container for Reading.
*/
IMetaData parameters = IMetaData.make();
if (isampleRate > 0)
parameters.setValue("sample_rate", ""+isampleRate);
if (ichannels > 0)
parameters.setValue("channels", ""+ichannels);
IMetaData rejectParameters = IMetaData.make();
retval = mIContainer.open(inputURL, IContainer.Type.READ, iFmt, false, true,
parameters, rejectParameters);
if (retval < 0)
throw new RuntimeException("could not open url: " + inputURL);
if (rejectParameters.getNumKeys() > 0)
throw new RuntimeException("some parameters were rejected: " + rejectParameters);
/**
* If the user EXPLICITLY asked for a output container format, we'll try to
* honor their request here.
*/
if (containerFormat != null)
{
oFmt = IContainerFormat.make();
/**
* Try to find an output format based on what the user specified, or
* failing that, based on the outputURL (e.g. if it ends in .flv, we'll
* guess FLV).
*/
retval = oFmt.setOutputFormat(containerFormat, outputURL, null);
if (retval < 0)
throw new RuntimeException("could not find output container format: "
+ containerFormat);
}
/**
* Open the output container for writing. If oFmt is null, we are telling
* Xuggler to guess the output container format based on the outputURL.
*/
retval = mOContainer.open(outputURL, IContainer.Type.WRITE, oFmt);
if (retval < 0)
throw new RuntimeException("could not open output url: " + outputURL);
/**
* Find out how many streams are there in the input container? For example,
* most FLV files will have 2 -- 1 audio stream and 1 video stream.
*/
int numStreams = mIContainer.getNumStreams();
if (numStreams <= 0)
throw new RuntimeException("not streams in input url: " + inputURL);
/**
* Here we create IStream, IStreamCoders and other objects for each input
* stream.
*
* We make parallel objects for each output stream as well.
*/
mIStreams = new IStream[numStreams];
mICoders = new IStreamCoder[numStreams];
mOStreams = new IStream[numStreams];
mOCoders = new IStreamCoder[numStreams];
mASamplers = new IAudioResampler[numStreams];
mVSamplers = new IVideoResampler[numStreams];
mIVideoPictures = new IVideoPicture[numStreams];
mOVideoPictures = new IVideoPicture[numStreams];
mISamples = new IAudioSamples[numStreams];
mOSamples = new IAudioSamples[numStreams];
/**
* Now let's go through the input streams one by one and explicitly set up
* our contexts.
*/
for (int i = 0; i < numStreams; i++)
{
/**
* Get the IStream for this input stream.
*/
IStream is = mIContainer.getStream(i);
/**
* And get the input stream coder. Xuggler will set up all sorts of
* defaults on this StreamCoder for you (such as the audio sample rate)
* when you open it.
*
* You can create IStreamCoders yourself using
* IStreamCoder#make(IStreamCoder.Direction), but then you have to set all
* parameters yourself.
*/
IStreamCoder ic = is.getStreamCoder();
/**
* Find out what Codec Xuggler guessed the input stream was encoded with.
*/
ICodec.Type cType = ic.getCodecType();
mIStreams[i] = is;
mICoders[i] = ic;
mOStreams[i] = null;
mOCoders[i] = null;
mASamplers[i] = null;
mVSamplers[i] = null;
mIVideoPictures[i] = null;
mOVideoPictures[i] = null;
mISamples[i] = null;
mOSamples[i] = null;
if (cType == ICodec.Type.CODEC_TYPE_AUDIO && mHasAudio
&& (astream == -1 || astream == i))
{
/**
* First, did the user specify an audio codec?
*/
ICodec codec = null;
if (acodec != null)
{
/**
* Looks like they did specify one; let's look it up by name.
*/
codec = ICodec.findEncodingCodecByName(acodec);
if (codec == null || codec.getType() != cType)
throw new RuntimeException("could not find encoder: " + acodec);
}
else
{
/**
* Looks like the user didn't specify an output coder for audio.
*
* So we ask Xuggler to guess an appropriate output coded based on the
* URL, container format, and that it's audio.
*/
codec = ICodec.guessEncodingCodec(oFmt, null, outputURL, null,
cType);
if (codec == null)
throw new RuntimeException("could not guess " + cType
+ " encoder for: " + outputURL);
}
/**
* So it looks like this stream as an audio stream. Now we add an audio
* stream to the output container that we will use to encode our
* resampled audio.
*/
IStream os = mOContainer.addNewStream(codec);
/**
* And we ask the IStream for an appropriately configured IStreamCoder
* for output.
*
* Unfortunately you still need to specify a lot of things for
* outputting (because we can't really guess what you want to encode
* as).
*/
IStreamCoder oc = os.getStreamCoder();
mOStreams[i] = os;
mOCoders[i] = oc;
/**
* Now let's see if the codec can support the input sample format; if not
* we pick the last sample format the codec supports.
*/
Format preferredFormat = ic.getSampleFormat();
List<Format> formats = codec.getSupportedAudioSampleFormats();
for(Format format : formats) {
oc.setSampleFormat(format);
if (format == preferredFormat)
break;
}
final String apreset = cmdLine.getOptionValue("apreset");
if (apreset != null)
Configuration.configure(apreset, oc);
/**
* In general a IStreamCoder encoding audio needs to know: 1) A ICodec
* to use. 2) The sample rate and number of channels of the audio. Most
* everything else can be defaulted.
*/
/**
* If the user didn't specify a sample rate to encode as, then just use
* the same sample rate as the input.
*/
if (sampleRate == 0)
sampleRate = ic.getSampleRate();
oc.setSampleRate(sampleRate);
/**
* If the user didn't specify a bit rate to encode as, then just use the
* same bit as the input.
*/
if (abitrate == 0)
abitrate = ic.getBitRate();
if (abitrate == 0)
// some containers don't give a bit-rate
abitrate = 64000;
oc.setBitRate(abitrate);
/**
* If the user didn't specify the number of channels to encode audio as,
* just assume we're keeping the same number of channels.
*/
if (channels == 0)
channels = ic.getChannels();
oc.setChannels(channels);
/**
* And set the quality (which defaults to 0, or highest, if the user
* doesn't tell us one).
*/
oc.setGlobalQuality(aquality);
/**
* Now check if our output channels or sample rate differ from our input
* channels or sample rate.
*
* If they do, we're going to need to resample the input audio to be in
* the right format to output.
*/
if (oc.getChannels() != ic.getChannels()
|| oc.getSampleRate() != ic.getSampleRate()
|| oc.getSampleFormat() != ic.getSampleFormat())
{
/**
* Create an audio resampler to do that job.
*/
mASamplers[i] = IAudioResampler.make(oc.getChannels(), ic
.getChannels(), oc.getSampleRate(), ic.getSampleRate(),
oc.getSampleFormat(), ic.getSampleFormat());
if (mASamplers[i] == null)
{
throw new RuntimeException(
"could not open audio resampler for stream: " + i);
}
}
else
{
mASamplers[i] = null;
}
/**
* Finally, create some buffers for the input and output audio
* themselves.
*
* We'll use these repeated during the #run(CommandLine) method.
*/
mISamples[i] = IAudioSamples.make(1024, ic.getChannels(), ic.getSampleFormat());
mOSamples[i] = IAudioSamples.make(1024, oc.getChannels(), oc.getSampleFormat());
}
else if (cType == ICodec.Type.CODEC_TYPE_VIDEO && mHasVideo
&& (vstream == -1 || vstream == i))
{
/**
* If you're reading these commends, this does the same thing as the
* above branch, only for video. I'm going to assume you read those
* comments and will only document something substantially different
* here.
*/
ICodec codec = null;
if (vcodec != null)
{
codec = ICodec.findEncodingCodecByName(vcodec);
if (codec == null || codec.getType() != cType)
throw new RuntimeException("could not find encoder: " + vcodec);
}
else
{
codec = ICodec.guessEncodingCodec(oFmt, null, outputURL, null,
cType);
if (codec == null)
throw new RuntimeException("could not guess " + cType
+ " encoder for: " + outputURL);
}
final IStream os = mOContainer.addNewStream(codec);
final IStreamCoder oc = os.getStreamCoder();
mOStreams[i] = os;
mOCoders[i] = oc;
// Set options AFTER selecting codec
final String vpreset = cmdLine.getOptionValue("vpreset");
if (vpreset != null)
Configuration.configure(vpreset, oc);
/**
* In general a IStreamCoder encoding video needs to know: 1) A ICodec
* to use. 2) The Width and Height of the Video 3) The pixel format
* (e.g. IPixelFormat.Type#YUV420P) of the video data. Most everything
* else can be defaulted.
*/
if (vbitrate == 0)
vbitrate = ic.getBitRate();
if (vbitrate == 0)
vbitrate = 250000;
oc.setBitRate(vbitrate);
if (vbitratetolerance > 0)
oc.setBitRateTolerance(vbitratetolerance);
int oWidth = ic.getWidth();
int oHeight = ic.getHeight();
if (oHeight <= 0 || oWidth <= 0)
throw new RuntimeException("could not find width or height in url: "
+ inputURL);
/**
* For this program we don't allow the user to specify the pixel format
* type; we force the output to be the same as the input.
*/
oc.setPixelType(ic.getPixelType());
if (vscaleFactor != 1.0)
{
/**
* In this case, it looks like the output video requires rescaling, so
* we create a IVideoResampler to do that dirty work.
*/
oWidth = (int) (oWidth * vscaleFactor);
oHeight = (int) (oHeight * vscaleFactor);
mVSamplers[i] = IVideoResampler
.make(oWidth, oHeight, oc.getPixelType(), ic.getWidth(), ic
.getHeight(), ic.getPixelType());
if (mVSamplers[i] == null)
{
throw new RuntimeException(
"This version of Xuggler does not support video resampling "
+ i);
}
}
else
{
mVSamplers[i] = null;
}
oc.setHeight(oHeight);
oc.setWidth(oWidth);
if (vquality >= 0)
{
oc.setFlag(IStreamCoder.Flags.FLAG_QSCALE, true);
oc.setGlobalQuality(vquality);
}
/**
* TimeBases are important, especially for Video. In general Audio
* encoders will assume that any new audio happens IMMEDIATELY after any
* prior audio finishes playing. But for video, we need to make sure
* it's being output at the right rate.
*
* In this case we make sure we set the same time base as the input, and
* then we don't change the time stamps of any IVideoPictures.
*
* But take my word that time stamps are tricky, and this only touches
* the envelope. The good news is, it's easier in Xuggler than some
* other systems.
*/
IRational num = null;
num = ic.getFrameRate();
oc.setFrameRate(num);
oc.setTimeBase(IRational.make(num.getDenominator(), num
.getNumerator()));
num = null;
/**
* And allocate buffers for us to store decoded and resample video
* pictures.
*/
mIVideoPictures[i] = IVideoPicture.make(ic.getPixelType(), ic
.getWidth(), ic.getHeight());
mOVideoPictures[i] = IVideoPicture.make(oc.getPixelType(), oc
.getWidth(), oc.getHeight());
}