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
use ffmpeg::format;
use ocl::{self, OclPrm};

use super::*;
use crate::capture;
use crate::hooks::hw::FrameCapture;
use crate::utils::MaybeUnavailable;

/// Resampling FPS converter which averages input frames for smooth motion.
pub struct SamplingConverter {
    /// Difference, in video frames, between how much time passed in-game and how much video we
    /// output.
    remainder: f64,

    /// The target time_base.
    time_base: f64,

    /// Data with a destructor, wrapped so `SamplingConverter` can be put in a static variable.
    private: SamplingConverterPrivate,
}

/// Data with a destructor.
struct SamplingConverterPrivate {
    /// Data used for OpenCL operations.
    ///
    /// This is Some(None) if OpenCL is unavailable and None during an engine restart.
    ocl_runtime_data: MaybeUnavailable<OclRuntimeData>,

    /// Pixels from the buffer are stored here when the engine restarts.
    ocl_backup_buffer: Option<Vec<ocl::prm::Float>>,

    /// The video resolution.
    video_resolution: (u32, u32),

    /// The OpenGL sampling buffer.
    gl_sampling_buffer: Vec<f32>,

    /// The OpenGL read buffer.
    gl_read_buffer: Vec<u8>,
}

/// Data used at runtime by OpenCL sampling.
struct OclRuntimeData {
    /// Buffer images.
    ocl_buffers: [ocl::Image<ocl::prm::Float>; 2],

    /// Output image.
    ocl_output_image: ocl::Image<ocl::prm::Float>,

    /// Index of the last written to OpenCL buffer.
    ocl_current_buffer_index: usize,
}

impl SamplingConverter {
    #[inline]
    pub fn new(engine: &mut Engine, time_base: f64, video_resolution: (u32, u32)) -> Self {
        assert!(time_base > 0f64);

        Self { remainder: 0f64,
               time_base,
               private: SamplingConverterPrivate::new(engine, video_resolution) }
    }

    /// This should be called before an engine restart.
    #[inline]
    pub fn backup_and_free_ocl_data(&mut self, engine: &mut Engine) {
        self.private.backup_and_free_ocl_data(engine);
    }
}

impl FPSConverter for SamplingConverter {
    fn time_passed<F>(&mut self, engine: &mut Engine, frametime: f64, capture: F)
        where F: FnOnce(&mut Engine) -> FrameCapture
    {
        assert!(frametime >= 0.0f64);

        let frame_capture = capture(engine);

        let old_remainder = self.remainder;
        self.remainder += frametime / self.time_base;

        let exposure = capture::get_capture_parameters(engine).sampling_exposure;

        if self.remainder <= (1f64 - exposure) {
            // Do nothing.
        } else if self.remainder < 1f64 {
            let weight = (self.remainder - old_remainder.max(1f64 - exposure)) * (1f64 / exposure);

            match frame_capture {
                FrameCapture::OpenGL(read_pixels) => {
                    let (w, h) = self.private.video_resolution;
                    self.private.gl_read_buffer.resize((w * h * 3) as usize, 0);
                    self.private
                        .gl_sampling_buffer
                        .resize((w * h * 3) as usize, 0f32);

                    read_pixels(engine.marker().1, (w, h), &mut self.private.gl_read_buffer);

                    let private: &mut SamplingConverterPrivate = &mut self.private;
                    weighted_image_add(&mut private.gl_sampling_buffer,
                                       &private.gl_read_buffer,
                                       weight as f32);
                }

                FrameCapture::OpenCL(ocl_gl_texture) => {
                    let ocl_data = self.private.get_ocl_data(engine).unwrap();

                    ocl_weighted_image_add(engine,
                                           ocl_gl_texture.as_ref(),
                                           ocl_data.src_buffer(),
                                           ocl_data.dst_buffer(),
                                           weight as f32);

                    ocl_data.switch_buffer_index();
                }
            }
        } else {
            let weight = (1f64 - old_remainder.max(1f64 - exposure)) * (1f64 / exposure);

            match frame_capture {
                FrameCapture::OpenGL(read_pixels) => {
                    let (w, h) = self.private.video_resolution;
                    self.private.gl_read_buffer.resize((w * h * 3) as usize, 0);
                    self.private
                        .gl_sampling_buffer
                        .resize((w * h * 3) as usize, 0f32);

                    read_pixels(engine.marker().1, (w, h), &mut self.private.gl_read_buffer);

                    let mut buf = capture::get_buffer(engine.marker().1, (w, h));
                    buf.set_format(format::Pixel::RGB24);
                    weighted_image_add_to(&self.private.gl_sampling_buffer,
                                          &self.private.gl_read_buffer,
                                          buf.as_mut_slice(),
                                          weight as f32);
                    capture::capture(engine.marker().1, buf, 1);

                    fill_with_black(&mut self.private.gl_sampling_buffer);

                    self.remainder -= 1f64;

                    // Output it more times if needed.
                    let additional_frames = self.remainder as usize;
                    if additional_frames > 0 {
                        let mut buf = capture::get_buffer(engine.marker().1, (w, h));
                        buf.set_format(format::Pixel::RGB24);
                        buf.as_mut_slice()
                           .copy_from_slice(&self.private.gl_read_buffer);
                        capture::capture(engine.marker().1, buf, additional_frames);

                        self.remainder -= additional_frames as f64;
                    }

                    // Add the remaining image into the buffer.
                    if self.remainder > (1f64 - exposure) {
                        let private: &mut SamplingConverterPrivate = &mut self.private;
                        weighted_image_add(&mut private.gl_sampling_buffer,
                                           &private.gl_read_buffer,
                                           ((self.remainder - (1f64 - exposure))
                                            * (1f64 / exposure))
                                           as f32);
                    }
                }

                FrameCapture::OpenCL(ocl_gl_texture) => {
                    let ocl_data = self.private.get_ocl_data(engine).unwrap();

                    ocl_weighted_image_add(engine,
                                           ocl_gl_texture.as_ref(),
                                           ocl_data.src_buffer(),
                                           ocl_data.output_image(),
                                           weight as f32);

                    ocl_fill_with_black(engine, ocl_data.dst_buffer());

                    ocl_data.switch_buffer_index();

                    // Output the frame.
                    let (w, h) = hw::get_resolution(engine.marker().1);
                    let mut buf = capture::get_buffer(engine.marker().1, (w, h));
                    hw::read_ocl_image_into_buf(engine, ocl_data.output_image(), &mut buf);
                    capture::capture(engine.marker().1, buf, 1);

                    self.remainder -= 1f64;

                    // Output it more times if needed.
                    let additional_frames = self.remainder as usize;
                    if additional_frames > 0 {
                        let mut buf = capture::get_buffer(engine.marker().1, (w, h));
                        hw::read_ocl_image_into_buf(engine, ocl_gl_texture.as_ref(), &mut buf);
                        capture::capture(engine.marker().1, buf, additional_frames);

                        self.remainder -= additional_frames as f64;
                    }

                    // Add the remaining image into the buffer.
                    if self.remainder > (1f64 - exposure) {
                        ocl_weighted_image_add(engine,
                                               ocl_gl_texture.as_ref(),
                                               ocl_data.src_buffer(),
                                               ocl_data.dst_buffer(),
                                               ((self.remainder - (1f64 - exposure))
                                                * (1f64 / exposure))
                                               as f32);
                        ocl_data.switch_buffer_index();
                    }
                }
            }
        }
    }
}

impl SamplingConverterPrivate {
    #[inline]
    fn new(engine: &mut Engine, video_resolution: (u32, u32)) -> Self {
        Self { ocl_runtime_data:
                   MaybeUnavailable::from_check_result(OclRuntimeData::new(engine,
                                                                           video_resolution)),
               ocl_backup_buffer: None,
               video_resolution,
               gl_sampling_buffer: Vec::new(),
               gl_read_buffer: Vec::new() }
    }

    #[inline]
    fn get_ocl_data(&mut self, engine: &mut Engine) -> Option<&mut OclRuntimeData> {
        if self.ocl_runtime_data.is_not_checked() {
            self.restore_ocl_data(engine);
        }

        self.ocl_runtime_data.as_mut().available()
    }

    /// This should be called before an engine restart.
    fn backup_and_free_ocl_data(&mut self, engine: &mut Engine) {
        let reset = if let MaybeUnavailable::Available(ref ocl_data) = self.ocl_runtime_data {
            // Copy the src buffer into the output image.
            ocl_weighted_image_add(engine,
                                   ocl_data.dst_buffer(),
                                   ocl_data.src_buffer(),
                                   ocl_data.output_image(),
                                   0f32);

            let image = ocl_data.output_image();

            let mut backup_buffer = Vec::with_capacity(image.element_count());
            backup_buffer.resize(image.element_count(), 0f32.into());

            image.read(&mut backup_buffer).enq().expect("image.read()");

            self.ocl_backup_buffer = Some(backup_buffer);

            true
        } else {
            false
        };

        if reset {
            self.ocl_runtime_data.reset();
        }
    }

    /// This should be called after an engine restart.
    fn restore_ocl_data(&mut self, engine: &mut Engine) {
        if !self.ocl_runtime_data.is_not_checked() {
            panic!("tried to restore already existing OpenCL data");
        }

        let ocl_data = OclRuntimeData::new(engine, self.video_resolution)
            .expect("changing from fullscreen to windowed is not supported");

        let temp_image = {
            let pro_que = hw::get_pro_que(engine).unwrap();
            hw::build_ocl_image(pro_que,
                                ocl::MemFlags::new().read_only().host_write_only(),
                                ocl::enums::ImageChannelDataType::Float,
                                self.video_resolution.into()).expect("building an OpenCL image")
        };

        let backup_buffer = self.ocl_backup_buffer.take().unwrap();
        temp_image.write(&backup_buffer)
                  .enq()
                  .expect("image.write()");

        // Copy the backup buffer into the src buffer.
        ocl_weighted_image_add(engine,
                               ocl_data.dst_buffer(),
                               &temp_image,
                               ocl_data.src_buffer(),
                               0f32);

        self.ocl_runtime_data = MaybeUnavailable::Available(ocl_data);
    }
}

impl OclRuntimeData {
    fn new(engine: &mut Engine, (w, h): (u32, u32)) -> Option<Self> {
        let mut rv = if let Some(pro_que) = hw::get_pro_que(engine) {
            Some(Self { ocl_buffers:
                            [hw::build_ocl_image(pro_que,
                                                 ocl::MemFlags::new().read_write()
                                                                     .host_no_access(),
                                                 ocl::enums::ImageChannelDataType::Float,
                                                 (w, h).into()).expect("building an OpenCL image"),
                             hw::build_ocl_image(pro_que,
                                                 ocl::MemFlags::new().read_write()
                                                                     .host_no_access(),
                                                 ocl::enums::ImageChannelDataType::Float,
                                                 (w, h).into()).expect("building an OpenCL image")],
                        ocl_output_image:
                            hw::build_ocl_image(pro_que,
                                                ocl::MemFlags::new().read_write().host_read_only(),
                                                ocl::enums::ImageChannelDataType::Float,
                                                (w, h).into()).expect("building an OpenCL image"),
                        ocl_current_buffer_index: 0 })
        } else {
            None
        };

        if let Some(ref mut rv) = rv {
            ocl_fill_with_black(engine, rv.src_buffer());
        }

        rv
    }

    #[inline]
    fn src_buffer(&self) -> &ocl::Image<ocl::prm::Float> {
        &self.ocl_buffers[self.ocl_current_buffer_index]
    }

    #[inline]
    fn dst_buffer(&self) -> &ocl::Image<ocl::prm::Float> {
        &self.ocl_buffers[self.ocl_current_buffer_index ^ 1]
    }

    #[inline]
    fn output_image(&self) -> &ocl::Image<ocl::prm::Float> {
        &self.ocl_output_image
    }

    #[inline]
    fn switch_buffer_index(&mut self) {
        self.ocl_current_buffer_index ^= 1;
    }
}

#[inline]
fn ocl_weighted_image_add<T: OclPrm, U: OclPrm, V: OclPrm>(engine: &mut Engine,
                                                           src: &ocl::Image<T>,
                                                           buf: &ocl::Image<U>,
                                                           dst: &ocl::Image<V>,
                                                           weight: f32) {
    let pro_que = hw::get_pro_que(engine).unwrap();

    let kernel = pro_que.kernel_builder("weighted_image_add")
                        .global_work_size(src.dims())
                        .arg(src)
                        .arg(buf)
                        .arg(dst)
                        .arg(weight)
                        .build()
                        .unwrap();

    unsafe {
        kernel.enq().expect("sampling kernel enq()");
    }
}

#[inline]
fn ocl_fill_with_black<T: OclPrm>(engine: &mut Engine, image: &ocl::Image<T>) {
    let pro_que = hw::get_pro_que(engine).unwrap();

    let kernel = pro_que.kernel_builder("fill_with_black")
                        .global_work_size(image.dims())
                        .arg(image)
                        .build()
                        .unwrap();

    unsafe {
        kernel.enq().expect("sampling kernel enq()");
    }
}

#[inline]
fn weighted_image_add(buf: &mut [f32], image: &[u8], weight: f32) {
    assert_eq!(buf.len(), image.len());

    for i in 0..buf.len() {
        buf[i] += f32::from(image[i]) * weight;
    }
}

#[inline]
fn weighted_image_add_to(buf: &[f32], image: &[u8], dst: &mut [u8], weight: f32) {
    assert_eq!(buf.len(), image.len());
    assert_eq!(buf.len(), dst.len());

    for i in 0..buf.len() {
        dst[i] = (buf[i] + f32::from(image[i]) * weight).round() as u8;
    }
}

#[inline]
fn fill_with_black(buf: &mut [f32]) {
    buf.iter_mut().for_each(|x| *x = 0.);
}

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

    #[test]
    fn fill_with_black_test() {
        let mut buf = [1f32, 2f32, 3f32, 4f32, 5f32];

        fill_with_black(&mut buf[..]);

        assert_eq!(buf, [0f32, 0f32, 0f32, 0f32, 0f32]);
    }

    #[test]
    fn weighted_image_add_test() {
        let mut buf = [1f32, 2f32, 3f32, 4f32, 5f32];
        let image = [10, 20, 30, 40, 50];

        weighted_image_add(&mut buf, &image, 0.5f32);

        assert_eq!(buf, [6f32, 12f32, 18f32, 24f32, 30f32]);
    }

    #[test]
    #[should_panic]
    fn weighted_image_add_len_mismatch_test() {
        let mut buf = [1f32, 2f32, 3f32, 4f32, 5f32];
        let image = [10, 20, 30, 40, 50, 60];

        weighted_image_add(&mut buf, &image, 0.5f32);
    }

    #[test]
    fn weighted_image_add_to_test() {
        let buf = [1f32, 2f32, 3f32, 4f32, 5f32];
        let image = [10, 20, 30, 40, 50];
        let mut dst = [5, 4, 3, 2, 1];

        weighted_image_add_to(&buf, &image, &mut dst, 0.5f32);

        assert_eq!(dst, [6, 12, 18, 24, 30]);
    }

    #[test]
    #[should_panic]
    fn weighted_image_add_to_len_mismatch_test() {
        let buf = [1f32, 2f32, 3f32, 4f32, 5f32];
        let image = [10, 20, 30, 40, 50, 60];
        let mut dst = [5, 4, 3, 2, 1];

        weighted_image_add_to(&buf, &image, &mut dst, 0.5f32);
    }

    #[test]
    #[should_panic]
    fn weighted_image_add_to_dst_len_mismatch_test() {
        let buf = [1f32, 2f32, 3f32, 4f32, 5f32];
        let image = [10, 20, 30, 40, 50];
        let mut dst = [5, 4, 3, 2, 1, 0];

        weighted_image_add_to(&buf, &image, &mut dst, 0.5f32);
    }
}