-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathH264Encoder.java
More file actions
349 lines (288 loc) · 10.8 KB
/
H264Encoder.java
File metadata and controls
349 lines (288 loc) · 10.8 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
package main;
import static java.lang.System.arraycopy;
import static org.jcodec.codecs.h264.H264Utils.escapeNAL;
import java.nio.ByteBuffer;
import org.jcodec.codecs.h264.encode.EncodedMB;
import org.jcodec.codecs.h264.encode.MBEncoderHelper;
import org.jcodec.codecs.h264.encode.MBEncoderI16x16;
import org.jcodec.codecs.h264.encode.MBEncoderP16x16;
import org.jcodec.codecs.h264.encode.MotionEstimator;
import org.jcodec.codecs.h264.encode.RateControl;
import org.jcodec.codecs.h264.io.CAVLC;
import org.jcodec.codecs.h264.io.model.MBType;
import org.jcodec.codecs.h264.io.model.NALUnit;
import org.jcodec.codecs.h264.io.model.NALUnitType;
import org.jcodec.codecs.h264.io.model.PictureParameterSet;
import org.jcodec.codecs.h264.io.model.RefPicMarkingIDR;
import org.jcodec.codecs.h264.io.model.SeqParameterSet;
import org.jcodec.codecs.h264.io.model.SliceHeader;
import org.jcodec.codecs.h264.io.model.SliceType;
import org.jcodec.codecs.h264.io.write.CAVLCWriter;
import org.jcodec.codecs.h264.io.write.SliceHeaderWriter;
import org.jcodec.common.VideoEncoder;
import org.jcodec.common.io.BitWriter;
import org.jcodec.common.logging.Logger;
import org.jcodec.common.model.ColorSpace;
import org.jcodec.common.model.Picture8Bit;
import org.jcodec.common.model.Size;
import org.jcodec.common.tools.MathUtil;
/**
* This class is part of JCodec ( www.jcodec.org ) This software is distributed
* under FreeBSD License
*
* MPEG 4 AVC ( H.264 ) Encoder
*
* Conforms to H.264 ( ISO/IEC 14496-10 ) specifications
*
* @author The JCodec project
*
*/
public class H264Encoder extends VideoEncoder {
// private static final int QP = 20;
private static final int KEY_INTERVAL_DEFAULT = 25;
public static H264Encoder createH264Encoder() {
return new H264Encoder(new DumbRateControl());
}
private CAVLC[] cavlc;
private byte[][] leftRow;
private byte[][] topLine;
private RateControl rc;
private int frameNumber;
private int keyInterval;
private int maxPOC;
private int maxFrameNumber;
private SeqParameterSet sps;
private PictureParameterSet pps;
private MBEncoderI16x16 mbEncoderI16x16;
private MBEncoderP16x16 mbEncoderP16x16;
private Picture8Bit ref;
private Picture8Bit picOut;
private EncodedMB[] topEncoded;
private EncodedMB outMB;
public H264Encoder(RateControl rc) {
this.rc = rc;
this.keyInterval = KEY_INTERVAL_DEFAULT;
}
public int getKeyInterval() {
return keyInterval;
}
public void setKeyInterval(int keyInterval) {
this.keyInterval = keyInterval;
}
/**
* Encode this picture into h.264 frame. Frame type will be selected by encoder.
*/
public ByteBuffer encodeFrame8Bit(Picture8Bit pic, ByteBuffer _out) {
if (frameNumber >= keyInterval) {
frameNumber = 0;
}
SliceType sliceType = frameNumber == 0 ? SliceType.I : SliceType.P;
boolean idr = frameNumber == 0;
return doEncodeFrame8Bit(pic, _out, idr, frameNumber++, sliceType);
}
/**
* Encode this picture as an IDR frame. IDR frame starts a new independently
* decodeable video sequence
*
* @param pic
* @param _out
* @return
*/
public ByteBuffer encodeIDRFrame(Picture8Bit pic, ByteBuffer _out) {
frameNumber = 0;
return doEncodeFrame8Bit(pic, _out, true, frameNumber, SliceType.I);
}
/**
* Encode this picture as a P-frame. P-frame is an frame predicted from one or
* more of the previosly decoded frame and is usually 10x less in size then the
* IDR frame.
*
* @param pic
* @param _out
* @return
*/
public ByteBuffer encodePFrame(Picture8Bit pic, ByteBuffer _out) {
frameNumber++;
return doEncodeFrame8Bit(pic, _out, true, frameNumber, SliceType.P);
}
public ByteBuffer doEncodeFrame8Bit(Picture8Bit pic, ByteBuffer _out, boolean idr, int frameNumber,
SliceType frameType) {
ByteBuffer dup = _out.duplicate();
if (idr) {
sps = initSPS(new Size(pic.getCroppedWidth(), pic.getCroppedHeight()));
pps = initPPS();
maxPOC = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
maxFrameNumber = 1 << (sps.log2_max_frame_num_minus4 + 4);
}
if (idr) {
dup.putInt(0x1);
new NALUnit(NALUnitType.SPS, 3).write(dup);
writeSPS(dup, sps);
dup.putInt(0x1);
new NALUnit(NALUnitType.PPS, 3).write(dup);
writePPS(dup, pps);
}
int mbWidth = sps.pic_width_in_mbs_minus1 + 1;
int mbHeight = sps.pic_height_in_map_units_minus1 + 1;
leftRow = new byte[][] { new byte[16], new byte[8], new byte[8] };
topLine = new byte[][] { new byte[mbWidth << 4], new byte[mbWidth << 3], new byte[mbWidth << 3] };
picOut = Picture8Bit.create(mbWidth << 4, mbHeight << 4, pic.getColor());
outMB = new EncodedMB();
topEncoded = new EncodedMB[mbWidth];
for (int i = 0; i < mbWidth; i++)
topEncoded[i] = new EncodedMB();
encodeSlice(sps, pps, pic, dup, idr, frameNumber, frameType);
putLastMBLine();
ref = picOut;
dup.flip();
return dup;
}
private void writePPS(ByteBuffer dup, PictureParameterSet pps) {
ByteBuffer tmp = ByteBuffer.allocate(1024);
pps.write(tmp);
tmp.flip();
escapeNAL(tmp, dup);
}
private void writeSPS(ByteBuffer dup, SeqParameterSet sps) {
ByteBuffer tmp = ByteBuffer.allocate(1024);
sps.write(tmp);
tmp.flip();
escapeNAL(tmp, dup);
}
public PictureParameterSet initPPS() {
PictureParameterSet pps = new PictureParameterSet();
pps.pic_init_qp_minus26 = rc.getInitQp(SliceType.I) - 26;
return pps;
}
public SeqParameterSet initSPS(Size sz) {
SeqParameterSet sps = new SeqParameterSet();
sps.pic_width_in_mbs_minus1 = ((sz.getWidth() + 15) >> 4) - 1;
sps.pic_height_in_map_units_minus1 = ((sz.getHeight() + 15) >> 4) - 1;
sps.chroma_format_idc = ColorSpace.YUV420J;
sps.profile_idc = 66;
sps.level_idc = 40;
sps.frame_mbs_only_flag = true;
sps.log2_max_frame_num_minus4 = Math.max(0, MathUtil.log2(keyInterval) - 3);
int codedWidth = (sps.pic_width_in_mbs_minus1 + 1) << 4;
int codedHeight = (sps.pic_height_in_map_units_minus1 + 1) << 4;
sps.frame_cropping_flag = codedWidth != sz.getWidth() || codedHeight != sz.getHeight();
sps.frame_crop_right_offset = (codedWidth - sz.getWidth() + 1) >> 1;
sps.frame_crop_bottom_offset = (codedHeight - sz.getHeight() + 1) >> 1;
return sps;
}
private void encodeSlice(SeqParameterSet sps, PictureParameterSet pps, Picture8Bit pic, ByteBuffer dup, boolean idr,
int frameNum, SliceType sliceType) {
if (idr && sliceType != SliceType.I) {
idr = false;
Logger.warn("Illegal value of idr = true when sliceType != I");
}
cavlc = new CAVLC[] { new CAVLC(sps, pps, 2, 2), new CAVLC(sps, pps, 1, 1), new CAVLC(sps, pps, 1, 1) };
mbEncoderI16x16 = new MBEncoderI16x16(cavlc, leftRow, topLine);
mbEncoderP16x16 = new MBEncoderP16x16(sps, ref, cavlc, new MotionEstimator(16));
rc.reset();
int qp = rc.getInitQp(sliceType);
dup.putInt(0x1);
new NALUnit(idr ? NALUnitType.IDR_SLICE : NALUnitType.NON_IDR_SLICE, 3).write(dup);
SliceHeader sh = new SliceHeader();
sh.slice_type = sliceType;
if (idr)
sh.refPicMarkingIDR = new RefPicMarkingIDR(false, false);
sh.pps = pps;
sh.sps = sps;
sh.pic_order_cnt_lsb = (frameNum << 1) % maxPOC;
sh.frame_num = frameNum % maxFrameNumber;
sh.slice_qp_delta = qp - (pps.pic_init_qp_minus26 + 26);
ByteBuffer buf = ByteBuffer.allocate(pic.getWidth() * pic.getHeight() * 4);
BitWriter sliceData = new BitWriter(buf);
new SliceHeaderWriter().write(sh, idr, 2, sliceData);
for (int mbY = 0; mbY < sps.pic_height_in_map_units_minus1 + 1; mbY++) {
for (int mbX = 0; mbX < sps.pic_width_in_mbs_minus1 + 1; mbX++) {
if (sliceType == SliceType.P) {
CAVLCWriter.writeUE(sliceData, 0); // number of skipped mbs
}
MBType mbType = selectMBType(sliceType);
if (mbType == MBType.I_16x16) {
// I16x16 carries part of layout information in the
// macroblock type
// itself for this reason we'll have to decide it now to
// embed into
// macroblock type
int predMode = mbEncoderI16x16.getPredMode(pic, mbX, mbY);
int cbpChroma = mbEncoderI16x16.getCbpChroma(pic, mbX, mbY);
int cbpLuma = mbEncoderI16x16.getCbpLuma(pic, mbX, mbY);
int i16x16TypeOffset = (cbpLuma / 15) * 12 + cbpChroma * 4 + predMode;
int mbTypeOffset = sliceType == SliceType.P ? 5 : 0;
CAVLCWriter.writeUE(sliceData, mbTypeOffset + mbType.code() + i16x16TypeOffset);
} else {
CAVLCWriter.writeUE(sliceData, mbType.code());
}
BitWriter candidate;
int qpDelta;
do {
candidate = sliceData.fork();
qpDelta = rc.getQpDelta();
encodeMacroblock(mbType, pic, mbX, mbY, candidate, qp, qpDelta);
} while (!rc.accept(candidate.position() - sliceData.position()));
sliceData = candidate;
qp += qpDelta;
collectPredictors(outMB.getPixels(), mbX);
addToReference(mbX, mbY);
}
}
sliceData.write1Bit(1);
sliceData.flush();
buf = sliceData.getBuffer();
buf.flip();
escapeNAL(buf, dup);
}
private void encodeMacroblock(MBType mbType, Picture8Bit pic, int mbX, int mbY, BitWriter candidate, int qp,
int qpDelta) {
if (mbType == MBType.I_16x16)
mbEncoderI16x16.encodeMacroblock(pic, mbX, mbY, candidate, outMB, mbX > 0 ? topEncoded[mbX - 1] : null,
mbY > 0 ? topEncoded[mbX] : null, qp + qpDelta, qpDelta);
else if (mbType == MBType.P_16x16)
mbEncoderP16x16.encodeMacroblock(pic, mbX, mbY, candidate, outMB, mbX > 0 ? topEncoded[mbX - 1] : null,
mbY > 0 ? topEncoded[mbX] : null, qp + qpDelta, qpDelta);
else
throw new RuntimeException("Macroblock of type " + mbType + " is not supported.");
}
private MBType selectMBType(SliceType sliceType) {
if (sliceType == SliceType.I)
return MBType.I_16x16;
else if (sliceType == SliceType.P)
return MBType.P_16x16;
else
throw new RuntimeException("Unsupported slice type");
}
private void addToReference(int mbX, int mbY) {
if (mbY > 0)
MBEncoderHelper.putBlkPic(picOut, topEncoded[mbX].getPixels(), mbX << 4, (mbY - 1) << 4);
EncodedMB tmp = topEncoded[mbX];
topEncoded[mbX] = outMB;
outMB = tmp;
}
private void putLastMBLine() {
int mbWidth = sps.pic_width_in_mbs_minus1 + 1;
int mbHeight = sps.pic_height_in_map_units_minus1 + 1;
for (int mbX = 0; mbX < mbWidth; mbX++)
MBEncoderHelper.putBlkPic(picOut, topEncoded[mbX].getPixels(), mbX << 4, (mbHeight - 1) << 4);
}
private void collectPredictors(Picture8Bit outMB, int mbX) {
arraycopy(outMB.getPlaneData(0), 240, topLine[0], mbX << 4, 16);
arraycopy(outMB.getPlaneData(1), 56, topLine[1], mbX << 3, 8);
arraycopy(outMB.getPlaneData(2), 56, topLine[2], mbX << 3, 8);
copyCol(outMB.getPlaneData(0), 15, 16, leftRow[0]);
copyCol(outMB.getPlaneData(1), 7, 8, leftRow[1]);
copyCol(outMB.getPlaneData(2), 7, 8, leftRow[2]);
}
private void copyCol(byte[] planeData, int off, int stride, byte[] out) {
for (int i = 0; i < out.length; i++) {
out[i] = planeData[off];
off += stride;
}
}
@Override
public ColorSpace[] getSupportedColorSpaces() {
return new ColorSpace[] { ColorSpace.YUV420J };
}
}