alpha2-native 0.10.0

Native headless and real-time host boundary for alpha2.
Documentation
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
//! VP9 alpha: the alpha stream in each block's addition decoded beside the colour stream.

use std::collections::{BTreeSet, VecDeque};

use alpha2_ffmpeg_bridge::DecodedFrame;
use alpha2_media::DecodeError;
use rsmpeg::avcodec::{AVCodec, AVCodecContext, AVPacket};
use rsmpeg::avutil::{AVFrame, AVRational};
use rsmpeg::error::RsmpegError;
use rsmpeg::ffi;

use crate::convert::{adapter_error, reject_unused_decode_options, video_decoder_options};
use crate::recovery::{FfmpegRecovery, Recovery};

/// The Matroska `BlockAddID` of VP9's alpha stream (`WebM`'s `alpha_mode` 1).
const ALPHA_BLOCK_ADDITION: u64 = 1;

#[derive(Debug)]
pub(crate) struct RawFrame {
    picture: DecodedFrame,
    alpha: Option<DecodedFrame>,
}

impl RawFrame {
    pub(crate) const fn opaque(picture: DecodedFrame) -> Self {
        Self {
            picture,
            alpha: None,
        }
    }

    pub(crate) const fn alpha(&self) -> Option<&DecodedFrame> {
        self.alpha.as_ref()
    }

    #[cfg(all(
        any(target_os = "linux", target_os = "macos", target_os = "windows"),
        feature = "hwdecode"
    ))]
    pub(crate) fn into_parts(self) -> (DecodedFrame, Option<DecodedFrame>) {
        (self.picture, self.alpha)
    }
}

impl std::ops::Deref for RawFrame {
    type Target = DecodedFrame;

    fn deref(&self) -> &DecodedFrame {
        &self.picture
    }
}

#[derive(Clone, Copy)]
pub(crate) enum FrameAlpha<'a> {
    Decoded(&'a DecodedFrame),
    AtLumaLayout(&'a alpha2_media::Plane),
}

impl FrameAlpha<'_> {
    pub(crate) fn plane(
        self,
        (width, height): (u32, u32),
        depth: u8,
        msb_aligned: bool,
    ) -> Result<alpha2_media::Plane, DecodeError> {
        let plane = match self {
            Self::Decoded(frame) => alpha_plane(frame, depth, msb_aligned)?,
            Self::AtLumaLayout(plane) => plane.clone(),
        };
        if (plane.width, plane.height) == (width, height) {
            Ok(plane)
        } else {
            Err(DecodeError::Adapter(format!(
                "a {}x{} alpha plane does not fit a {width}x{height} picture",
                plane.width, plane.height
            )))
        }
    }
}

pub(crate) fn carries_alpha_stream(packet: &AVPacket) -> bool {
    alpha2_ffmpeg_bridge::packet_block_addition(packet, ALPHA_BLOCK_ADDITION).is_some()
}

fn pairing_pts(frame: &AVFrame) -> i64 {
    if frame.pts == ffi::AV_NOPTS_VALUE {
        frame.best_effort_timestamp
    } else {
        frame.pts
    }
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum StreamEnd {
    Open,
    Signalled,
    Drained,
}

pub(crate) struct AlphaCompanion {
    decoder: AVCodecContext,
    pictures: VecDeque<DecodedFrame>,
    alphas: VecDeque<DecodedFrame>,
    pictures_dropped_unreported: BTreeSet<i64>,
    awaiting_keyframe: bool,
    from_stream_start: bool,
    end: StreamEnd,
    pictures_taken: u64,
    alphas_received: u64,
}

impl AlphaCompanion {
    pub(crate) fn open(threads: i64, time_base: AVRational) -> Result<Self, DecodeError> {
        let codec = AVCodec::find_decoder_by_name(c"vp9").ok_or_else(|| {
            DecodeError::Unsupported("this FFmpeg runtime has no vp9 decoder".into())
        })?;
        crate::decode::allowed_decoder(&codec)?;
        let mut decoder = AVCodecContext::new(&codec);
        decoder.set_pkt_timebase(time_base);
        let unused =
            alpha2_ffmpeg_bridge::open_codec_context(&mut decoder, video_decoder_options(threads))
                .map_err(adapter_error)?;
        reject_unused_decode_options(unused)?;
        Ok(Self {
            decoder,
            pictures: VecDeque::new(),
            alphas: VecDeque::new(),
            pictures_dropped_unreported: BTreeSet::new(),
            awaiting_keyframe: true,
            from_stream_start: true,
            end: StreamEnd::Open,
            pictures_taken: 0,
            alphas_received: 0,
        })
    }

    pub(crate) fn flush(&mut self) {
        self.decoder.flush_buffers();
        self.pictures.clear();
        self.alphas.clear();
        self.pictures_dropped_unreported.clear();
        self.awaiting_keyframe = true;
        self.from_stream_start = false;
        self.end = StreamEnd::Open;
    }

    pub(crate) const fn restarted_from_stream_start(&mut self, from_start: bool) {
        self.from_stream_start = from_start;
    }

    pub(crate) const fn pictures_taken(&self) -> u64 {
        self.pictures_taken
    }

    pub(crate) fn hold_picture(&mut self, picture: DecodedFrame) {
        self.pictures_taken = self.pictures_taken.wrapping_add(1);
        self.pictures.push_back(picture);
    }

    pub(crate) fn send(
        &mut self,
        packet: &AVPacket,
        recovery: &mut Recovery,
    ) -> Result<(), DecodeError> {
        let pts = packet.pts;
        let Some(payload) =
            alpha2_ffmpeg_bridge::packet_block_addition(packet, ALPHA_BLOCK_ADDITION)
        else {
            return self.damaged(pts, "the block carries no alpha data", recovery);
        };
        if self.awaiting_keyframe {
            if !alpha2_ffmpeg_bridge::vp9_frame_is_keyframe(payload) {
                if self.from_stream_start {
                    return self.damaged(
                        pts,
                        "the alpha stream starts without a key frame",
                        recovery,
                    );
                }
                self.pictures_dropped_unreported.insert(pts);
                return Ok(());
            }
            self.awaiting_keyframe = false;
        }
        let mut alpha = alpha2_ffmpeg_bridge::packet_from_bytes(payload).map_err(adapter_error)?;
        alpha.set_pts(packet.pts);
        alpha.set_dts(packet.dts);
        alpha.set_duration(packet.duration);
        for _ in 0..64 {
            match self.decoder.send_packet(Some(&alpha)) {
                Ok(()) => return Ok(()),
                Err(RsmpegError::DecoderFullError) => {
                    let received = self.alphas_received;
                    self.receive_ready_alphas(recovery)?;
                    if self.alphas_received == received {
                        return Err(DecodeError::Adapter(
                            "the alpha decoder takes no packet and returns no frame".into(),
                        ));
                    }
                }
                Err(error) => {
                    // FFmpeg's frame threads return an error with a later packet; pairing pins it.
                    recovery.unless_damage(error)?;
                    return Ok(());
                }
            }
        }
        Err(DecodeError::Adapter(
            "alpha packet retry budget exceeded".into(),
        ))
    }

    pub(crate) fn send_end(&mut self, recovery: &mut Recovery) -> Result<(), DecodeError> {
        if self.end != StreamEnd::Open {
            return Ok(());
        }
        loop {
            match self.decoder.send_packet(None) {
                Ok(()) | Err(RsmpegError::DecoderFlushedError) => break,
                Err(RsmpegError::DecoderFullError) => {
                    let received = self.alphas_received;
                    self.receive_ready_alphas(recovery)?;
                    if self.alphas_received == received {
                        break;
                    }
                }
                Err(error) => {
                    recovery.error(error, "video alpha flush", None)?;
                    break;
                }
            }
        }
        self.end = StreamEnd::Signalled;
        Ok(())
    }

    fn damaged(
        &mut self,
        pts: i64,
        detail: &str,
        recovery: &mut Recovery,
    ) -> Result<(), DecodeError> {
        self.pictures_dropped_unreported.insert(pts);
        report_damage(pts, detail, recovery)
    }

    fn receive_ready_alphas(&mut self, recovery: &mut Recovery) -> Result<(), DecodeError> {
        loop {
            match DecodedFrame::receive(&mut self.decoder) {
                Ok(frame) => {
                    self.alphas_received = self.alphas_received.wrapping_add(1);
                    if frame.flags
                        & i32::try_from(ffi::AV_FRAME_FLAG_CORRUPT).expect("flag fits i32")
                        != 0
                        || frame.decode_error_flags != 0
                    {
                        let pts = pairing_pts(&frame);
                        self.damaged(pts, "the alpha frame is corrupt", recovery)?;
                        continue;
                    }
                    self.alphas.push_back(frame);
                }
                Err(RsmpegError::DecoderDrainError) => return Ok(()),
                Err(RsmpegError::DecoderFlushedError) => {
                    self.end = StreamEnd::Drained;
                    return Ok(());
                }
                Err(error) => recovery.unless_damage(error)?,
            }
        }
    }

    pub(crate) fn next_pair(
        &mut self,
        recovery: &mut Recovery,
    ) -> Result<Option<RawFrame>, DecodeError> {
        self.receive_ready_alphas(recovery)?;
        while let Some(picture) = self.pictures.front() {
            let pts = pairing_pts(picture);
            self.pictures_dropped_unreported = self.pictures_dropped_unreported.split_off(&pts);
            while self
                .alphas
                .front()
                .is_some_and(|alpha| pairing_pts(alpha) < pts)
            {
                self.alphas.pop_front();
            }
            let dropped = self.pictures_dropped_unreported.remove(&pts);
            let matched = self
                .alphas
                .front()
                .is_some_and(|alpha| pairing_pts(alpha) == pts);
            if !matched && !dropped && self.alphas.is_empty() && self.end != StreamEnd::Drained {
                return Ok(None);
            }
            let picture = self.pictures.pop_front().expect("a picture waits");
            let alpha = matched.then(|| self.alphas.pop_front().expect("a matched alpha frame"));
            if dropped {
                continue;
            }
            let Some(alpha) = alpha else {
                report_damage(pts, "the alpha frame is missing", recovery)?;
                continue;
            };
            if let Err(detail) = alpha_fits(&picture, &alpha) {
                report_damage(pts, &detail, recovery)?;
                continue;
            }
            return Ok(Some(RawFrame {
                picture,
                alpha: Some(alpha),
            }));
        }
        Ok(None)
    }
}

fn report_damage(pts: i64, detail: &str, recovery: &mut Recovery) -> Result<(), DecodeError> {
    recovery.corrupt_with_detail(
        "video alpha",
        crate::recovery::pts(pts),
        Some(detail.to_owned()),
    )
}

fn alpha_fits(picture: &AVFrame, alpha: &AVFrame) -> Result<(), String> {
    if (alpha.width, alpha.height) != (picture.width, picture.height) {
        return Err(format!(
            "the alpha frame is {}x{}, the picture {}x{}",
            alpha.width, alpha.height, picture.width, picture.height
        ));
    }
    let depth = |format| alpha2_ffmpeg_bridge::yuv_layout(format).map(|layout| layout.bit_depth);
    let picture_depth =
        alpha2_ffmpeg_bridge::sample_profile(picture.format).map(|profile| profile.bit_depth);
    match (depth(alpha.format), picture_depth) {
        (Some(8), _) => Ok(()),
        (Some(alpha), Some(picture)) if u32::from(alpha) == u32::from(picture) => Ok(()),
        (alpha, picture) => Err(format!(
            "the alpha frame's depth {alpha:?} does not fit the picture's {picture:?}"
        )),
    }
}

fn alpha_plane(
    alpha: &DecodedFrame,
    depth: u8,
    msb_aligned: bool,
) -> Result<alpha2_media::Plane, DecodeError> {
    let planes = alpha
        .yuv_planes()
        .map_err(adapter_error)?
        .ok_or_else(|| DecodeError::Unsupported("the alpha frame has no luma plane".into()))?;
    let source_depth = planes.layout.bit_depth;
    let luma = planes.planes.into_iter().next().expect("a luma plane");
    if source_depth == depth && planes.layout.msb_aligned == msb_aligned {
        return Ok(alpha2_media::Plane {
            bytes: luma.bytes,
            stride: luma.stride,
            width: luma.width,
            height: luma.height,
        });
    }
    let rescale = match source_depth {
        8 => Rescale::Widen(Box::new(widened_alpha(depth, msb_aligned))),
        _ if source_depth == depth && msb_aligned && !planes.layout.msb_aligned => {
            Rescale::ToHighBits(16 - u32::from(depth))
        }
        _ => {
            return Err(DecodeError::Unsupported(format!(
                "a {source_depth}-bit alpha plane cannot go with {depth}-bit colour"
            )));
        }
    };
    let sample_bytes = usize::from(source_depth.div_ceil(8));
    let width = usize::try_from(luma.width).map_err(|_| DecodeError::OutOfRange)?;
    let stride = usize::try_from(luma.stride).map_err(|_| DecodeError::OutOfRange)?;
    let rows = usize::try_from(luma.height).map_err(|_| DecodeError::OutOfRange)?;
    let mut bytes = Vec::with_capacity(width * 2 * rows);
    for row in luma.bytes.chunks(stride).take(rows) {
        for sample in row[..width * sample_bytes].chunks(sample_bytes) {
            bytes.extend_from_slice(&rescale.sample(sample).to_le_bytes());
        }
    }
    Ok(alpha2_media::Plane {
        bytes: bytes.into(),
        stride: luma.width * 2,
        width: luma.width,
        height: luma.height,
    })
}

enum Rescale {
    Widen(Box<[u16; 256]>),
    ToHighBits(u32),
}

impl Rescale {
    fn sample(&self, bytes: &[u8]) -> u16 {
        match self {
            Self::Widen(table) => table[usize::from(bytes[0])],
            Self::ToHighBits(shift) => u16::from_le_bytes([bytes[0], bytes[1]]) << shift,
        }
    }
}

fn widened_alpha(depth: u8, msb_aligned: bool) -> [u16; 256] {
    let maximum = (1_u32 << depth) - 1;
    let shift = if msb_aligned {
        16 - u32::from(depth)
    } else {
        0
    };
    std::array::from_fn(|value| {
        let value = u32::try_from(value).expect("an index below 256");
        let widened = (value * maximum + 127) / 255;
        u16::try_from(widened << shift).expect("a sample fits 16 bits")
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn alpha_widens_from_eight_bits_keeping_its_ends() {
        let ten = widened_alpha(10, false);
        assert_eq!((ten[0], ten[128], ten[255]), (0, 514, 1023));
        let p010 = widened_alpha(10, true);
        assert_eq!((p010[0], p010[255]), (0, 1023 << 6));
        let sixteen = widened_alpha(16, false);
        assert_eq!((sixteen[1], sixteen[255]), (257, 65535));
        assert_eq!(widened_alpha(8, false)[200], 200);
    }
}