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
use crate::error::NativeErrorExt;
use crate::formats::YUVSource;
use crate::Error;
use openh264_sys2::{
videoFormatI420, EVideoFormatType, ISVCEncoder, ISVCEncoderVtbl, SEncParamBase, SEncParamExt, SFrameBSInfo, SLayerBSInfo, SSourcePicture, WelsCreateSVCEncoder, WelsDestroySVCEncoder, ENCODER_OPTION, ENCODER_OPTION_DATAFORMAT, ENCODER_OPTION_TRACE_LEVEL, VIDEO_CODING_LAYER, WELS_LOG_DETAIL, WELS_LOG_QUIET
};
use std::os::raw::{c_int, c_uchar, c_void};
use std::ptr::{addr_of_mut, null, null_mut};
#[rustfmt::skip]
#[allow(non_snake_case)]
#[derive(Debug)]
pub struct EncoderRawAPI {
encoder_ptr: *mut *const ISVCEncoderVtbl,
initialize: unsafe extern "C" fn(arg1: *mut ISVCEncoder, pParam: *const SEncParamBase) -> c_int,
initialize_ext: unsafe extern "C" fn(arg1: *mut ISVCEncoder, pParam: *const SEncParamExt) -> c_int,
get_default_params: unsafe extern "C" fn(arg1: *mut ISVCEncoder, pParam: *mut SEncParamExt) -> c_int,
uninitialize: unsafe extern "C" fn(arg1: *mut ISVCEncoder) -> c_int,
encode_frame: unsafe extern "C" fn(arg1: *mut ISVCEncoder, kpSrcPic: *const SSourcePicture, pBsInfo: *mut SFrameBSInfo) -> c_int,
encode_parameter_sets: unsafe extern "C" fn(arg1: *mut ISVCEncoder, pBsInfo: *mut SFrameBSInfo) -> c_int,
force_intra_frame: unsafe extern "C" fn(arg1: *mut ISVCEncoder, bIDR: bool) -> c_int,
set_option: unsafe extern "C" fn(arg1: *mut ISVCEncoder, eOptionId: ENCODER_OPTION, pOption: *mut c_void) -> c_int,
get_option: unsafe extern "C" fn(arg1: *mut ISVCEncoder, eOptionId: ENCODER_OPTION, pOption: *mut c_void) -> c_int,
}
#[rustfmt::skip]
#[allow(clippy::too_many_arguments)]
#[allow(clippy::missing_safety_doc)]
#[allow(non_snake_case)]
#[allow(unused)]
impl EncoderRawAPI {
fn new() -> Result<Self, Error> {
unsafe {
let mut encoder_ptr = null::<ISVCEncoderVtbl>() as *mut *const ISVCEncoderVtbl;
WelsCreateSVCEncoder(&mut encoder_ptr as *mut *mut *const ISVCEncoderVtbl).ok()?;
let e = || {
Error::msg("VTable missing function.")
};
Ok(Self {
encoder_ptr,
initialize: (*(*encoder_ptr)).Initialize.ok_or_else(e)?,
initialize_ext: (*(*encoder_ptr)).InitializeExt.ok_or_else(e)?,
get_default_params: (*(*encoder_ptr)).GetDefaultParams.ok_or_else(e)?,
uninitialize: (*(*encoder_ptr)).Uninitialize.ok_or_else(e)?,
encode_frame: (*(*encoder_ptr)).EncodeFrame.ok_or_else(e)?,
encode_parameter_sets: (*(*encoder_ptr)).EncodeParameterSets.ok_or_else(e)?,
force_intra_frame: (*(*encoder_ptr)).ForceIntraFrame.ok_or_else(e)?,
set_option: (*(*encoder_ptr)).SetOption.ok_or_else(e)?,
get_option: (*(*encoder_ptr)).GetOption.ok_or_else(e)?,
})
}
}
unsafe fn uninitialize(&self) -> c_int { (self.uninitialize)(self.encoder_ptr) }
unsafe fn initialize(&self, pParam: *const SEncParamBase) -> c_int { (self.initialize)(self.encoder_ptr, pParam) }
unsafe fn initialize_ext(&self, pParam: *const SEncParamExt) -> c_int { (self.initialize_ext)(self.encoder_ptr, pParam) }
pub unsafe fn get_default_params(&self, pParam: *mut SEncParamExt) -> c_int { (self.get_default_params)(self.encoder_ptr, pParam) }
pub unsafe fn encode_frame(&self, kpSrcPic: *const SSourcePicture, pBsInfo: *mut SFrameBSInfo) -> c_int { (self.encode_frame)(self.encoder_ptr, kpSrcPic, pBsInfo) }
pub unsafe fn encode_parameter_sets(&self, pBsInfo: *mut SFrameBSInfo) -> c_int { (self.encode_parameter_sets)(self.encoder_ptr, pBsInfo) }
pub unsafe fn force_intra_frame(&self, bIDR: bool) -> c_int { (self.force_intra_frame)(self.encoder_ptr, bIDR) }
pub unsafe fn set_option(&self, eOptionId: ENCODER_OPTION, pOption: *mut c_void) -> c_int { (self.set_option)(self.encoder_ptr, eOptionId, pOption) }
pub unsafe fn get_option(&self, eOptionId: ENCODER_OPTION, pOption: *mut c_void) -> c_int { (self.get_option)(self.encoder_ptr, eOptionId, pOption) }
}
impl Drop for EncoderRawAPI {
fn drop(&mut self) {
unsafe {
WelsDestroySVCEncoder(self.encoder_ptr);
}
}
}
#[derive(Default, Copy, Clone, Debug)]
pub struct EncoderConfig {
width: u32,
height: u32,
enable_skip_frame: bool,
target_bitrate: u32,
enable_denoise: bool,
debug: i32,
data_format: EVideoFormatType,
}
impl EncoderConfig {
pub fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
enable_skip_frame: true,
target_bitrate: 120_000,
enable_denoise: false,
debug: 0,
data_format: videoFormatI420,
}
}
pub fn set_bitrate_bps(mut self, bps: u32) -> Self {
self.target_bitrate = bps;
self
}
pub fn debug(mut self, value: bool) -> Self {
self.debug = if value { WELS_LOG_DETAIL } else { WELS_LOG_QUIET };
self
}
}
pub struct Encoder {
params: SEncParamExt,
raw_api: EncoderRawAPI,
bit_stream_info: SFrameBSInfo,
}
impl Encoder {
pub fn with_config(mut config: EncoderConfig) -> Result<Self, Error> {
let raw_api = EncoderRawAPI::new()?;
let mut params = SEncParamExt::default();
#[rustfmt::skip]
unsafe {
raw_api.get_default_params(&mut params).ok()?;
params.iPicWidth = config.width as c_int;
params.iPicHeight = config.height as c_int;
params.bEnableFrameSkip = config.enable_skip_frame;
params.iTargetBitrate = config.target_bitrate as c_int;
params.bEnableDenoise = config.enable_denoise;
raw_api.initialize_ext(¶ms).ok()?;
raw_api.set_option(ENCODER_OPTION_TRACE_LEVEL, addr_of_mut!(config.debug).cast()).ok()?;
raw_api.set_option(ENCODER_OPTION_DATAFORMAT, addr_of_mut!(config.data_format).cast()).ok()?;
};
Ok(Self {
params,
raw_api,
bit_stream_info: Default::default(),
})
}
pub fn encode<T: YUVSource>(&mut self, yuv_source: &T) -> Result<EncodedBitStream<'_>, Error> {
assert_eq!(yuv_source.width(), self.params.iPicWidth);
assert_eq!(yuv_source.height(), self.params.iPicHeight);
let source = SSourcePicture {
iColorFormat: videoFormatI420,
iStride: [yuv_source.y_stride(), yuv_source.u_stride(), yuv_source.v_stride(), 0],
pData: [
yuv_source.y().as_ptr() as *mut c_uchar,
yuv_source.u().as_ptr() as *mut c_uchar,
yuv_source.v().as_ptr() as *mut c_uchar,
null_mut(),
],
iPicWidth: self.params.iPicWidth,
iPicHeight: self.params.iPicHeight,
..Default::default()
};
unsafe {
self.raw_api.encode_frame(&source, &mut self.bit_stream_info).ok()?;
Ok(EncodedBitStream {
bit_stream_info: &self.bit_stream_info,
})
}
}
pub unsafe fn raw_api(&mut self) -> &mut EncoderRawAPI {
&mut self.raw_api
}
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe {
self.raw_api.uninitialize();
}
}
}
pub struct EncodedBitStream<'a> {
bit_stream_info: &'a SFrameBSInfo,
}
impl<'a> EncodedBitStream<'a> {
pub fn raw_info(&self) -> &'a SFrameBSInfo {
self.bit_stream_info
}
pub fn frame_type(&self) -> FrameType {
FrameType::from_c_int(self.bit_stream_info.eFrameType)
}
pub fn num_layers(&self) -> usize {
self.bit_stream_info.iLayerNum as usize
}
pub fn layer(&self, i: usize) -> Option<Layer<'a>> {
if i < self.num_layers() {
Some(Layer {
layer_info: &self.bit_stream_info.sLayerInfo[i],
})
} else {
None
}
}
pub fn write_vec(&self, dst: &mut Vec<u8>) {
for l in 0..self.num_layers() {
let layer = self.layer(l).unwrap();
for n in 0..layer.nal_count() {
let nal = layer.nal_unit(n).unwrap();
dst.extend_from_slice(nal)
}
}
}
pub fn to_vec(&self) -> Vec<u8> {
let mut rval = Vec::new();
self.write_vec(&mut rval);
rval
}
}
#[derive(Debug)]
pub struct Layer<'a> {
layer_info: &'a SLayerBSInfo,
}
impl<'a> Layer<'a> {
pub fn raw_info(&self) -> &'a SLayerBSInfo {
self.layer_info
}
pub fn nal_count(&self) -> usize {
self.layer_info.iNalCount as usize
}
pub fn nal_unit(&self, i: usize) -> Option<&[u8]> {
if i < self.nal_count() {
let mut offset = 0;
let slice = unsafe {
for nal_idx in 0..i {
let size = *self.layer_info.pNalLengthInByte.add(nal_idx) as usize;
offset += size;
}
let size = *self.layer_info.pNalLengthInByte.add(i) as usize;
std::slice::from_raw_parts(self.layer_info.pBsBuf.add(offset), size)
};
Some(slice)
} else {
None
}
}
pub fn is_video(&self) -> bool {
self.layer_info.uiLayerType == VIDEO_CODING_LAYER as c_uchar
}
}
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Clone)]
pub enum FrameType {
Invalid,
IDR,
I,
P,
Skip,
IPMixed,
}
impl FrameType {
fn from_c_int(native: std::os::raw::c_int) -> Self {
use openh264_sys2::{videoFrameTypeI, videoFrameTypeIDR, videoFrameTypeIPMixed, videoFrameTypeP, videoFrameTypeSkip};
#[allow(non_upper_case_globals)]
match native {
videoFrameTypeIDR => Self::IDR,
videoFrameTypeI => Self::I,
videoFrameTypeP => Self::P,
videoFrameTypeSkip => Self::Skip,
videoFrameTypeIPMixed => Self::IPMixed,
_ => Self::Invalid,
}
}
}