/
VideoEncoder.java
554 lines (508 loc) · 18.3 KB
/
VideoEncoder.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
/*
* Copyright (C) 2023 pedroSG94.
*
* Licensed under the Apache License, Version 2.0 (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
*
* 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.
*/
package com.pedro.encoder.video;
import android.graphics.ImageFormat;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import com.pedro.common.av1.Av1Parser;
import com.pedro.common.av1.Obu;
import com.pedro.common.av1.ObuType;
import com.pedro.encoder.BaseEncoder;
import com.pedro.encoder.Frame;
import com.pedro.encoder.input.video.FpsLimiter;
import com.pedro.encoder.input.video.GetCameraData;
import com.pedro.encoder.utils.CodecUtil;
import com.pedro.encoder.utils.yuv.YUVUtil;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Created by pedro on 19/01/17.
* This class need use same resolution, fps and imageFormat that Camera1ApiManagerGl
*/
public class VideoEncoder extends BaseEncoder implements GetCameraData {
private final GetVideoData getVideoData;
private boolean spsPpsSetted = false;
private boolean forceKey = false;
//video data necessary to send after requestKeyframe.
private ByteBuffer oldSps, oldPps, oldVps;
//surface to buffer encoder
private Surface inputSurface;
private int width = 640;
private int height = 480;
private int fps = 30;
private int bitRate = 1200 * 1024; //in kbps
private int rotation = 90;
private int iFrameInterval = 2;
//for disable video
private final FpsLimiter fpsLimiter = new FpsLimiter();
private FormatVideoEncoder formatVideoEncoder = FormatVideoEncoder.YUV420Dynamical;
private int profile = -1;
private int level = -1;
public VideoEncoder(GetVideoData getVideoData) {
this.getVideoData = getVideoData;
type = CodecUtil.H264_MIME;
TAG = "VideoEncoder";
}
public boolean prepareVideoEncoder(int width, int height, int fps, int bitRate, int rotation,
int iFrameInterval, FormatVideoEncoder formatVideoEncoder) {
return prepareVideoEncoder(width, height, fps, bitRate, rotation, iFrameInterval,
formatVideoEncoder, -1, -1);
}
/**
* Prepare encoder with custom parameters
*/
public boolean prepareVideoEncoder(int width, int height, int fps, int bitRate, int rotation,
int iFrameInterval, FormatVideoEncoder formatVideoEncoder, int profile,
int level) {
if (prepared) stop();
this.width = width;
this.height = height;
this.fps = fps;
this.bitRate = bitRate;
this.rotation = rotation;
this.iFrameInterval = iFrameInterval;
this.formatVideoEncoder = formatVideoEncoder;
this.profile = profile;
this.level = level;
isBufferMode = true;
MediaCodecInfo encoder = chooseEncoder(type);
try {
if (encoder != null) {
Log.i(TAG, "Encoder selected " + encoder.getName());
codec = MediaCodec.createByCodecName(encoder.getName());
if (this.formatVideoEncoder == FormatVideoEncoder.YUV420Dynamical) {
this.formatVideoEncoder = chooseColorDynamically(encoder);
if (this.formatVideoEncoder == null) {
Log.e(TAG, "YUV420 dynamical choose failed");
return false;
}
}
} else {
Log.e(TAG, "Valid encoder not found");
return false;
}
MediaFormat videoFormat;
//if you don't use mediacodec rotation you need swap width and height in rotation 90 or 270
// for correct encoding resolution
String resolution;
if ((rotation == 90 || rotation == 270)) {
resolution = height + "x" + width;
videoFormat = MediaFormat.createVideoFormat(type, height, width);
} else {
resolution = width + "x" + height;
videoFormat = MediaFormat.createVideoFormat(type, width, height);
}
Log.i(TAG, "Prepare video info: " + this.formatVideoEncoder.name() + ", " + resolution);
videoFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,
this.formatVideoEncoder.getFormatCodec());
videoFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 0);
videoFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
videoFormat.setInteger(MediaFormat.KEY_FRAME_RATE, fps);
videoFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, iFrameInterval);
//Set CBR mode if supported by encoder.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && CodecUtil.isCBRModeSupported(encoder, type)) {
Log.i(TAG, "set bitrate mode CBR");
videoFormat.setInteger(MediaFormat.KEY_BITRATE_MODE,
MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR);
} else {
Log.i(TAG, "bitrate mode CBR not supported using default mode");
}
// Rotation by encoder.
// Removed because this is ignored by most encoders, producing different results on different devices
// videoFormat.setInteger(MediaFormat.KEY_ROTATION, rotation);
if (this.profile > 0) {
// MediaFormat.KEY_PROFILE, API > 21
videoFormat.setInteger("profile", this.profile);
}
if (this.level > 0) {
// MediaFormat.KEY_LEVEL, API > 23
videoFormat.setInteger("level", this.level);
}
setCallback();
codec.configure(videoFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
running = false;
if (formatVideoEncoder == FormatVideoEncoder.SURFACE
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
isBufferMode = false;
inputSurface = codec.createInputSurface();
}
Log.i(TAG, "prepared");
prepared = true;
return true;
} catch (Exception e) {
Log.e(TAG, "Create VideoEncoder failed.", e);
this.stop();
return false;
}
}
@Override
public void start(boolean resetTs) {
forceKey = false;
shouldReset = resetTs;
spsPpsSetted = false;
if (formatVideoEncoder != FormatVideoEncoder.SURFACE) {
YUVUtil.preAllocateBuffers(width * height * 3 / 2);
}
Log.i(TAG, "started");
}
@Override
protected void stopImp() {
spsPpsSetted = false;
if (inputSurface != null) inputSurface.release();
inputSurface = null;
oldSps = null;
oldPps = null;
oldVps = null;
Log.i(TAG, "stopped");
}
@Override
public void reset() {
stop(false);
prepareVideoEncoder(width, height, fps, bitRate, rotation, iFrameInterval, formatVideoEncoder,
profile, level);
restart();
}
private FormatVideoEncoder chooseColorDynamically(MediaCodecInfo mediaCodecInfo) {
for (int color : mediaCodecInfo.getCapabilitiesForType(type).colorFormats) {
if (color == FormatVideoEncoder.YUV420PLANAR.getFormatCodec()) {
return FormatVideoEncoder.YUV420PLANAR;
} else if (color == FormatVideoEncoder.YUV420SEMIPLANAR.getFormatCodec()) {
return FormatVideoEncoder.YUV420SEMIPLANAR;
}
}
return null;
}
/**
* Prepare encoder with default parameters
*/
public boolean prepareVideoEncoder() {
return prepareVideoEncoder(width, height, fps, bitRate, rotation, iFrameInterval,
formatVideoEncoder, profile, level);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void setVideoBitrateOnFly(int bitrate) {
if (isRunning()) {
this.bitRate = bitrate;
Bundle bundle = new Bundle();
bundle.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, bitrate);
try {
codec.setParameters(bundle);
} catch (IllegalStateException e) {
Log.e(TAG, "encoder need be running", e);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void requestKeyframe() {
if (isRunning()) {
if (spsPpsSetted) {
Bundle bundle = new Bundle();
bundle.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0);
try {
codec.setParameters(bundle);
getVideoData.onSpsPpsVps(oldSps, oldPps, oldVps);
} catch (IllegalStateException e) {
Log.e(TAG, "encoder need be running", e);
}
} else {
//You need wait until encoder generate first frame.
forceKey = true;
}
}
}
public Surface getInputSurface() {
return inputSurface;
}
public void setInputSurface(Surface inputSurface) {
this.inputSurface = inputSurface;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getRotation() {
return rotation;
}
public void setFps(int fps) {
this.fps = fps;
}
public void setRotation(int rotation) {
this.rotation = rotation;
}
public int getFps() {
return fps;
}
public int getBitRate() {
return bitRate;
}
public void setForceFps(int fps) {
fpsLimiter.setFPS(fps);
}
@Override
public void inputYUVData(Frame frame) {
if (running && !queue.offer(frame)) {
Log.i(TAG, "frame discarded");
}
}
private boolean sendSPSandPPS(MediaFormat mediaFormat) {
//AV1
if (type.equals(CodecUtil.AV1_MIME)) {
ByteBuffer bufferInfo = mediaFormat.getByteBuffer("csd-0");
//we need an av1ConfigurationRecord with sequenceObu to work
if (bufferInfo != null && bufferInfo.remaining() > 4) {
getVideoData.onSpsPpsVps(bufferInfo, null, null);
return true;
}
return false;
//H265
} else if (type.equals(CodecUtil.H265_MIME)) {
List<ByteBuffer> byteBufferList = extractVpsSpsPpsFromH265(mediaFormat.getByteBuffer("csd-0"));
oldSps = byteBufferList.get(1);
oldPps = byteBufferList.get(2);
oldVps = byteBufferList.get(0);
getVideoData.onSpsPpsVps(oldSps, oldPps, oldVps);
return true;
//H264
} else {
oldSps = mediaFormat.getByteBuffer("csd-0");
oldPps = mediaFormat.getByteBuffer("csd-1");
oldVps = null;
getVideoData.onSpsPpsVps(oldSps, oldPps, oldVps);
return true;
}
}
/**
* choose the video encoder by mime.
*/
@Override
protected MediaCodecInfo chooseEncoder(String mime) {
List<MediaCodecInfo> mediaCodecInfoList;
if (codecType == CodecUtil.CodecType.HARDWARE) {
mediaCodecInfoList = CodecUtil.getAllHardwareEncoders(mime, true);
} else if (codecType == CodecUtil.CodecType.SOFTWARE) {
mediaCodecInfoList = CodecUtil.getAllSoftwareEncoders(mime, true);
} else {
//Priority: hardware CBR > hardware > software CBR > software
mediaCodecInfoList = CodecUtil.getAllEncoders(mime, true, true);
}
Log.i(TAG, mediaCodecInfoList.size() + " encoders found");
for (MediaCodecInfo mci : mediaCodecInfoList) {
Log.i(TAG, "Encoder " + mci.getName());
MediaCodecInfo.CodecCapabilities codecCapabilities = mci.getCapabilitiesForType(mime);
for (int color : codecCapabilities.colorFormats) {
Log.i(TAG, "Color supported: " + color);
if (formatVideoEncoder == FormatVideoEncoder.SURFACE) {
if (color == FormatVideoEncoder.SURFACE.getFormatCodec()) return mci;
} else {
//check if encoder support any yuv420 color
if (color == FormatVideoEncoder.YUV420PLANAR.getFormatCodec()
|| color == FormatVideoEncoder.YUV420SEMIPLANAR.getFormatCodec()) {
return mci;
}
}
}
}
return null;
}
/**
* decode sps and pps if the encoder never call to MediaCodec.INFO_OUTPUT_FORMAT_CHANGED
*/
private Pair<ByteBuffer, ByteBuffer> decodeSpsPpsFromBuffer(ByteBuffer outputBuffer, int length) {
byte[] csd = new byte[length];
outputBuffer.get(csd, 0, length);
outputBuffer.rewind();
int i = 0;
int spsIndex = -1;
int ppsIndex = -1;
while (i < length - 4) {
if (csd[i] == 0 && csd[i + 1] == 0 && csd[i + 2] == 0 && csd[i + 3] == 1) {
if (spsIndex == -1) {
spsIndex = i;
} else {
ppsIndex = i;
break;
}
}
i++;
}
if (spsIndex != -1 && ppsIndex != -1) {
byte[] sps = new byte[ppsIndex];
System.arraycopy(csd, spsIndex, sps, 0, ppsIndex);
byte[] pps = new byte[length - ppsIndex];
System.arraycopy(csd, ppsIndex, pps, 0, length - ppsIndex);
return new Pair<>(ByteBuffer.wrap(sps), ByteBuffer.wrap(pps));
}
return null;
}
/**
* You need find 0 0 0 1 byte sequence that is the initiation of vps, sps and pps
* buffers.
*
* @param csd0byteBuffer get in mediacodec case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED
* @return list with vps, sps and pps
*/
private List<ByteBuffer> extractVpsSpsPpsFromH265(ByteBuffer csd0byteBuffer) {
List<ByteBuffer> byteBufferList = new ArrayList<>();
int vpsPosition = -1;
int spsPosition = -1;
int ppsPosition = -1;
int contBufferInitiation = 0;
int length = csd0byteBuffer.remaining();
byte[] csdArray = new byte[length];
csd0byteBuffer.get(csdArray, 0, length);
csd0byteBuffer.rewind();
for (int i = 0; i < csdArray.length; i++) {
if (contBufferInitiation == 3 && csdArray[i] == 1) {
if (vpsPosition == -1) {
vpsPosition = i - 3;
} else if (spsPosition == -1) {
spsPosition = i - 3;
} else {
ppsPosition = i - 3;
}
}
if (csdArray[i] == 0) {
contBufferInitiation++;
} else {
contBufferInitiation = 0;
}
}
byte[] vps = new byte[spsPosition];
byte[] sps = new byte[ppsPosition - spsPosition];
byte[] pps = new byte[csdArray.length - ppsPosition];
for (int i = 0; i < csdArray.length; i++) {
if (i < spsPosition) {
vps[i] = csdArray[i];
} else if (i < ppsPosition) {
sps[i - spsPosition] = csdArray[i];
} else {
pps[i - ppsPosition] = csdArray[i];
}
}
byteBufferList.add(ByteBuffer.wrap(vps));
byteBufferList.add(ByteBuffer.wrap(sps));
byteBufferList.add(ByteBuffer.wrap(pps));
return byteBufferList;
}
/**
*
* @param buffer key frame
* @return av1 ObuSequence
*/
private ByteBuffer extractObuSequence(ByteBuffer buffer, MediaCodec.BufferInfo bufferInfo) {
//we can only extract info from keyframes
if (bufferInfo.flags != MediaCodec.BUFFER_FLAG_KEY_FRAME) return null;
byte[] av1Data = new byte[buffer.remaining()];
buffer.get(av1Data);
Av1Parser av1Parser = new Av1Parser();
List<Obu> obuList = av1Parser.getObus(av1Data);
for (Obu obu: obuList) {
if (av1Parser.getObuType(obu.getHeader()[0]) == ObuType.SEQUENCE_HEADER) {
return ByteBuffer.wrap(obu.getFullData());
}
}
return null;
}
@Override
protected Frame getInputFrame() throws InterruptedException {
Frame frame = queue.take();
if (frame == null) return null;
if (fpsLimiter.limitFPS()) return getInputFrame();
byte[] buffer = frame.getBuffer();
boolean isYV12 = frame.getFormat() == ImageFormat.YV12;
int orientation = frame.isFlip() ? frame.getOrientation() + 180 : frame.getOrientation();
if (orientation >= 360) orientation -= 360;
buffer = isYV12 ? YUVUtil.rotateYV12(buffer, width, height, orientation)
: YUVUtil.rotateNV21(buffer, width, height, orientation);
buffer = isYV12 ? YUVUtil.YV12toYUV420byColor(buffer, width, height, formatVideoEncoder)
: YUVUtil.NV21toYUV420byColor(buffer, width, height, formatVideoEncoder);
frame.setBuffer(buffer);
return frame;
}
@Override
protected long calculatePts(Frame frame, long presentTimeUs) {
return Math.max(0, frame.getTimeStamp() - presentTimeUs);
}
@Override
public void formatChanged(@NonNull MediaCodec mediaCodec, @NonNull MediaFormat mediaFormat) {
getVideoData.onVideoFormat(mediaFormat);
spsPpsSetted = sendSPSandPPS(mediaFormat);
}
@Override
protected void checkBuffer(@NonNull ByteBuffer byteBuffer,
@NonNull MediaCodec.BufferInfo bufferInfo) {
if (forceKey && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
forceKey = false;
requestKeyframe();
}
fixTimeStamp(bufferInfo);
if (!spsPpsSetted && type.equals(CodecUtil.H264_MIME)) {
Log.i(TAG, "formatChanged not called, doing manual sps/pps extraction...");
Pair<ByteBuffer, ByteBuffer> buffers = decodeSpsPpsFromBuffer(byteBuffer.duplicate(), bufferInfo.size);
if (buffers != null) {
Log.i(TAG, "manual sps/pps extraction success");
oldSps = buffers.first;
oldPps = buffers.second;
oldVps = null;
getVideoData.onSpsPpsVps(oldSps, oldPps, oldVps);
spsPpsSetted = true;
} else {
Log.e(TAG, "manual sps/pps extraction failed");
}
} else if (!spsPpsSetted && type.equals(CodecUtil.H265_MIME)) {
Log.i(TAG, "formatChanged not called, doing manual vps/sps/pps extraction...");
List<ByteBuffer> byteBufferList = extractVpsSpsPpsFromH265(byteBuffer.duplicate());
if (byteBufferList.size() == 3) {
Log.i(TAG, "manual vps/sps/pps extraction success");
oldSps = byteBufferList.get(1);
oldPps = byteBufferList.get(2);
oldVps = byteBufferList.get(0);
getVideoData.onSpsPpsVps(oldSps, oldPps, oldVps);
spsPpsSetted = true;
} else {
Log.e(TAG, "manual vps/sps/pps extraction failed");
}
} else if (!spsPpsSetted && type.equals(CodecUtil.AV1_MIME)) {
Log.i(TAG, "formatChanged not called, doing manual av1 extraction...");
ByteBuffer obuSequence = extractObuSequence(byteBuffer.duplicate(), bufferInfo);
if (obuSequence != null) {
getVideoData.onSpsPpsVps(obuSequence, null, null);
spsPpsSetted = true;
} else {
Log.e(TAG, "manual av1 extraction failed");
}
}
if (formatVideoEncoder == FormatVideoEncoder.SURFACE) {
bufferInfo.presentationTimeUs = System.nanoTime() / 1000 - presentTimeUs;
}
}
@Override
protected void sendBuffer(@NonNull ByteBuffer byteBuffer,
@NonNull MediaCodec.BufferInfo bufferInfo) {
getVideoData.getVideoData(byteBuffer, bufferInfo);
}
}