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
656
657
#![doc = include_str!("../README.md")]
use std::f64::consts::{LN_10, PI};
use std::ops::{Index, IndexMut};
use std::sync::RwLock;
use image::{DynamicImage, GenericImageView};
use itertools::Itertools;
use libm::lgamma;
#[cfg(feature = "rayon")]
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
mod convert;
use convert::{LuminanceImage, ToLumaZero};
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("image and jpeg99 have different dimensions")]
DifferentDimensions,
}
type Result<T> = std::result::Result<T, Error>;
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub struct Grid(pub u8);
impl Grid {
const fn from_xy(x: u32, y: u32) -> Self {
Self(((x % 8) + (y % 8) * 8) as u8)
}
pub const fn x(&self) -> u8 {
self.0 % 8
}
pub const fn y(&self) -> u8 {
self.0 / 8
}
}
#[derive(Default, Clone, Copy, Debug)]
pub struct ForgedRegion {
pub x0: u32,
pub y0: u32,
pub x1: u32,
pub y1: u32,
pub grid: Grid,
pub lnfa: f64,
}
pub struct ForeignGridAreas {
votes: Votes,
forgery_mask: Vec<u8>,
forged_regions: Vec<ForgedRegion>,
lnfa_grids: [f64; 64],
main_grid: Option<Grid>,
}
impl ForeignGridAreas {
pub fn votes(&self) -> &Votes {
&self.votes
}
pub fn forgery_mask(&self) -> &[u8] {
self.forgery_mask.as_ref()
}
pub fn forged_regions(&self) -> &[ForgedRegion] {
self.forged_regions.as_ref()
}
pub fn lnfa_grids(&self) -> [f64; 64] {
self.lnfa_grids
}
pub fn main_grid(&self) -> Option<Grid> {
self.main_grid
}
pub fn is_cropped(&self) -> bool {
self.main_grid.map_or(false, |grid| grid.0 > 0)
}
}
pub struct MissingGridAreas {
votes: Votes,
missing_regions: Vec<ForgedRegion>,
forgery_mask: Vec<u8>,
}
impl MissingGridAreas {
pub fn votes(&self) -> &Votes {
&self.votes
}
pub fn missing_regions(&self) -> &[ForgedRegion] {
self.missing_regions.as_ref()
}
pub fn forgery_mask(&self) -> &[u8] {
self.forgery_mask.as_ref()
}
}
pub struct Zero {
luminance: LuminanceImage,
jpeg_99: Option<LuminanceImage>,
}
impl Zero {
pub fn from_image(image: &DynamicImage) -> Self {
let luminance = image.to_luma32f_zero();
Self {
luminance,
jpeg_99: None,
}
}
pub fn with_missing_grids_detection<'a>(
mut self,
jpeg_99: impl Into<Option<&'a DynamicImage>>,
) -> Result<Self> {
let image = if let Some(image) = jpeg_99.into() {
image
} else {
return Ok(self);
};
if image.dimensions() != self.luminance.dimensions() {
return Err(Error::DifferentDimensions);
}
self.jpeg_99 = Some(image.to_luma32f_zero());
Ok(self)
}
pub fn detect_forgeries(self) -> (ForeignGridAreas, Option<MissingGridAreas>) {
let width = self.luminance.width();
let height = self.luminance.height();
let votes = Votes::from_luminance(&self.luminance);
let (main_grid, lnfa_grids) = votes.detect_global_grids();
let (forged_regions, forgery_mask) = votes.detect_forgeries(main_grid, Grid(63));
let forgeries = ForeignGridAreas {
votes,
forgery_mask,
forged_regions,
lnfa_grids,
main_grid,
};
if let Some(main_grid) = main_grid {
if let Some(jpeg_99) = self.jpeg_99 {
let mut jpeg_99_votes = Votes::from_luminance(&jpeg_99);
for x in 0..width {
for y in 0..height {
let index = (x + y * width) as usize;
if forgeries.votes[index] == Some(main_grid) {
jpeg_99_votes[index] = None;
}
}
}
let (jpeg_99_forged_regions, jpeg_99_forgery_mask) =
jpeg_99_votes.detect_forgeries(None, Grid(0));
let missing_grid_areas = MissingGridAreas {
votes: jpeg_99_votes,
missing_regions: jpeg_99_forged_regions,
forgery_mask: jpeg_99_forgery_mask,
};
return (forgeries, Some(missing_grid_areas));
}
}
(forgeries, None)
}
}
pub struct Votes {
votes: Box<[Option<Grid>]>,
width: u32,
height: u32,
log_nt: f64,
}
impl Index<usize> for Votes {
type Output = Option<Grid>;
fn index(&self, index: usize) -> &Self::Output {
&self.votes[index]
}
}
impl Index<[u32; 2]> for Votes {
type Output = Option<Grid>;
fn index(&self, xy: [u32; 2]) -> &Self::Output {
&self.votes[(xy[0] + xy[1] * self.width) as usize]
}
}
impl IndexMut<usize> for Votes {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.votes[index]
}
}
impl Votes {
fn from_luminance(image: &LuminanceImage) -> Self {
struct State {
zero: Vec<u32>,
votes: Vec<Option<Grid>>,
}
let cosine = cosine_table();
let zero = vec![0u32; (image.width() * image.height()) as usize];
let votes = vec![None; (image.width() * image.height()) as usize];
let lock = RwLock::new(State { zero, votes });
let iter = 0..image.height() - 7;
#[cfg(feature = "rayon")]
let iter = iter.into_par_iter();
iter.for_each(|y| {
for x in 0..image.width() - 7 {
let number_of_zeroes = unsafe { compute_number_of_zeros(&cosine, image, x, y) };
let const_along = unsafe { is_const_along_x_or_y(image, x, y) };
{
let mut state = lock.write().unwrap();
for xx in x..x + 8 {
for yy in y..y + 8 {
let index = (xx + yy * image.width()) as usize;
unsafe {
match number_of_zeroes.cmp(state.zero.get_unchecked(index)) {
std::cmp::Ordering::Equal => {
*state.votes.get_unchecked_mut(index) = None;
}
std::cmp::Ordering::Greater => {
*state.zero.get_unchecked_mut(index) = number_of_zeroes;
*state.votes.get_unchecked_mut(index) = if const_along {
None
} else {
Some(Grid::from_xy(x, y))
};
}
std::cmp::Ordering::Less => (),
}
}
}
}
}
}
});
let mut votes = lock.into_inner().unwrap().votes;
for xx in 0..image.width() {
for yy in 0..7 {
let index = (xx + yy * image.width()) as usize;
votes[index] = None;
}
for yy in (image.height() - 7)..image.height() {
let index = (xx + yy * image.width()) as usize;
votes[index] = None;
}
}
for yy in 0..image.height() {
for xx in 0..7 {
let index = (xx + yy * image.width()) as usize;
votes[index] = None;
}
for xx in (image.width() - 7)..image.width() {
let index = (xx + yy * image.width()) as usize;
votes[index] = None;
}
}
Self {
votes: votes.into_boxed_slice(),
width: image.width(),
height: image.height(),
log_nt: 2.0f64.mul_add(
f64::from(image.height()).log10(),
2.0f64.mul_add(64.0f64.log10(), 2.0 * f64::from(image.width()).log10()),
),
}
}
fn detect_global_grids(&self) -> (Option<Grid>, [f64; 64]) {
let mut grid_votes = [0u32; 64];
let p = 1.0 / 64.0;
let most_voted_grid = self.votes.iter().flatten().max_by_key(|grid| {
let votes = &mut grid_votes[grid.0 as usize];
*votes += 1;
*votes
});
let n = self.width * self.height / 64;
let lnfa_grids: [f64; 64] = std::array::from_fn(|i| {
let k = grid_votes[i] / 64;
log_nfa(n, k, p, self.log_nt)
});
if let Some(most_voted_grid) = most_voted_grid {
if lnfa_grids[most_voted_grid.0 as usize] < 0.0 {
return (Some(*most_voted_grid), lnfa_grids);
}
}
(None, lnfa_grids)
}
fn detect_forgeries(
&self,
grid_to_exclude: Option<Grid>,
grid_max: Grid,
) -> (Vec<ForgedRegion>, Vec<u8>) {
let p = 1.0 / 64.0;
let w = 9;
let min_size = (64.0 * self.log_nt / 64.0f64.log10()).ceil() as usize;
let mut mask_aux = vec![0u8; self.votes.len()];
let mut used = vec![false; self.votes.len()];
let mut forgery_mask = vec![0u8; self.votes.len()];
let mut forgery_mask_reg = vec![0; self.votes.len()];
let mut forged_regions = Vec::new();
for x in 0..self.width {
for y in 0..self.height {
let index = (x + y * self.width) as usize;
if used[index] {
continue;
}
if self[index] == grid_to_exclude {
continue;
}
let grid = if let Some(grid) = self[index] {
grid
} else {
continue;
};
if grid.0 > grid_max.0 {
continue;
}
let mut x0 = x; let mut y0 = y;
let mut x1 = x;
let mut y1 = y;
used[index] = true;
let mut regions_xy = vec![(x, y)];
let mut i = 0;
while i < regions_xy.len() {
let (reg_x, reg_y) = regions_xy[i];
for xx in reg_x.saturating_sub(w)..=reg_x.saturating_add(w).min(self.width - 1)
{
for yy in
reg_y.saturating_sub(w)..=reg_y.saturating_add(w).min(self.height - 1)
{
let index = (xx + yy * self.width) as usize;
if used[index] {
continue;
}
if self[index] != Some(grid) {
continue;
}
used[index] = true;
regions_xy.push((xx, yy));
if xx < x0 {
x0 = xx;
}
if yy < y0 {
y0 = yy;
}
if xx > x1 {
x1 = xx;
}
if yy > y1 {
y1 = yy;
}
}
}
i += 1;
}
if regions_xy.len() >= min_size {
let n = (x1 - x0 + 1) * (y1 - y0 + 1) / 64;
let k = regions_xy.len() / 64;
let lnfa = log_nfa(n, k as u32, p, self.log_nt);
if lnfa < 0.0 {
forged_regions.push(ForgedRegion {
x0,
y0,
x1,
y1,
grid,
lnfa,
});
for (reg_x, reg_y) in ®ions_xy {
let index = reg_x + reg_y * self.width;
forgery_mask[index as usize] = 255;
}
}
}
}
}
for x in w..(self.width - w) {
for y in w..(self.height - w) {
let index = (x + y * self.width) as usize;
if forgery_mask[index] != 0 {
for xx in (x - w)..=(x + w) {
for yy in (y - w)..=(y + w) {
let index = (xx + yy * self.width) as usize;
mask_aux[index] = 255;
forgery_mask_reg[index] = 255;
}
}
}
}
}
for x in w..(self.width - w) {
for y in w..(self.height - w) {
let index = (x + y * self.width) as usize;
if mask_aux[index] == 0 {
for xx in (x - w)..=(x + w) {
for yy in (y - w)..=(y + w) {
let index = (xx + yy * self.width) as usize;
forgery_mask_reg[index] = 0;
}
}
}
}
}
(forged_regions, forgery_mask_reg)
}
}
fn cosine_table() -> [[f64; 8]; 8] {
let mut cosine = [[0.0; 8]; 8];
(0..8).cartesian_product(0..8).for_each(|(k, l)| {
cosine[k as usize][l as usize] =
(2.0f64.mul_add(f64::from(k), 1.0) * f64::from(l) * PI / 16.0).cos();
});
cosine
}
unsafe fn compute_number_of_zeros(
cosine: &[[f64; 8]; 8],
image: &LuminanceImage,
x: u32,
y: u32,
) -> u32 {
let vec = image.as_raw();
(0..8)
.cartesian_product(0..8)
.filter(|(i, j)| *i > 0 || *j > 0)
.map(|(i, j)| {
let normalization = 0.25
* (if i == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 })
* (if j == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 });
let dct_ij = (0..8)
.cartesian_product(0..8)
.map(|(xx, yy)| {
let index = (x + xx + (y + yy) * image.width()) as usize;
let pixel = vec.get_unchecked(index);
pixel * cosine[xx as usize][i as usize] * cosine[yy as usize][j as usize]
})
.sum::<f64>()
* normalization;
u32::from(dct_ij.abs() < 0.5)
})
.sum()
}
unsafe fn is_const_along_x_or_y(image: &LuminanceImage, x: u32, y: u32) -> bool {
let along_y = || {
for yy in 0..8 {
let v1 = image.unsafe_get_pixel(x, y + yy);
for xx in 1..8 {
let v2 = image.unsafe_get_pixel(x + xx, y + yy);
if v1 != v2 {
return false;
}
}
}
true
};
let along_x = || {
for xx in 0..8 {
let v1 = image.unsafe_get_pixel(x + xx, y);
for yy in 1..8 {
let v2 = image.unsafe_get_pixel(x + xx, y + yy);
if v1 != v2 {
return false;
}
}
}
true
};
along_x() || along_y()
}
fn log_nfa(n: u32, k: u32, p: f64, log_nt: f64) -> f64 {
let tolerance = 0.1;
let p_term = p / (1.0 - p);
debug_assert!(k <= n && (0.0..=1.0).contains(&p));
if n == 0 || k == 0 {
return log_nt;
} else if n == k {
return f64::from(n).mul_add(p.log10(), log_nt);
}
let log1term =
lgamma(f64::from(n) + 1.0) - lgamma(f64::from(k) + 1.0) - lgamma(f64::from(n - k) + 1.0)
+ f64::from(k) * p.ln()
+ f64::from(n - k) * (1.0 - p).ln();
let mut term = log1term.exp();
if term == 0.0 {
if f64::from(k) > f64::from(n) * p {
return log1term / LN_10 + log_nt;
}
return log_nt;
}
let mut bin_tail = term;
for i in (k + 1)..=n {
let bin_term = f64::from(n - i + 1) * 1.0 / f64::from(i);
let mult_term = bin_term * p_term;
term *= mult_term;
bin_tail += term;
if bin_term < 1.0 {
let err =
term * ((1.0 - mult_term.powf(f64::from(n - i + 1))) / (1.0 - mult_term) - 1.0);
if err < tolerance * (-bin_tail.log10() - log_nt).abs() * bin_tail {
break;
}
}
}
bin_tail.log10() + log_nt
}