forked from bytedeco/javacv
/
FFmpegFrameRecorder.java
1365 lines (1223 loc) · 60.4 KB
/
FFmpegFrameRecorder.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
/*
* Copyright (C) 2009-2021 Samuel Audet
*
* Licensed either under the Apache License, Version 2.0, or (at your option)
* under the terms of the GNU General Public License as published by
* the Free Software Foundation (subject to the "Classpath" exception),
* either version 2, or any later version (collectively, the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/
* http://www.gnu.org/software/classpath/license.html
*
* or as provided in the LICENSE.txt file that accompanied this code.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Based on the output-example.c file included in FFmpeg 0.6.5
* as well as on the decoding_encoding.c file included in FFmpeg 0.11.1,
* and on the encode_video.c file included in FFmpeg 4.4,
* which are covered by the following copyright notice:
*
* Libavformat API example: Output a media file in any supported
* libavformat format. The default codecs are used.
*
* Copyright (c) 2001,2003 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.bytedeco.javacv;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.FloatPointer;
import org.bytedeco.javacpp.IntPointer;
import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacpp.Pointer;
import org.bytedeco.javacpp.PointerScope;
import org.bytedeco.javacpp.PointerPointer;
import org.bytedeco.javacpp.ShortPointer;
import org.bytedeco.ffmpeg.avcodec.*;
import org.bytedeco.ffmpeg.avdevice.*;
import org.bytedeco.ffmpeg.avformat.*;
import org.bytedeco.ffmpeg.avutil.*;
import org.bytedeco.ffmpeg.swresample.*;
import org.bytedeco.ffmpeg.swscale.*;
import static org.bytedeco.ffmpeg.global.avcodec.*;
import static org.bytedeco.ffmpeg.global.avdevice.*;
import static org.bytedeco.ffmpeg.global.avformat.*;
import static org.bytedeco.ffmpeg.global.avutil.*;
import static org.bytedeco.ffmpeg.global.swresample.*;
import static org.bytedeco.ffmpeg.global.swscale.*;
/**
*
* @author Samuel Audet
*/
public class FFmpegFrameRecorder extends FrameRecorder {
public static class Exception extends FrameRecorder.Exception {
public Exception(String message) { super(message + " (For more details, make sure FFmpegLogCallback.set() has been called.)"); }
public Exception(String message, Throwable cause) { super(message, cause); }
}
public static FFmpegFrameRecorder createDefault(File f, int w, int h) throws Exception { return new FFmpegFrameRecorder(f, w, h); }
public static FFmpegFrameRecorder createDefault(String f, int w, int h) throws Exception { return new FFmpegFrameRecorder(f, w, h); }
private static Exception loadingException = null;
public static void tryLoad() throws Exception {
if (loadingException != null) {
throw loadingException;
} else {
try {
Loader.load(org.bytedeco.ffmpeg.global.avutil.class);
Loader.load(org.bytedeco.ffmpeg.global.swresample.class);
Loader.load(org.bytedeco.ffmpeg.global.avcodec.class);
Loader.load(org.bytedeco.ffmpeg.global.avformat.class);
Loader.load(org.bytedeco.ffmpeg.global.swscale.class);
/* initialize libavcodec, and register all codecs and formats */
av_jni_set_java_vm(Loader.getJavaVM(), null);
avcodec_register_all();
av_register_all();
avformat_network_init();
Loader.load(org.bytedeco.ffmpeg.global.avdevice.class);
avdevice_register_all();
} catch (Throwable t) {
if (t instanceof Exception) {
throw loadingException = (Exception)t;
} else {
throw loadingException = new Exception("Failed to load " + FFmpegFrameRecorder.class, t);
}
}
}
}
static {
try {
tryLoad();
FFmpegLockCallback.init();
} catch (Exception ex) { }
}
public FFmpegFrameRecorder(File file, int audioChannels) {
this(file, 0, 0, audioChannels);
}
public FFmpegFrameRecorder(String filename, int audioChannels) {
this(filename, 0, 0, audioChannels);
}
public FFmpegFrameRecorder(File file, int imageWidth, int imageHeight) {
this(file, imageWidth, imageHeight, 0);
}
public FFmpegFrameRecorder(String filename, int imageWidth, int imageHeight) {
this(filename, imageWidth, imageHeight, 0);
}
public FFmpegFrameRecorder(File file, int imageWidth, int imageHeight, int audioChannels) {
this(file.getAbsolutePath(), imageWidth, imageHeight, audioChannels);
}
public FFmpegFrameRecorder(String filename, int imageWidth, int imageHeight, int audioChannels) {
this.filename = filename;
this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
this.audioChannels = audioChannels;
this.pixelFormat = AV_PIX_FMT_NONE;
this.videoCodec = AV_CODEC_ID_NONE;
this.videoBitrate = 400000;
this.frameRate = 30;
this.sampleFormat = AV_SAMPLE_FMT_NONE;
this.audioCodec = AV_CODEC_ID_NONE;
this.audioBitrate = 64000;
this.sampleRate = 44100;
this.interleaved = true;
}
public FFmpegFrameRecorder(OutputStream outputStream, int audioChannels) {
this(outputStream.toString(), audioChannels);
this.outputStream = outputStream;
this.closeOutputStream = true;
}
public FFmpegFrameRecorder(OutputStream outputStream, int imageWidth, int imageHeight) {
this(outputStream.toString(), imageWidth, imageHeight);
this.outputStream = outputStream;
this.closeOutputStream = true;
}
public FFmpegFrameRecorder(OutputStream outputStream, int imageWidth, int imageHeight, int audioChannels) {
this(outputStream.toString(), imageWidth, imageHeight, audioChannels);
this.outputStream = outputStream;
this.closeOutputStream = true;
}
public void release() throws Exception {
synchronized (org.bytedeco.ffmpeg.global.avcodec.class) {
releaseUnsafe();
}
}
public synchronized void releaseUnsafe() throws Exception {
started = false;
if (plane_ptr != null && plane_ptr2 != null) {
plane_ptr.releaseReference();
plane_ptr2.releaseReference();
plane_ptr = plane_ptr2 = null;
}
if (video_pkt != null && audio_pkt != null) {
video_pkt.releaseReference();
audio_pkt.releaseReference();
video_pkt = audio_pkt = null;
}
/* close each codec */
if (video_c != null) {
avcodec_free_context(video_c);
video_c = null;
}
if (audio_c != null) {
avcodec_free_context(audio_c);
audio_c = null;
}
if (picture_buf != null) {
av_free(picture_buf);
picture_buf = null;
}
if (picture != null) {
av_frame_free(picture);
picture = null;
}
if (tmp_picture != null) {
av_frame_free(tmp_picture);
tmp_picture = null;
}
if (video_outbuf != null) {
av_free(video_outbuf);
video_outbuf = null;
}
if (frame != null) {
av_frame_free(frame);
frame = null;
}
if (samples_in != null) {
for (int i = 0; i < samples_in.length; i++) {
if (samples_in[i] != null) {
samples_in[i].releaseReference();
}
}
samples_in = null;
}
if (samples_out != null) {
for (int i = 0; i < samples_out.length; i++) {
av_free(samples_out[i].position(0));
}
samples_out = null;
}
if (audio_outbuf != null) {
av_free(audio_outbuf);
audio_outbuf = null;
}
if (video_st != null && video_st.metadata() != null) {
av_dict_free(video_st.metadata());
video_st.metadata(null);
}
if (audio_st != null && audio_st.metadata() != null) {
av_dict_free(audio_st.metadata());
audio_st.metadata(null);
}
video_st = null;
audio_st = null;
filename = null;
AVFormatContext outputStreamKey = oc;
if (oc != null && !oc.isNull()) {
if (outputStream == null && (oformat.flags() & AVFMT_NOFILE) == 0) {
/* close the output file */
avio_close(oc.pb());
}
/* free the streams */
avformat_free_context(oc);
oc = null;
}
if (img_convert_ctx != null) {
sws_freeContext(img_convert_ctx);
img_convert_ctx = null;
}
if (samples_convert_ctx != null) {
swr_free(samples_convert_ctx);
samples_convert_ctx = null;
}
if (outputStream != null) {
try {
if (closeOutputStream) {
outputStream.close();
}
} catch (IOException ex) {
throw new Exception("Error on OutputStream.close(): ", ex);
} finally {
outputStream = null;
outputStreams.remove(outputStreamKey);
if (avio != null) {
if (avio.buffer() != null) {
av_free(avio.buffer());
avio.buffer(null);
}
av_free(avio);
avio = null;
}
}
}
}
@Override protected void finalize() throws Throwable {
super.finalize();
release();
}
static Map<Pointer,OutputStream> outputStreams = Collections.synchronizedMap(new HashMap<Pointer,OutputStream>());
static class WriteCallback extends Write_packet_Pointer_BytePointer_int {
@Override public int call(Pointer opaque, BytePointer buf, int buf_size) {
try {
byte[] b = new byte[buf_size];
OutputStream os = outputStreams.get(opaque);
buf.get(b, 0, buf_size);
os.write(b, 0, buf_size);
return buf_size;
}
catch (Throwable t) {
System.err.println("Error on OutputStream.write(): " + t);
return -1;
}
}
}
static WriteCallback writeCallback = new WriteCallback().retainReference();
static class SeekCallback extends Seek_Pointer_long_int {
@Override public long call(Pointer opaque, long offset, int whence) {
try {
OutputStream os = outputStreams.get(opaque);
((Seekable)os).seek(offset, whence);
return 0;
}
catch (Throwable t) {
System.err.println("Error on OutputStream.seek(): " + t);
return -1;
}
}
}
static SeekCallback seekCallback = new SeekCallback().retainReference();
private OutputStream outputStream;
private boolean closeOutputStream;
private AVIOContext avio;
private String filename;
private AVFrame picture, tmp_picture;
private BytePointer picture_buf;
private BytePointer video_outbuf;
private int video_outbuf_size;
private AVFrame frame;
private Pointer[] samples_in;
private BytePointer[] samples_out;
private BytePointer audio_outbuf;
private int audio_outbuf_size;
private int audio_input_frame_size;
private AVOutputFormat oformat;
private AVFormatContext oc;
private AVCodec video_codec, audio_codec;
private AVCodecContext video_c, audio_c;
private AVStream video_st, audio_st;
private SwsContext img_convert_ctx;
private SwrContext samples_convert_ctx;
private int samples_channels, samples_format, samples_rate;
private PointerPointer plane_ptr, plane_ptr2;
private AVPacket video_pkt, audio_pkt;
private int[] got_video_packet, got_audio_packet;
private AVFormatContext ifmt_ctx;
private volatile boolean started = false;
public boolean isCloseOutputStream() {
return closeOutputStream;
}
public void setCloseOutputStream(boolean closeOutputStream) {
this.closeOutputStream = closeOutputStream;
}
@Override public int getFrameNumber() {
return picture == null ? super.getFrameNumber() : (int)picture.pts();
}
@Override public void setFrameNumber(int frameNumber) {
if (picture == null) { super.setFrameNumber(frameNumber); } else { picture.pts(frameNumber); }
}
/** Returns best guess for timestamp in microseconds... */
@Override public long getTimestamp() {
return Math.round(getFrameNumber() * 1000000L / getFrameRate());
}
@Override public void setTimestamp(long timestamp) {
setFrameNumber((int)Math.round(timestamp * getFrameRate() / 1000000L));
}
public void start(AVFormatContext inputFormatContext) throws Exception {
this.ifmt_ctx = inputFormatContext;
start();
}
@Override public void start() throws Exception {
synchronized (org.bytedeco.ffmpeg.global.avcodec.class) {
startUnsafe();
}
}
public synchronized void startUnsafe() throws Exception {
try (PointerScope scope = new PointerScope()) {
if (oc != null && !oc.isNull()) {
throw new Exception("start() has already been called: Call stop() before calling start() again.");
}
int ret;
picture = null;
tmp_picture = null;
picture_buf = null;
frame = null;
video_outbuf = null;
audio_outbuf = null;
oc = new AVFormatContext(null);
video_c = null;
audio_c = null;
video_st = null;
audio_st = null;
plane_ptr = new PointerPointer(AVFrame.AV_NUM_DATA_POINTERS).retainReference();
plane_ptr2 = new PointerPointer(AVFrame.AV_NUM_DATA_POINTERS).retainReference();
video_pkt = new AVPacket().retainReference();
audio_pkt = new AVPacket().retainReference();
got_video_packet = new int[1];
got_audio_packet = new int[1];
/* auto detect the output format from the name. */
String format_name = format == null || format.length() == 0 ? null : format;
if ((oformat = av_guess_format(format_name, filename, null)) == null) {
int proto = filename.indexOf("://");
if (proto > 0) {
format_name = filename.substring(0, proto);
}
if ((oformat = av_guess_format(format_name, filename, null)) == null) {
throw new Exception("av_guess_format() error: Could not guess output format for \"" + filename + "\" and " + format + " format.");
}
}
format_name = oformat.name().getString();
/* allocate the output media context */
if (avformat_alloc_output_context2(oc, null, format_name, filename) < 0) {
throw new Exception("avformat_alloc_context2() error:\tCould not allocate format context");
}
if (outputStream != null) {
avio = avio_alloc_context(new BytePointer(av_malloc(4096)), 4096, 1, oc, null, writeCallback, outputStream instanceof Seekable ? seekCallback : null);
oc.pb(avio);
filename = outputStream.toString();
outputStreams.put(oc, outputStream);
}
oc.oformat(oformat);
oc.filename().putString(filename);
oc.max_delay(maxDelay);
/* add the audio and video streams using the format codecs
and initialize the codecs */
AVStream inpVideoStream = null, inpAudioStream = null;
if (ifmt_ctx != null) {
// get input video and audio stream indices from ifmt_ctx
for (int idx = 0; idx < ifmt_ctx.nb_streams(); idx++) {
AVStream inputStream = ifmt_ctx.streams(idx);
if (inputStream.codec().codec_type() == AVMEDIA_TYPE_VIDEO) {
inpVideoStream = inputStream;
videoCodec = inpVideoStream.codec().codec_id();
if (inpVideoStream.r_frame_rate().num() != AV_NOPTS_VALUE && inpVideoStream.r_frame_rate().den() != 0) {
frameRate = (inpVideoStream.r_frame_rate().num())*1.0d / (inpVideoStream.r_frame_rate().den());
}
} else if (inputStream.codec().codec_type() == AVMEDIA_TYPE_AUDIO) {
inpAudioStream = inputStream;
audioCodec = inpAudioStream.codec().codec_id();
}
}
}
if (imageWidth > 0 && imageHeight > 0) {
if (videoCodec != AV_CODEC_ID_NONE) {
oformat.video_codec(videoCodec);
} else if ("flv".equals(format_name)) {
oformat.video_codec(AV_CODEC_ID_FLV1);
} else if ("mp4".equals(format_name)) {
oformat.video_codec(AV_CODEC_ID_MPEG4);
} else if ("3gp".equals(format_name)) {
oformat.video_codec(AV_CODEC_ID_H263);
} else if ("avi".equals(format_name)) {
oformat.video_codec(AV_CODEC_ID_HUFFYUV);
}
/* find the video encoder */
if ((video_codec = avcodec_find_encoder_by_name(videoCodecName)) == null &&
(video_codec = avcodec_find_encoder(oformat.video_codec())) == null) {
releaseUnsafe();
throw new Exception("avcodec_find_encoder() error: Video codec not found.");
}
oformat.video_codec(video_codec.id());
AVRational frame_rate = av_d2q(frameRate, 1001000);
AVRational supported_framerates = video_codec.supported_framerates();
if (supported_framerates != null) {
int idx = av_find_nearest_q_idx(frame_rate, supported_framerates);
frame_rate = supported_framerates.position(idx);
}
/* add a video output stream */
if ((video_st = avformat_new_stream(oc, null)) == null) {
releaseUnsafe();
throw new Exception("avformat_new_stream() error: Could not allocate video stream.");
}
if ((video_c = avcodec_alloc_context3(video_codec)) == null) {
releaseUnsafe();
throw new Exception("avcodec_alloc_context3() error: Could not allocate video encoding context.");
}
if (inpVideoStream != null) {
if ((ret = avcodec_copy_context(video_st.codec(), inpVideoStream.codec())) < 0) {
releaseUnsafe();
throw new Exception("avcodec_copy_context() error:\tFailed to copy context from input to output stream codec context");
}
videoBitrate = (int) inpVideoStream.codec().bit_rate();
pixelFormat = inpVideoStream.codec().pix_fmt();
aspectRatio = inpVideoStream.codec().sample_aspect_ratio().num()*1.0d/ inpVideoStream.codec().sample_aspect_ratio().den();
videoQuality = inpVideoStream.codec().global_quality();
video_c.codec_tag(0);
}
video_c.codec_id(oformat.video_codec());
video_c.codec_type(AVMEDIA_TYPE_VIDEO);
/* put sample parameters */
video_c.bit_rate(videoBitrate);
/* resolution must be a multiple of two. Scale height to maintain the aspect ratio. */
if (imageWidth % 2 == 1) {
int roundedWidth = imageWidth + 1;
imageHeight = (roundedWidth * imageHeight + imageWidth / 2) / imageWidth;
imageWidth = roundedWidth;
}
video_c.width(imageWidth);
video_c.height(imageHeight);
if (aspectRatio > 0) {
AVRational r = av_d2q(aspectRatio, 255);
video_c.sample_aspect_ratio(r);
video_st.sample_aspect_ratio(r);
}
/* time base: this is the fundamental unit of time (in seconds) in terms
of which frame timestamps are represented. for fixed-fps content,
timebase should be 1/framerate and timestamp increments should be
identically 1. */
AVRational time_base = av_inv_q(frame_rate);
video_c.time_base(time_base);
video_st.time_base(time_base);
video_st.avg_frame_rate(frame_rate);
video_st.codec().time_base(time_base); // "deprecated", but this is actually required
if (gopSize >= 0) {
video_c.gop_size(gopSize); /* emit one intra frame every gopSize frames at most */
}
if (videoQuality >= 0) {
video_c.flags(video_c.flags() | AV_CODEC_FLAG_QSCALE);
video_c.global_quality((int)Math.round(FF_QP2LAMBDA * videoQuality));
}
if (pixelFormat != AV_PIX_FMT_NONE) {
video_c.pix_fmt(pixelFormat);
} else if (video_c.codec_id() == AV_CODEC_ID_RAWVIDEO || video_c.codec_id() == AV_CODEC_ID_PNG ||
video_c.codec_id() == AV_CODEC_ID_HUFFYUV || video_c.codec_id() == AV_CODEC_ID_FFV1) {
video_c.pix_fmt(AV_PIX_FMT_RGB32); // appropriate for common lossless formats
} else if (video_c.codec_id() == AV_CODEC_ID_JPEGLS) {
video_c.pix_fmt(AV_PIX_FMT_BGR24);
} else if (video_c.codec_id() == AV_CODEC_ID_MJPEG || video_c.codec_id() == AV_CODEC_ID_MJPEGB) {
video_c.pix_fmt(AV_PIX_FMT_YUVJ420P);
} else {
video_c.pix_fmt(AV_PIX_FMT_YUV420P); // lossy, but works with about everything
}
if (video_c.codec_id() == AV_CODEC_ID_MPEG2VIDEO) {
/* just for testing, we also add B frames */
video_c.max_b_frames(2);
} else if (video_c.codec_id() == AV_CODEC_ID_MPEG1VIDEO) {
/* Needed to avoid using macroblocks in which some coeffs overflow.
This does not happen with normal video, it just happens here as
the motion of the chroma plane does not match the luma plane. */
video_c.mb_decision(2);
} else if (video_c.codec_id() == AV_CODEC_ID_H263) {
// H.263 does not support any other resolution than the following
if (imageWidth <= 128 && imageHeight <= 96) {
video_c.width(128).height(96);
} else if (imageWidth <= 176 && imageHeight <= 144) {
video_c.width(176).height(144);
} else if (imageWidth <= 352 && imageHeight <= 288) {
video_c.width(352).height(288);
} else if (imageWidth <= 704 && imageHeight <= 576) {
video_c.width(704).height(576);
} else {
video_c.width(1408).height(1152);
}
} else if (video_c.codec_id() == AV_CODEC_ID_H264) {
// default to constrained baseline to produce content that plays back on anything,
// without any significant tradeoffs for most use cases
video_c.profile(AVCodecContext.FF_PROFILE_H264_CONSTRAINED_BASELINE);
}
// some formats want stream headers to be separate
if ((oformat.flags() & AVFMT_GLOBALHEADER) != 0) {
video_c.flags(video_c.flags() | AV_CODEC_FLAG_GLOBAL_HEADER);
}
if ((video_codec.capabilities() & AV_CODEC_CAP_EXPERIMENTAL) != 0) {
video_c.strict_std_compliance(AVCodecContext.FF_COMPLIANCE_EXPERIMENTAL);
}
if (maxBFrames >= 0) {
video_c.max_b_frames(maxBFrames);
video_c.has_b_frames(maxBFrames == 0 ? 0 : 1);
}
if (trellis >= 0) {
video_c.trellis(trellis);
}
}
/*
* add an audio output stream
*/
if (audioChannels > 0 && audioBitrate > 0 && sampleRate > 0) {
if (audioCodec != AV_CODEC_ID_NONE) {
oformat.audio_codec(audioCodec);
} else if ("flv".equals(format_name) || "mp4".equals(format_name) || "3gp".equals(format_name)) {
oformat.audio_codec(AV_CODEC_ID_AAC);
} else if ("avi".equals(format_name)) {
oformat.audio_codec(AV_CODEC_ID_PCM_S16LE);
}
/* find the audio encoder */
if ((audio_codec = avcodec_find_encoder_by_name(audioCodecName)) == null &&
(audio_codec = avcodec_find_encoder(oformat.audio_codec())) == null) {
releaseUnsafe();
throw new Exception("avcodec_find_encoder() error: Audio codec not found.");
}
oformat.audio_codec(audio_codec.id());
AVRational sample_rate = av_d2q(sampleRate, 1001000);
if ((audio_st = avformat_new_stream(oc, null)) == null) {
releaseUnsafe();
throw new Exception("avformat_new_stream() error: Could not allocate audio stream.");
}
if ((audio_c = avcodec_alloc_context3(audio_codec)) == null) {
releaseUnsafe();
throw new Exception("avcodec_alloc_context3() error: Could not allocate audio encoding context.");
}
if (inpAudioStream != null && audioChannels > 0) {
if ((ret = avcodec_copy_context(audio_st.codec(), inpAudioStream.codec())) < 0) {
throw new Exception("avcodec_copy_context() error " + ret + ": Failed to copy context from input audio to output audio stream codec context\n");
}
audioBitrate = (int) inpAudioStream.codec().bit_rate();
sampleRate = inpAudioStream.codec().sample_rate();
audioChannels = inpAudioStream.codec().channels();
sampleFormat = inpAudioStream.codec().sample_fmt();
audioQuality = inpAudioStream.codec().global_quality();
audio_c.codec_tag(0);
// audio_st.pts(inpAudioStream.pts());
audio_st.duration(inpAudioStream.duration());
audio_st.time_base().num(inpAudioStream.time_base().num());
audio_st.time_base().den(inpAudioStream.time_base().den());
}
audio_c.codec_id(oformat.audio_codec());
audio_c.codec_type(AVMEDIA_TYPE_AUDIO);
/* put sample parameters */
audio_c.bit_rate(audioBitrate);
audio_c.sample_rate(sampleRate);
audio_c.channels(audioChannels);
audio_c.channel_layout(av_get_default_channel_layout(audioChannels));
if (sampleFormat != AV_SAMPLE_FMT_NONE) {
audio_c.sample_fmt(sampleFormat);
} else {
// use AV_SAMPLE_FMT_S16 by default, if available
audio_c.sample_fmt(AV_SAMPLE_FMT_FLTP);
IntPointer formats = audio_c.codec().sample_fmts();
for (int i = 0; formats.get(i) != -1; i++) {
if (formats.get(i) == AV_SAMPLE_FMT_S16) {
audio_c.sample_fmt(AV_SAMPLE_FMT_S16);
break;
}
}
}
AVRational time_base = av_inv_q(sample_rate);
audio_c.time_base(time_base);
audio_st.time_base(time_base);
audio_st.codec().time_base(time_base); // "deprecated", but this is actually required
switch (audio_c.sample_fmt()) {
case AV_SAMPLE_FMT_U8:
case AV_SAMPLE_FMT_U8P: audio_c.bits_per_raw_sample(8); break;
case AV_SAMPLE_FMT_S16:
case AV_SAMPLE_FMT_S16P: audio_c.bits_per_raw_sample(16); break;
case AV_SAMPLE_FMT_S32:
case AV_SAMPLE_FMT_S32P: audio_c.bits_per_raw_sample(32); break;
case AV_SAMPLE_FMT_FLT:
case AV_SAMPLE_FMT_FLTP: audio_c.bits_per_raw_sample(32); break;
case AV_SAMPLE_FMT_DBL:
case AV_SAMPLE_FMT_DBLP: audio_c.bits_per_raw_sample(64); break;
default: assert false;
}
if (audioQuality >= 0) {
audio_c.flags(audio_c.flags() | AV_CODEC_FLAG_QSCALE);
audio_c.global_quality((int)Math.round(FF_QP2LAMBDA * audioQuality));
}
// some formats want stream headers to be separate
if ((oformat.flags() & AVFMT_GLOBALHEADER) != 0) {
audio_c.flags(audio_c.flags() | AV_CODEC_FLAG_GLOBAL_HEADER);
}
if ((audio_codec.capabilities() & AV_CODEC_CAP_EXPERIMENTAL) != 0) {
audio_c.strict_std_compliance(AVCodecContext.FF_COMPLIANCE_EXPERIMENTAL);
}
}
/* now that all the parameters are set, we can open the audio and
video codecs and allocate the necessary encode buffers */
if (video_st != null && inpVideoStream == null) {
AVDictionary options = new AVDictionary(null);
if (videoQuality >= 0) {
av_dict_set(options, "crf", "" + videoQuality, 0);
}
for (Entry<String, String> e : videoOptions.entrySet()) {
av_dict_set(options, e.getKey(), e.getValue(), 0);
}
// Enable multithreading when available
video_c.thread_count(0);
/* open the codec */
if ((ret = avcodec_open2(video_c, video_codec, options)) < 0) {
releaseUnsafe();
av_dict_free(options);
throw new Exception("avcodec_open2() error " + ret + ": Could not open video codec.");
}
av_dict_free(options);
video_outbuf = null;
// if ((oformat.flags() & AVFMT_RAWPICTURE) == 0) {
// /* allocate output buffer */
// /* XXX: API change will be done */
// /* buffers passed into lav* can be allocated any way you prefer,
// as long as they're aligned enough for the architecture, and
// they're freed appropriately (such as using av_free for buffers
// allocated with av_malloc) */
// video_outbuf_size = Math.max(256 * 1024, 8 * video_c.width() * video_c.height()); // a la ffmpeg.c
// video_outbuf = new BytePointer(av_malloc(video_outbuf_size));
// }
/* allocate the encoded raw picture */
if ((picture = av_frame_alloc()) == null) {
releaseUnsafe();
throw new Exception("av_frame_alloc() error: Could not allocate picture.");
}
picture.pts(0); // magic required by libx264
int size = av_image_get_buffer_size(video_c.pix_fmt(), video_c.width(), video_c.height(), 1);
if ((picture_buf = new BytePointer(av_malloc(size))).isNull()) {
releaseUnsafe();
throw new Exception("av_malloc() error: Could not allocate picture buffer.");
}
/* if the output format is not equal to the image format, then a temporary
picture is needed too. It is then converted to the required output format */
if ((tmp_picture = av_frame_alloc()) == null) {
releaseUnsafe();
throw new Exception("av_frame_alloc() error: Could not allocate temporary picture.");
}
/* copy the stream parameters to the muxer */
if ((ret = avcodec_parameters_from_context(video_st.codecpar(), video_c)) < 0) {
releaseUnsafe();
throw new Exception("avcodec_parameters_from_context() error " + ret + ": Could not copy the video stream parameters.");
}
AVDictionary metadata = new AVDictionary(null);
for (Entry<String, String> e : videoMetadata.entrySet()) {
av_dict_set(metadata, new BytePointer(e.getKey(), charset), new BytePointer(e.getValue(), charset), 0);
}
video_st.metadata(metadata);
}
if (audio_st != null && inpAudioStream == null) {
AVDictionary options = new AVDictionary(null);
if (audioQuality >= 0) {
av_dict_set(options, "crf", "" + audioQuality, 0);
}
for (Entry<String, String> e : audioOptions.entrySet()) {
av_dict_set(options, e.getKey(), e.getValue(), 0);
}
// Enable multithreading when available
audio_c.thread_count(0);
/* open the codec */
if ((ret = avcodec_open2(audio_c, audio_codec, options)) < 0) {
releaseUnsafe();
av_dict_free(options);
throw new Exception("avcodec_open2() error " + ret + ": Could not open audio codec.");
}
av_dict_free(options);
audio_outbuf_size = 256 * 1024;
audio_outbuf = new BytePointer(av_malloc(audio_outbuf_size));
/* ugly hack for PCM codecs (will be removed ASAP with new PCM
support to compute the input frame size in samples */
if (audio_c.frame_size() <= 1) {
audio_outbuf_size = AV_INPUT_BUFFER_MIN_SIZE;
audio_input_frame_size = audio_outbuf_size / audio_c.channels();
switch (audio_c.codec_id()) {
case AV_CODEC_ID_PCM_S16LE:
case AV_CODEC_ID_PCM_S16BE:
case AV_CODEC_ID_PCM_U16LE:
case AV_CODEC_ID_PCM_U16BE:
audio_input_frame_size >>= 1;
break;
default:
break;
}
} else {
audio_input_frame_size = audio_c.frame_size();
}
//int bufferSize = audio_input_frame_size * audio_c.bits_per_raw_sample()/8 * audio_c.channels();
int planes = av_sample_fmt_is_planar(audio_c.sample_fmt()) != 0 ? (int)audio_c.channels() : 1;
int data_size = av_samples_get_buffer_size((IntPointer)null, audio_c.channels(),
audio_input_frame_size, audio_c.sample_fmt(), 1) / planes;
samples_out = new BytePointer[planes];
for (int i = 0; i < samples_out.length; i++) {
samples_out[i] = new BytePointer(av_malloc(data_size)).capacity(data_size);
}
samples_in = new Pointer[AVFrame.AV_NUM_DATA_POINTERS];
/* allocate the audio frame */
if ((frame = av_frame_alloc()) == null) {
releaseUnsafe();
throw new Exception("av_frame_alloc() error: Could not allocate audio frame.");
}
frame.pts(0); // magic required by libvorbis and webm
/* copy the stream parameters to the muxer */
if ((ret = avcodec_parameters_from_context(audio_st.codecpar(), audio_c)) < 0) {
releaseUnsafe();
throw new Exception("avcodec_parameters_from_context() error " + ret + ": Could not copy the audio stream parameters.");
}
AVDictionary metadata = new AVDictionary(null);
for (Entry<String, String> e : audioMetadata.entrySet()) {
av_dict_set(metadata, new BytePointer(e.getKey(), charset), new BytePointer(e.getValue(), charset), 0);
}
audio_st.metadata(metadata);
}
AVDictionary options = new AVDictionary(null);
for (Entry<String, String> e : this.options.entrySet()) {
av_dict_set(options, e.getKey(), e.getValue(), 0);
}
/* open the output file, if needed */
if (outputStream == null && (oformat.flags() & AVFMT_NOFILE) == 0) {
AVIOContext pb = new AVIOContext(null);
if ((ret = avio_open2(pb, filename, AVIO_FLAG_WRITE, null, options)) < 0) {
String errorMsg = "avio_open2 error() error " + ret + ": Could not open '" + filename + "'";
releaseUnsafe();
av_dict_free(options);
throw new Exception(errorMsg);
}
oc.pb(pb);
}
AVDictionary metadata = new AVDictionary(null);
for (Entry<String, String> e : this.metadata.entrySet()) {
av_dict_set(metadata, new BytePointer(e.getKey(), charset), new BytePointer(e.getValue(), charset), 0);
}
/* write the stream header, if any */
if ((ret = avformat_write_header(oc.metadata(metadata), options)) < 0) {
String errorMsg = "avformat_write_header error() error " + ret + ": Could not write header to '" + filename + "'";
releaseUnsafe();
av_dict_free(options);
throw new Exception(errorMsg);
}
av_dict_free(options);
if (av_log_get_level() >= AV_LOG_INFO) {
av_dump_format(oc, 0, filename, 1);
}
started = true;
}
}
public synchronized void flush() throws Exception {
synchronized (oc) {
/* flush all the buffers */
while (video_st != null && ifmt_ctx == null && recordImage(0, 0, 0, 0, 0, AV_PIX_FMT_NONE, (Buffer[])null));
while (audio_st != null && ifmt_ctx == null && recordSamples(0, 0, (Buffer[])null));
if (interleaved && (video_st != null || audio_st != null)) {
av_interleaved_write_frame(oc, null);
} else {
av_write_frame(oc, null);
}
}
}
public void stop() throws Exception {
if (oc != null) {
try {
flush();
/* write the trailer, if any */
av_write_trailer(oc);
} finally {
release();
}
}
}
@Override public void record(Frame frame) throws Exception {
record(frame, frame != null && frame.opaque instanceof AVFrame ? ((AVFrame)frame.opaque).format() : AV_PIX_FMT_NONE);
}
public synchronized void record(Frame frame, int pixelFormat) throws Exception {
if (frame == null || (frame.image == null && frame.samples == null)) {
recordImage(0, 0, 0, 0, 0, pixelFormat, (Buffer[])null);
} else {
if (frame.image != null) {
frame.keyFrame = recordImage(frame.imageWidth, frame.imageHeight, frame.imageDepth,
frame.imageChannels, frame.imageStride, pixelFormat, frame.image);
}
if (frame.samples != null) {
frame.keyFrame = recordSamples(frame.sampleRate, frame.audioChannels, frame.samples);
}
}
}
public synchronized boolean recordImage(int width, int height, int depth, int channels, int stride, int pixelFormat, Buffer ... image) throws Exception {
try (PointerScope scope = new PointerScope()) {
if (video_st == null) {
throw new Exception("No video output stream (Is imageWidth > 0 && imageHeight > 0 and has start() been called?)");
}
if (!started) {
throw new Exception("start() was not called successfully!");
}
int ret;
if (image == null || image.length == 0) {
/* no more frame to compress. The codec has a latency of a few
frames if using B frames, so we get the last frames by
passing the same picture again */
} else {
int step = stride * Math.abs(depth) / 8;
BytePointer data = image[0] instanceof ByteBuffer
? new BytePointer((ByteBuffer)image[0]).position(0)
: new BytePointer(new Pointer(image[0]).position(0));
if (pixelFormat == AV_PIX_FMT_NONE) {
if ((depth == Frame.DEPTH_UBYTE || depth == Frame.DEPTH_BYTE) && channels == 3) {
pixelFormat = AV_PIX_FMT_BGR24;
} else if ((depth == Frame.DEPTH_UBYTE || depth == Frame.DEPTH_BYTE) && channels == 1) {
pixelFormat = AV_PIX_FMT_GRAY8;
} else if ((depth == Frame.DEPTH_USHORT || depth == Frame.DEPTH_SHORT) && channels == 1) {
pixelFormat = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN) ?
AV_PIX_FMT_GRAY16BE : AV_PIX_FMT_GRAY16LE;
} else if ((depth == Frame.DEPTH_UBYTE || depth == Frame.DEPTH_BYTE) && channels == 4) {
pixelFormat = AV_PIX_FMT_RGBA;
} else if ((depth == Frame.DEPTH_UBYTE || depth == Frame.DEPTH_BYTE) && channels == 2) {
pixelFormat = AV_PIX_FMT_NV21; // Android's camera capture format
} else {
throw new Exception("Could not guess pixel format of image: depth=" + depth + ", channels=" + channels);
}
}