-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencoder.rs
More file actions
271 lines (228 loc) · 7.84 KB
/
encoder.rs
File metadata and controls
271 lines (228 loc) · 7.84 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
use std::ptr;
use std::os::raw::c_int;
use LibAV;
use codec::{
Codec,
MediaType,
};
use ffi::{
self,
AVCodecContext,
AVSampleFormat,
AVRational,
avcodec_alloc_context3,
avcodec_free_context,
av_get_channel_layout_nb_channels,
};
use ffi::AVSampleFormat::AV_SAMPLE_FMT_S16;
use format::OutputFormat;
use audio::ChannelLayout;
use audio::constants::CHANNEL_LAYOUT_STEREO;
use generic::RefMutFrame;
use common::{self, Packet, Timebase};
use errors::*;
use util::OwnedOrRefMut;
/// Audio encoder.
///
/// Encoding is done by repeatedly calling `encode` with
/// the `Frame` that should be encoded and by consuming
/// the returned `Packet` iterator.
///
/// When no more frames need to be encoded,
/// the encoder should be `flush`ed to obtain
/// the remaining buffered packets.
pub struct Encoder {
ptr: *mut AVCodecContext,
}
impl Encoder {
/// Create a new encoder builder with the passed `codec`.
pub fn from_codec(codec: Codec) -> Result<EncoderBuilder> {
EncoderBuilder::from_codec(codec)
}
/// Returns the sample format of the encoder.
pub fn sample_format(&self) -> AVSampleFormat {
self.as_ref().sample_fmt
}
// TODO: Check for underflow
/// Returns the sample rate of the encoder.
pub fn sample_rate(&self) -> u32 {
self.as_ref().sample_rate as u32
}
/// Returns the time base of the encoder.
pub fn time_base(&self) -> Timebase {
self.as_ref().time_base.into()
}
/// Returns the frame size required by the encoder.
/// If the result is `None`, any frame size may be used.
pub fn frame_size(&self) -> Option<usize> {
match self.as_ref().frame_size as usize {
0 => None,
size => Some(size),
}
}
/// Returns the codec of the encoder.
pub fn codec(&self) -> Codec {
unsafe {
Codec::from_ptr(self.as_ref().codec)
}
}
/// Encode a Frame and return the encoded packets as iterator.
pub fn encode<'a, F>(&mut self, frame: F) -> Result<Packets> where
F: Into<RefMutFrame<'a>>,
{
unsafe {
let mut frame = frame.into().into_audio_frame()
.ok_or("Cannot encode non-audio frame as audio")?;
// Do scaling if needed
// if !frame.is_compatible_with_encoder(self) {
// self.update_scaler(frame)?;
// self.init_tmp_frame()?;
// let tmp_frame = self.tmp_frame.as_mut().unwrap();
// let scaler = self.scaler.as_mut().unwrap();
// scaler.scale_frame(&mut frame, tmp_frame);
// // Copy frame data
// tmp_frame.set_pts(frame.pts());
// frame = tmp_frame;
// }
// Encode the frame
{
let mut packet = ::std::mem::zeroed();
ffi::av_init_packet(&mut packet);
let res = ffi::avcodec_send_frame(self.ptr, frame.as_mut_ptr());
if res < 0 {
bail!("Could not encode frame: 0x{:X}", res)
}
}
Ok(Packets::from_mut_encoder(self))
}
}
/// Flush the encoder.
/// The encoder may buffer data and needs to be flushed
/// to obtain the remaining packets as iterator.
pub fn flush(self) -> Result<Packets<'static>> {
unsafe {
// Flush encoder
let res = ffi::avcodec_send_frame(self.ptr, ptr::null_mut());
if res < 0 {
bail!("Could not flush encoder: 0x{:X}", res)
}
Ok(Packets::from_encoder(self))
}
}
}
impl Encoder {
pub fn as_mut(&mut self) -> &mut AVCodecContext { unsafe { &mut *self.ptr } }
pub fn as_ptr(&self) -> *const AVCodecContext { self.ptr }
pub fn as_mut_ptr(&mut self) -> *mut AVCodecContext { self.ptr }
}
impl AsRef<AVCodecContext> for Encoder {
fn as_ref(&self) -> &AVCodecContext {
unsafe { &*self.ptr }
}
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe {
if !self.ptr.is_null() {
avcodec_free_context(&mut self.ptr);
}
}
}
}
/// Builder for creating encoders.
pub struct EncoderBuilder {
codec: Codec,
sample_format: Option<AVSampleFormat>,
sample_rate: Option<u32>,
channel_layout: Option<ChannelLayout>,
}
impl EncoderBuilder {
/// Create a new encoder builder with the passed `codec`.
pub fn from_codec(codec: Codec) -> Result<Self> {
common::encoder::require_is_encoder(codec)?;
common::encoder::require_codec_type(MediaType::Audio, codec)?;
Ok(EncoderBuilder {
codec: codec,
sample_format: None,
sample_rate: None,
channel_layout: None,
})
}
/// Set the sample format. Default: `AV_SAMPLE_FMT_S16`.
pub fn sample_format(&mut self, sample_format: AVSampleFormat) -> &mut Self {
self.sample_format = Some(sample_format); self
}
// TODO: Check for overflow
/// Set the sample rate. Default: `44100`.
pub fn sample_rate(&mut self, sample_rate: u32) -> &mut Self {
self.sample_rate = Some(sample_rate); self
}
/// Set the channel layout. Default: `CHANNEL_LAYOUT_STEREO`.
pub fn channel_layout(&mut self, channel_layout: ChannelLayout) -> &mut Self {
self.channel_layout = Some(channel_layout); self
}
/// Open the encoder.
pub fn open(&self, format: OutputFormat) -> Result<Encoder> {
unsafe {
let sample_rate = self.sample_rate.unwrap_or(44100) as c_int;
let sample_format = self.sample_format.unwrap_or(AV_SAMPLE_FMT_S16);
let channel_layout = self.channel_layout.unwrap_or(CHANNEL_LAYOUT_STEREO);
LibAV::init();
let mut codec_context = avcodec_alloc_context3(self.codec.as_ptr());
if codec_context.is_null() {
bail!("Could not allocate an encoding context");
}
// Initialize encoder fields
common::encoder::init(codec_context, format);
(*codec_context).sample_rate = sample_rate;
(*codec_context).sample_fmt = sample_format;
(*codec_context).time_base = AVRational { num: 1, den: sample_rate };
(*codec_context).channel_layout = channel_layout.bits();
(*codec_context).channels = av_get_channel_layout_nb_channels(channel_layout.bits());
common::encoder::open(codec_context, "audio")?;
Ok(Encoder {
ptr: codec_context,
})
}
}
}
/// Iterator over encoded packets.
pub struct Packets<'encoder> {
encoder: OwnedOrRefMut<'encoder, Encoder>,
}
impl<'encoder> Packets<'encoder> {
fn from_encoder(encoder: Encoder) -> Self {
Packets {
encoder: OwnedOrRefMut::Owned(encoder)
}
}
fn from_mut_encoder(encoder: &'encoder mut Encoder) -> Self {
Packets {
encoder: OwnedOrRefMut::Borrowed(encoder)
}
}
}
impl<'encoder> Iterator for Packets<'encoder> {
type Item = Result<Packet<'static>>;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let mut packet = ffi::av_packet_alloc();
let res = ffi::avcodec_receive_packet(self.encoder.as_mut_ptr(), packet);
if res < 0 {
ffi::av_packet_free(&mut packet);
match res {
ffi::AVERROR_EAGAIN | ffi::AVERROR_EOF => return None,
_ => return Some(Err(format!("Failed to receive packet: 0x{:X}", res).into())),
}
}
let packet = Packet::from_ptr(packet, self.encoder.time_base());
Some(Ok(packet))
}
}
}
impl<'encoder> Drop for Packets<'encoder> {
fn drop(&mut self) {
// Receive every packet possible
for _ in self {}
}
}