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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
use std::{
    fs::{self, File},
    path::Path,
    slice,
    sync::{
        atomic::{self, AtomicBool},
        mpsc, Arc,
    },
    thread::{self, JoinHandle},
};

use parking_lot::{Condvar, Mutex};
use windows::{
    core::HSTRING,
    Foundation::{EventRegistrationToken, TimeSpan, TypedEventHandler},
    Graphics::{
        DirectX::Direct3D11::IDirect3DSurface,
        Imaging::{BitmapAlphaMode, BitmapEncoder, BitmapPixelFormat},
    },
    Media::{
        Core::{
            MediaStreamSample, MediaStreamSource, MediaStreamSourceSampleRequestedEventArgs,
            MediaStreamSourceStartingEventArgs, VideoStreamDescriptor,
        },
        MediaProperties::{
            MediaEncodingProfile, MediaEncodingSubtypes, VideoEncodingProperties,
            VideoEncodingQuality,
        },
        Transcoding::MediaTranscoder,
    },
    Security::Cryptography::CryptographicBuffer,
    Storage::{
        FileAccessMode, StorageFile,
        Streams::{
            Buffer, DataReader, IRandomAccessStream, InMemoryRandomAccessStream, InputStreamOptions,
        },
    },
};

use crate::{
    d3d11::SendDirectX,
    frame::{Frame, ImageFormat},
    settings::ColorFormat,
};

#[derive(thiserror::Error, Eq, PartialEq, Clone, Debug)]
pub enum ImageEncoderError {
    #[error("This color format is not supported for saving as image")]
    UnsupportedFormat,
    #[error("Windows API Error: {0}")]
    WindowsError(#[from] windows::core::Error),
}

/// The `ImageEncoder` struct represents an image encoder that can be used to encode image buffers to image bytes with a specified format and color format.
pub struct ImageEncoder {
    format: ImageFormat,
    color_format: ColorFormat,
}

impl ImageEncoder {
    /// Create a new ImageEncoder with the specified format and color format.
    ///
    /// # Arguments
    ///
    /// * `format` - The desired image format.
    /// * `color_format` - The desired color format.
    ///
    /// # Returns
    ///
    /// A new `ImageEncoder` instance.
    pub const fn new(format: ImageFormat, color_format: ColorFormat) -> Self {
        Self {
            format,
            color_format,
        }
    }

    /// Encode the image buffer to image bytes with the specified format.
    ///
    /// # Arguments
    ///
    /// * `image_buffer` - The image buffer to encode.
    /// * `width` - The width of the image.
    /// * `height` - The height of the image.
    ///
    /// # Returns
    ///
    /// The encoded image bytes as a `Vec<u8>`.
    ///
    /// # Errors
    ///
    /// Returns an `Error` if the encoding fails or if the color format is unsupported.
    pub fn encode(
        &self,
        image_buffer: &[u8],
        width: u32,
        height: u32,
    ) -> Result<Vec<u8>, ImageEncoderError> {
        let encoder = match self.format {
            ImageFormat::Jpeg => BitmapEncoder::JpegEncoderId()?,
            ImageFormat::Png => BitmapEncoder::PngEncoderId()?,
            ImageFormat::Gif => BitmapEncoder::GifEncoderId()?,
            ImageFormat::Tiff => BitmapEncoder::TiffEncoderId()?,
            ImageFormat::Bmp => BitmapEncoder::BmpEncoderId()?,
            ImageFormat::JpegXr => BitmapEncoder::JpegXREncoderId()?,
        };

        let stream = InMemoryRandomAccessStream::new()?;
        let encoder = BitmapEncoder::CreateAsync(encoder, &stream)?.get()?;

        let pixelformat = match self.color_format {
            ColorFormat::Bgra8 => BitmapPixelFormat::Bgra8,
            ColorFormat::Rgba8 => BitmapPixelFormat::Rgba8,
            ColorFormat::Rgba16F => return Err(ImageEncoderError::UnsupportedFormat),
        };

        encoder.SetPixelData(
            pixelformat,
            BitmapAlphaMode::Premultiplied,
            width,
            height,
            1.0,
            1.0,
            image_buffer,
        )?;

        encoder.FlushAsync()?.get()?;

        let buffer = Buffer::Create(u32::try_from(stream.Size()?).unwrap())?;
        stream
            .ReadAsync(&buffer, buffer.Capacity()?, InputStreamOptions::None)?
            .get()?;

        let data_reader = DataReader::FromBuffer(&buffer)?;
        let length = data_reader.UnconsumedBufferLength()?;
        let mut bytes = vec![0u8; length as usize];
        data_reader.ReadBytes(&mut bytes)?;

        Ok(bytes)
    }
}

#[derive(thiserror::Error, Debug)]
pub enum VideoEncoderError {
    #[error("Windows API Error: {0}")]
    WindowsError(#[from] windows::core::Error),
    #[error("Frame send error")]
    FrameSendError(#[from] mpsc::SendError<Option<(VideoEncoderSource, TimeSpan)>>),
    #[error("IO Error: {0}")]
    IoError(#[from] std::io::Error),
}

unsafe impl Send for VideoEncoderError {}
unsafe impl Sync for VideoEncoderError {}

#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum VideoEncoderType {
    Avi,
    Hevc,
    Mp4,
    Wmv,
}

#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum VideoEncoderQuality {
    Auto = 0,
    HD1080p = 1,
    HD720p = 2,
    Wvga = 3,
    Ntsc = 4,
    Pal = 5,
    Vga = 6,
    Qvga = 7,
    Uhd2160p = 8,
    Uhd4320p = 9,
}

/// The `VideoEncoderSource` struct represents all the types that can be send to the encoder.
pub enum VideoEncoderSource {
    DirectX(SendDirectX<IDirect3DSurface>),
    Buffer((SendDirectX<*const u8>, usize)),
}

/// The `VideoEncoder` struct represents a video encoder that can be used to encode video frames and save them to a specified file path.
pub struct VideoEncoder {
    first_timespan: Option<TimeSpan>,
    frame_sender: mpsc::Sender<Option<(VideoEncoderSource, TimeSpan)>>,
    sample_requested: EventRegistrationToken,
    media_stream_source: MediaStreamSource,
    starting: EventRegistrationToken,
    transcode_thread: Option<JoinHandle<Result<(), VideoEncoderError>>>,
    frame_notify: Arc<(Mutex<bool>, Condvar)>,
    error_notify: Arc<AtomicBool>,
}

impl VideoEncoder {
    /// Creates a new `VideoEncoder` instance with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `encoder_type` - The type of video encoder to use.
    /// * `encoder_quality` - The quality of the video encoder.
    /// * `width` - The width of the video frames.
    /// * `height` - The height of the video frames.
    /// * `path` - The file path where the encoded video will be saved.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the `VideoEncoder` instance if successful, or a
    /// `VideoEncoderError` if an error occurs.
    pub fn new<P: AsRef<Path>>(
        encoder_type: VideoEncoderType,
        encoder_quality: VideoEncoderQuality,
        width: u32,
        height: u32,
        path: P,
    ) -> Result<Self, VideoEncoderError> {
        let path = path.as_ref();

        let media_encoding_profile = match encoder_type {
            VideoEncoderType::Avi => {
                MediaEncodingProfile::CreateAvi(VideoEncodingQuality(encoder_quality as i32))?
            }
            VideoEncoderType::Hevc => {
                MediaEncodingProfile::CreateHevc(VideoEncodingQuality(encoder_quality as i32))?
            }
            VideoEncoderType::Mp4 => {
                MediaEncodingProfile::CreateMp4(VideoEncodingQuality(encoder_quality as i32))?
            }
            VideoEncoderType::Wmv => {
                MediaEncodingProfile::CreateWmv(VideoEncodingQuality(encoder_quality as i32))?
            }
        };

        let video_encoding_properties = VideoEncodingProperties::CreateUncompressed(
            &MediaEncodingSubtypes::Bgra8()?,
            width,
            height,
        )?;

        let video_stream_descriptor = VideoStreamDescriptor::Create(&video_encoding_properties)?;

        let media_stream_source =
            MediaStreamSource::CreateFromDescriptor(&video_stream_descriptor)?;
        media_stream_source.SetBufferTime(TimeSpan::default())?;

        let (frame_sender, frame_receiver) =
            mpsc::channel::<Option<(VideoEncoderSource, TimeSpan)>>();

        let starting = media_stream_source.Starting(&TypedEventHandler::<
            MediaStreamSource,
            MediaStreamSourceStartingEventArgs,
        >::new(move |_, stream_start| {
            let stream_start = stream_start
                .as_ref()
                .expect("MediaStreamSource Starting parameter was None This Should Not Happen.");

            stream_start
                .Request()?
                .SetActualStartPosition(TimeSpan { Duration: 0 })?;
            Ok(())
        }))?;

        let frame_notify = Arc::new((Mutex::new(false), Condvar::new()));

        let sample_requested = media_stream_source.SampleRequested(&TypedEventHandler::<
            MediaStreamSource,
            MediaStreamSourceSampleRequestedEventArgs,
        >::new({
            let frame_receiver = frame_receiver;
            let frame_notify = frame_notify.clone();

            move |_, sample_requested| {
                let sample_requested = sample_requested.as_ref().expect(
                    "MediaStreamSource SampleRequested parameter was None This Should Not Happen.",
                );

                let frame = match frame_receiver.recv() {
                    Ok(frame) => frame,
                    Err(e) => panic!("Failed to receive frame from frame sender: {e}"),
                };

                match frame {
                    Some((source, timespan)) => {
                        let sample = match source {
                            VideoEncoderSource::DirectX(surface) => {
                                MediaStreamSample::CreateFromDirect3D11Surface(
                                    &surface.0, timespan,
                                )?
                            }
                            VideoEncoderSource::Buffer(buffer_data) => {
                                let buffer = buffer_data.0;
                                let buffer =
                                    unsafe { slice::from_raw_parts(buffer.0, buffer_data.1) };
                                let buffer = CryptographicBuffer::CreateFromByteArray(buffer)?;
                                MediaStreamSample::CreateFromBuffer(&buffer, timespan)?
                            }
                        };

                        sample_requested.Request()?.SetSample(&sample)?;
                    }
                    None => {
                        sample_requested.Request()?.SetSample(None)?;
                    }
                }

                let (lock, cvar) = &*frame_notify;
                *lock.lock() = true;
                cvar.notify_one();

                Ok(())
            }
        }))?;

        let media_transcoder = MediaTranscoder::new()?;
        media_transcoder.SetHardwareAccelerationEnabled(true)?;

        File::create(path)?;
        let path = fs::canonicalize(path).unwrap().to_string_lossy()[4..].to_string();
        let path = Path::new(&path);

        let path = &HSTRING::from(path.as_os_str().to_os_string());

        let file = StorageFile::GetFileFromPathAsync(path)?.get()?;
        let media_stream_output = file.OpenAsync(FileAccessMode::ReadWrite)?.get()?;

        let transcode = media_transcoder
            .PrepareMediaStreamSourceTranscodeAsync(
                &media_stream_source,
                &media_stream_output,
                &media_encoding_profile,
            )?
            .get()?;

        let error_notify = Arc::new(AtomicBool::new(false));
        let transcode_thread = thread::spawn({
            let error_notify = error_notify.clone();

            move || -> Result<(), VideoEncoderError> {
                let result = transcode.TranscodeAsync();

                if result.is_err() {
                    error_notify.store(true, atomic::Ordering::Relaxed);
                }

                result?.get()?;

                drop(media_transcoder);

                Ok(())
            }
        });

        Ok(Self {
            first_timespan: None,
            frame_sender,
            sample_requested,
            media_stream_source,
            starting,
            transcode_thread: Some(transcode_thread),
            frame_notify,
            error_notify,
        })
    }

    /// Creates a new `VideoEncoder` instance with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `encoder_type` - The type of video encoder to use.
    /// * `encoder_quality` - The quality of the video encoder.
    /// * `width` - The width of the video frames.
    /// * `height` - The height of the video frames.
    /// * `stream` - The stream where the encoded video will be saved.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the `VideoEncoder` instance if successful, or a
    /// `VideoEncoderError` if an error occurs.
    pub fn new_from_stream<P: AsRef<Path>>(
        encoder_type: VideoEncoderType,
        encoder_quality: VideoEncoderQuality,
        width: u32,
        height: u32,
        stream: IRandomAccessStream,
    ) -> Result<Self, VideoEncoderError> {
        let media_encoding_profile = match encoder_type {
            VideoEncoderType::Avi => {
                MediaEncodingProfile::CreateAvi(VideoEncodingQuality(encoder_quality as i32))?
            }
            VideoEncoderType::Hevc => {
                MediaEncodingProfile::CreateHevc(VideoEncodingQuality(encoder_quality as i32))?
            }
            VideoEncoderType::Mp4 => {
                MediaEncodingProfile::CreateMp4(VideoEncodingQuality(encoder_quality as i32))?
            }
            VideoEncoderType::Wmv => {
                MediaEncodingProfile::CreateWmv(VideoEncodingQuality(encoder_quality as i32))?
            }
        };

        let video_encoding_properties = VideoEncodingProperties::CreateUncompressed(
            &MediaEncodingSubtypes::Bgra8()?,
            width,
            height,
        )?;

        let video_stream_descriptor = VideoStreamDescriptor::Create(&video_encoding_properties)?;

        let media_stream_source =
            MediaStreamSource::CreateFromDescriptor(&video_stream_descriptor)?;
        media_stream_source.SetBufferTime(TimeSpan::default())?;

        let (frame_sender, frame_receiver) =
            mpsc::channel::<Option<(VideoEncoderSource, TimeSpan)>>();

        let starting = media_stream_source.Starting(&TypedEventHandler::<
            MediaStreamSource,
            MediaStreamSourceStartingEventArgs,
        >::new(move |_, stream_start| {
            let stream_start = stream_start
                .as_ref()
                .expect("MediaStreamSource Starting parameter was None This Should Not Happen.");

            stream_start
                .Request()?
                .SetActualStartPosition(TimeSpan { Duration: 0 })?;
            Ok(())
        }))?;

        let frame_notify = Arc::new((Mutex::new(false), Condvar::new()));

        let sample_requested = media_stream_source.SampleRequested(&TypedEventHandler::<
            MediaStreamSource,
            MediaStreamSourceSampleRequestedEventArgs,
        >::new({
            let frame_receiver = frame_receiver;
            let frame_notify = frame_notify.clone();

            move |_, sample_requested| {
                let sample_requested = sample_requested.as_ref().expect(
                    "MediaStreamSource SampleRequested parameter was None This Should Not Happen.",
                );

                let frame = match frame_receiver.recv() {
                    Ok(frame) => frame,
                    Err(e) => panic!("Failed to receive frame from frame sender: {e}"),
                };

                match frame {
                    Some((source, timespan)) => {
                        let sample = match source {
                            VideoEncoderSource::DirectX(surface) => {
                                MediaStreamSample::CreateFromDirect3D11Surface(
                                    &surface.0, timespan,
                                )?
                            }
                            VideoEncoderSource::Buffer(buffer_data) => {
                                let buffer = buffer_data.0;
                                let buffer =
                                    unsafe { slice::from_raw_parts(buffer.0, buffer_data.1) };
                                let buffer = CryptographicBuffer::CreateFromByteArray(buffer)?;
                                MediaStreamSample::CreateFromBuffer(&buffer, timespan)?
                            }
                        };

                        sample_requested.Request()?.SetSample(&sample)?;
                    }
                    None => {
                        sample_requested.Request()?.SetSample(None)?;
                    }
                }

                let (lock, cvar) = &*frame_notify;
                *lock.lock() = true;
                cvar.notify_one();

                Ok(())
            }
        }))?;

        let media_transcoder = MediaTranscoder::new()?;
        media_transcoder.SetHardwareAccelerationEnabled(true)?;

        let transcode = media_transcoder
            .PrepareMediaStreamSourceTranscodeAsync(
                &media_stream_source,
                &stream,
                &media_encoding_profile,
            )?
            .get()?;

        let error_notify = Arc::new(AtomicBool::new(false));
        let transcode_thread = thread::spawn({
            let error_notify = error_notify.clone();

            move || -> Result<(), VideoEncoderError> {
                let result = transcode.TranscodeAsync();

                if result.is_err() {
                    error_notify.store(true, atomic::Ordering::Relaxed);
                }

                result?.get()?;

                drop(media_transcoder);

                Ok(())
            }
        });

        Ok(Self {
            first_timespan: None,
            frame_sender,
            sample_requested,
            media_stream_source,
            starting,
            transcode_thread: Some(transcode_thread),
            frame_notify,
            error_notify,
        })
    }

    /// Sends a video frame to the video encoder for encoding.
    ///
    /// # Arguments
    ///
    /// * `frame` - A mutable reference to the `Frame` to be encoded.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the frame is successfully sent for encoding, or a `VideoEncoderError`
    /// if an error occurs.
    pub fn send_frame(&mut self, frame: &mut Frame) -> Result<(), VideoEncoderError> {
        let timespan = match self.first_timespan {
            Some(timespan) => TimeSpan {
                Duration: frame.timespan().Duration - timespan.Duration,
            },
            None => {
                let timespan = frame.timespan();
                self.first_timespan = Some(timespan);
                TimeSpan { Duration: 0 }
            }
        };
        let surface = SendDirectX::new(unsafe { frame.as_raw_surface() });

        self.frame_sender
            .send(Some((VideoEncoderSource::DirectX(surface), timespan)))?;

        let (lock, cvar) = &*self.frame_notify;
        let mut processed = lock.lock();
        if !*processed {
            cvar.wait(&mut processed);
        }
        *processed = false;
        drop(processed);

        if self.error_notify.load(atomic::Ordering::Relaxed) {
            if let Some(transcode_thread) = self.transcode_thread.take() {
                transcode_thread
                    .join()
                    .expect("Failed to join transcode thread")?;
            }
        }

        Ok(())
    }

    /// Sends a video frame to the video encoder for encoding.
    ///
    /// # Arguments
    ///
    /// * `buffer` - A reference to the byte slice to be encoded Windows API expect this to be Bgra and bottom-top.
    /// * `timespan` - The timespan that correlates to the frame buffer.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the frame is successfully sent for encoding, or a `VideoEncoderError`
    /// if an error occurs.
    pub fn send_frame_buffer(
        &mut self,
        buffer: &[u8],
        timespan: i64,
    ) -> Result<(), VideoEncoderError> {
        let frame_timespan = timespan;
        let timespan = match self.first_timespan {
            Some(timespan) => TimeSpan {
                Duration: frame_timespan - timespan.Duration,
            },
            None => {
                let timespan = frame_timespan;
                self.first_timespan = Some(TimeSpan { Duration: timespan });
                TimeSpan { Duration: 0 }
            }
        };

        self.frame_sender.send(Some((
            VideoEncoderSource::Buffer((SendDirectX::new(buffer.as_ptr()), buffer.len())),
            timespan,
        )))?;

        let (lock, cvar) = &*self.frame_notify;
        let mut processed = lock.lock();
        if !*processed {
            cvar.wait(&mut processed);
        }
        *processed = false;
        drop(processed);

        if self.error_notify.load(atomic::Ordering::Relaxed) {
            if let Some(transcode_thread) = self.transcode_thread.take() {
                transcode_thread
                    .join()
                    .expect("Failed to join transcode thread")?;
            }
        }

        Ok(())
    }

    /// Finishes encoding the video and performs any necessary cleanup.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the encoding is successfully finished, or a `VideoEncoderError` if an
    /// error occurs.
    pub fn finish(mut self) -> Result<(), VideoEncoderError> {
        self.frame_sender.send(None)?;

        if let Some(transcode_thread) = self.transcode_thread.take() {
            transcode_thread
                .join()
                .expect("Failed to join transcode thread")?;
        }

        self.media_stream_source.RemoveStarting(self.starting)?;
        self.media_stream_source
            .RemoveSampleRequested(self.sample_requested)?;

        Ok(())
    }
}

impl Drop for VideoEncoder {
    fn drop(&mut self) {
        let _ = self.frame_sender.send(None);

        if let Some(transcode_thread) = self.transcode_thread.take() {
            let _ = transcode_thread.join();
        }
    }
}

#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for VideoEncoder {}