Support for finding similar videos (#460)

* Add support for similar videos to CLI

* Add GUI support for similar videos

* Video duplicates

* git_dup

* Documentation
pull/461/head
Rafał Mikrut 2 years ago committed by GitHub
parent 4a202633ee
commit 29129d3ec0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

1
.gitignore vendored

@ -6,3 +6,4 @@
results*.txt
TestSuite*
*.snap
flatpak/

117
Cargo.lock generated

@ -47,9 +47,9 @@ dependencies = [
[[package]]
name = "anyhow"
version = "1.0.45"
version = "1.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee10e43ae4a853c0a3591d4e2ada1719e553be18199d9da9d4a83f5927c2f5c7"
checksum = "62e1f47f7dc0422027a4e370dd4548d4d66b26782e513e98dca1e689e058a80e"
[[package]]
name = "arrayref"
@ -476,6 +476,7 @@ dependencies = [
"crc32fast",
"crossbeam-channel",
"directories-next",
"ffmpeg_cmdline_utils",
"futures",
"hamming",
"humansize",
@ -484,6 +485,7 @@ dependencies = [
"rayon",
"rodio",
"tempfile",
"vid_dup_finder_lib",
"xxhash-rust",
"zip",
]
@ -601,6 +603,19 @@ version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
[[package]]
name = "ffmpeg_cmdline_utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f156b1f5ba5f16135ec1efd32d9f90d0dad3ef8f8b77ca9928d4d0e3b24dd41"
dependencies = [
"image",
"rayon",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "field-offset"
version = "0.3.4"
@ -1051,7 +1066,7 @@ checksum = "5ea4eac6fc4f64ed363d5c210732b747bfa5ddd8a25ac347d887f298c3a70b49"
dependencies = [
"base64",
"image",
"rustdct",
"rustdct 0.4.0",
"serde",
"transpose 0.2.1",
]
@ -1074,6 +1089,12 @@ dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"
[[package]]
name = "jni"
version = "0.19.0"
@ -1146,15 +1167,15 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.107"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbe5e23404da5b4f555ef85ebed98fb4083e55a00c317800bc2a50ede9f3d219"
checksum = "8521a1b57e76b1ec69af7599e75e38e7b7fad6610f037db8c79b127201b5d119"
[[package]]
name = "libloading"
version = "0.7.1"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0cf036d15402bea3c5d4de17b3fce76b3e4a56ebc1f577be0e7a72f7c607cf0"
checksum = "afe203d669ec979b7128619bae5a63b7b42e9203c1b29146079ee05e2f604b52"
dependencies = [
"cfg-if",
"winapi",
@ -1336,9 +1357,9 @@ dependencies = [
[[package]]
name = "ndk-sys"
version = "0.2.1"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c44922cb3dbb1c70b5e5f443d63b64363a898564d739ba5198e3a9138442868d"
checksum = "e1bcdd74c20ad5d95aacd60ef9ba40fdf77f767051040541df557b7a9b2a2121"
[[package]]
name = "nix"
@ -1372,6 +1393,15 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-complex"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "747d632c0c558b87dbabbe6a82f3b4ae03720d0646ac5b7b4dae89394be5f2c5"
dependencies = [
"num-traits",
]
[[package]]
name = "num-derive"
version = "0.3.3"
@ -1611,6 +1641,15 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed0cfbc8191465bed66e1718596ee0b0b35d5ee1f41c5df2189d0fe8bde535ba"
[[package]]
name = "primal-check"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01419cee72c1a1ca944554e23d83e483e1bccf378753344e881de28b5487511d"
dependencies = [
"num-integer",
]
[[package]]
name = "proc-macro-crate"
version = "0.1.5"
@ -1826,7 +1865,16 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef4d167674b4cf68c2114bdbcd34c95aa9071652b73b0f43b19298f1d2780b7d"
dependencies = [
"rustfft",
"rustfft 3.0.1",
]
[[package]]
name = "rustdct"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fadcb505b98aa64da1dadb1498b912e3642aae4606623cb3ae952cd8da33f80d"
dependencies = [
"rustfft 5.1.1",
]
[[package]]
@ -1835,13 +1883,33 @@ version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77008ed59a8923c8b4ac2e5eaa6d28fbe893d3b9515098a4a5fc7767d6430fe5"
dependencies = [
"num-complex",
"num-complex 0.2.4",
"num-integer",
"num-traits",
"strength_reduce",
"transpose 0.1.0",
]
[[package]]
name = "rustfft"
version = "5.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1869bb2a6ff77380d52ff4bc631f165637035a55855c76aa462c85474dadc42f"
dependencies = [
"num-complex 0.3.1",
"num-integer",
"num-traits",
"primal-check",
"strength_reduce",
"transpose 0.2.1",
]
[[package]]
name = "ryu"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]]
name = "same-file"
version = "1.0.6"
@ -1901,6 +1969,17 @@ dependencies = [
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "063bf466a64011ac24040a49009724ee60a57da1b437617ceb32e53ad61bfb19"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "shlex"
version = "0.1.1"
@ -2193,6 +2272,22 @@ version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe"
[[package]]
name = "vid_dup_finder_lib"
version = "0.1.0"
source = "git+https://github.com/qarmin/vid_dup_finder_lib#a4809772aea8f73c9a22da6fb43df50bfdd1b31d"
dependencies = [
"ffmpeg_cmdline_utils",
"image",
"rand",
"rayon",
"rustdct 0.6.0",
"serde",
"serde_json",
"thiserror",
"transpose 0.2.1",
]
[[package]]
name = "walkdir"
version = "2.3.2"

@ -1,5 +1,6 @@
## Version 3.3.1 - 22.11.2021r
- Fix crash when moving buttons [#457](https://github.com/qarmin/czkawka/pull/457)
- Hide move button at start [c9ca230](https://github.com/qarmin/czkawka/commit/c9ca230dfd05e2166b2d68683b091cfd45037edd)
## Version 3.3.0 - 20.11.2021r
- Select files by pressing space key [#415](https://github.com/qarmin/czkawka/pull/415)

@ -20,6 +20,7 @@
- Empty Files - Looks for empty files across the drive
- Temporary Files - Finds temporary files
- Similar Images - Finds images which are not exactly the same (different resolution, watermarks)
- Similar Videos - Looks for similar visually videos
- Zeroed Files - Finds files which are filled with zeros (usually corrupted)
- Same Music - Searches for music with the same artist, album etc.
- Invalid Symbolic Links - Shows symbolic links which point to non-existent files/directories
@ -101,10 +102,11 @@ Bleachbit is a master at finding and removing temporary files, while Czkawka onl
| Temporary files | • | • | | • |
| Big files | • | | | |
| Similar images | • | | • | |
| Zeroed Files | • | | | |
| Similar videos | • | | | |
| Zeroed files | • | | | |
| Music duplicates(tags) | • | | • | |
| Invalid symlinks | • | • | | |
| Broken Files | • | | | |
| Broken files | • | | | |
| Names conflict | • | • | | |
| Installed packages | | • | | |
| Invalid names | | • | | |

@ -123,7 +123,7 @@ pub enum Commands {
not_recursive: NotRecursive,
#[structopt(short = "g", long, default_value = "Gradient", parse(try_from_str = parse_similar_hash_algorithm), help="Hash algorithm (allowed: Mean, Gradient, Blockhash, VertGradient, DoubleGradient)")]
hash_alg: HashAlg,
#[structopt(short = "f", long, default_value = "Lanczos3", parse(try_from_str = parse_similar_image_filter), help="Hash algorithm (allowed: Lanczos3, Nearest, Triangle, Faussian, Catmullrom)")]
#[structopt(short = "z", long, default_value = "Lanczos3", parse(try_from_str = parse_similar_image_filter), help="Hash algorithm (allowed: Lanczos3, Nearest, Triangle, Faussian, Catmullrom)")]
image_filter: FilterType,
#[structopt(short = "c", long, default_value = "8", parse(try_from_str = parse_image_hash_size), help="Hash size (allowed: 4, 8, 16)")]
hash_size: u8,
@ -204,6 +204,29 @@ pub enum Commands {
#[structopt(flatten)]
not_recursive: NotRecursive,
},
#[structopt(name = "video", about = "Finds similar video files", help_message = HELP_MESSAGE, after_help = "EXAMPLE:\n czkawka videos -d /home/rafal -f results.txt")]
SimilarVideos {
#[structopt(flatten)]
directories: Directories,
#[structopt(flatten)]
excluded_directories: ExcludedDirectories,
#[structopt(flatten)]
excluded_items: ExcludedItems,
// #[structopt(short = "D", long, help = "Delete found files")]
// delete_files: bool, TODO
#[structopt(flatten)]
file_to_save: FileToSave,
#[structopt(flatten)]
allowed_extensions: AllowedExtensions,
#[structopt(flatten)]
not_recursive: NotRecursive,
#[structopt(short, long, parse(try_from_str = parse_minimal_file_size), default_value = "8192", help = "Minimum size in bytes", long_help = "Minimum size of checked files in bytes, assigning bigger value may speed up searching")]
minimal_file_size: u64,
#[structopt(short = "i", long, parse(try_from_str = parse_maximal_file_size), default_value = "18446744073709551615", help = "Maximum size in bytes", long_help = "Maximum size of checked files in bytes, assigning lower value may speed up searching")]
maximal_file_size: u64,
#[structopt(short = "t", long, parse(try_from_str = parse_tolerance), default_value = "10", help = "Video maximium difference (allowed values <0,20>)", long_help = "Maximum difference between video frames, bigger value means that videos can looks more and more different (allowed values <0,20>)")]
tolerance: i32,
},
#[structopt(name = "tester", about = "Contains various test", help_message = HELP_MESSAGE, after_help = "EXAMPLE:\n czkawka tests -i")]
Tester {
#[structopt(short = "i", long = "test_image", help = "Test speed of hashing provided test.jpg image with different filters and methods.")]
@ -283,6 +306,19 @@ fn parse_hash_type(src: &str) -> Result<HashType, &'static str> {
}
}
fn parse_tolerance(src: &str) -> Result<i32, &'static str> {
match src.parse::<i32>() {
Ok(t) => {
if (0..=20).contains(&t) {
Ok(t)
} else {
Err("Tolerance should be in range <0,20>(Higher and lower similarity )")
}
}
_ => Err("Failed to parse tolerance as i32 value."),
}
}
fn parse_checking_method(src: &str) -> Result<CheckingMethod, &'static str> {
match src.to_ascii_lowercase().as_str() {
"name" => Ok(CheckingMethod::Name),

@ -16,6 +16,7 @@ use czkawka_core::{
invalid_symlinks::InvalidSymlinks,
same_music::SameMusic,
similar_images::{return_similarity_from_similarity_preset, SimilarImages},
similar_videos::SimilarVideos,
temporary::{self, Temporary},
zeroed::{self, ZeroedFiles},
};
@ -385,6 +386,41 @@ fn main() {
br.print_results();
br.get_text_messages().print_messages();
}
Commands::SimilarVideos {
directories,
excluded_directories,
excluded_items,
file_to_save,
not_recursive,
tolerance,
minimal_file_size,
maximal_file_size,
allowed_extensions,
} => {
let mut vr = SimilarVideos::new();
vr.set_included_directory(directories.directories);
vr.set_excluded_directory(excluded_directories.excluded_directories);
vr.set_excluded_items(excluded_items.excluded_items);
vr.set_allowed_extensions(allowed_extensions.allowed_extensions.join(","));
vr.set_recursive_search(!not_recursive.not_recursive);
vr.set_minimal_file_size(minimal_file_size);
vr.set_maximal_file_size(maximal_file_size);
vr.set_tolerance(tolerance);
vr.find_similar_videos(None, None);
if let Some(file_name) = file_to_save.file_name() {
if !vr.save_results_to_file(file_name) {
vr.get_text_messages().print_messages();
process::exit(1);
}
}
#[cfg(not(debug_assertions))] // This will show too much probably unnecessary data to debug, comment line only if needed
vr.print_results();
vr.get_text_messages().print_messages();
}
Commands::Tester { test_image } => {
if test_image {
test_image_conversion_speed();

@ -34,13 +34,17 @@ futures = "0.3.17"
zip = "0.5.13"
rodio = { version = "0.14.0", optional = true }
# Hashes
# Hashes for duplicate files
blake3 = "1.2.0"
crc32fast = "1.2.1"
xxhash-rust = { version = "0.8.2", features = ["xxh3"] }
tempfile = "3.2.0"
# Video Duplactes
vid_dup_finder_lib = { git = "https://github.com/qarmin/vid_dup_finder_lib"}
ffmpeg_cmdline_utils = "0.1.0"
[features]
default = []

@ -346,7 +346,7 @@ impl DebugPrint for BigFile {
println!("Excluded items - {:?}", self.excluded_items.items);
println!("Included directories - {:?}", self.directories.included_directories);
println!("Excluded directories - {:?}", self.directories.excluded_directories);
println!("Recursive search - {}", self.recursive_search.to_string());
println!("Recursive search - {}", self.recursive_search);
println!("Number of files to check - {:?}", self.number_of_files_to_check);
println!("-----------------------------------------");
}

@ -517,7 +517,7 @@ impl DebugPrint for BrokenFiles {
println!("Excluded items - {:?}", self.excluded_items.items);
println!("Included directories - {:?}", self.directories.included_directories);
println!("Excluded directories - {:?}", self.directories.excluded_directories);
println!("Recursive search - {}", self.recursive_search.to_string());
println!("Recursive search - {}", self.recursive_search);
println!("Delete Method - {:?}", self.delete_method);
println!("-----------------------------------------");
}

@ -1073,7 +1073,7 @@ impl DebugPrint for DuplicateFinder {
println!("Excluded items - {:?}", self.excluded_items.items);
println!("Included directories - {:?}", self.directories.included_directories);
println!("Excluded directories - {:?}", self.directories.excluded_directories);
println!("Recursive search - {}", self.recursive_search.to_string());
println!("Recursive search - {}", self.recursive_search);
println!("Minimum file size - {:?}", self.minimal_file_size);
println!("Checking Method - {:?}", self.check_method);
println!("Delete Method - {:?}", self.delete_method);

@ -320,7 +320,7 @@ impl DebugPrint for EmptyFiles {
println!("Excluded items - {:?}", self.excluded_items.items);
println!("Included directories - {:?}", self.directories.included_directories);
println!("Excluded directories - {:?}", self.directories.excluded_directories);
println!("Recursive search - {}", self.recursive_search.to_string());
println!("Recursive search - {}", self.recursive_search);
println!("Delete Method - {:?}", self.delete_method);
println!("-----------------------------------------");
}

@ -359,7 +359,6 @@ impl SaveResults for EmptyFolder {
}
}
impl PrintResults for EmptyFolder {
/// Prints basic info about empty folders // TODO print better
fn print_results(&self) {
if !self.empty_folder_list.is_empty() {
println!("Found {} empty folders", self.empty_folder_list.len());

@ -367,7 +367,7 @@ impl DebugPrint for InvalidSymlinks {
println!("Excluded items - {:?}", self.excluded_items.items);
println!("Included directories - {:?}", self.directories.included_directories);
println!("Excluded directories - {:?}", self.directories.excluded_directories);
println!("Recursive search - {}", self.recursive_search.to_string());
println!("Recursive search - {}", self.recursive_search);
println!("Delete Method - {:?}", self.delete_method);
println!("-----------------------------------------");
}

@ -9,6 +9,7 @@ pub mod empty_folder;
pub mod invalid_symlinks;
pub mod same_music;
pub mod similar_images;
pub mod similar_videos;
pub mod temporary;
pub mod zeroed;

@ -669,7 +669,7 @@ impl DebugPrint for SameMusic {
println!("Found duplicated files music - {}", self.duplicated_music_entries.len());
println!("Included directories - {:?}", self.directories.included_directories);
println!("Excluded directories - {:?}", self.directories.excluded_directories);
println!("Recursive search - {}", self.recursive_search.to_string());
println!("Recursive search - {}", self.recursive_search);
println!("Delete Method - {:?}", self.delete_method);
println!("-----------------------------------------");
}

@ -696,7 +696,6 @@ impl SaveResults for SimilarImages {
}
}
impl PrintResults for SimilarImages {
/// Prints basic info about empty folders // TODO print better
fn print_results(&self) {
if !self.similar_vectors.is_empty() {
println!("Found {} images which have similar friends", self.similar_vectors.len());

@ -0,0 +1,720 @@
use crate::common::Common;
use crate::common_directory::Directories;
use crate::common_extensions::Extensions;
use crate::common_items::ExcludedItems;
use crate::common_messages::Messages;
use crate::common_traits::{DebugPrint, PrintResults, SaveResults};
use crossbeam_channel::Receiver;
use directories_next::ProjectDirs;
use ffmpeg_cmdline_utils::FfmpegErrorKind::FfmpegNotFound;
use humansize::{file_size_opts as options, FileSize};
use rayon::prelude::*;
use std::collections::{BTreeMap, HashMap};
use std::fs::OpenOptions;
use std::fs::{File, Metadata};
use std::io::Write;
use std::io::*;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread::sleep;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{fs, mem, thread};
use vid_dup_finder_lib::HashCreationErrorKind::DetermineVideo;
use vid_dup_finder_lib::{NormalizedTolerance, VideoHash};
pub const MAX_TOLERANCE: i32 = 20;
#[derive(Debug)]
pub struct ProgressData {
pub current_stage: u8,
pub max_stage: u8,
pub videos_checked: usize,
pub videos_to_check: usize,
}
#[derive(Clone, Debug)]
pub struct FileEntry {
pub path: PathBuf,
pub size: u64,
pub modified_date: u64,
pub vhash: VideoHash,
}
/// Distance metric to use with the BK-tree.
struct Hamming;
impl bk_tree::Metric<Vec<u8>> for Hamming {
fn distance(&self, a: &Vec<u8>, b: &Vec<u8>) -> u32 {
hamming::distance_fast(a, b).unwrap() as u32
}
fn threshold_distance(&self, a: &Vec<u8>, b: &Vec<u8>, _threshold: u32) -> Option<u32> {
Some(self.distance(a, b))
}
}
/// Struct to store most basics info about all folder
pub struct SimilarVideos {
information: Info,
text_messages: Messages,
directories: Directories,
excluded_items: ExcludedItems,
allowed_extensions: Extensions,
similar_vectors: Vec<Vec<FileEntry>>,
recursive_search: bool,
minimal_file_size: u64,
maximal_file_size: u64,
videos_hashes: BTreeMap<Vec<u8>, Vec<FileEntry>>,
stopped_search: bool,
videos_to_check: BTreeMap<String, FileEntry>,
use_cache: bool,
tolerance: i32,
}
/// Info struck with helpful information's about results
#[derive(Default)]
pub struct Info {
pub number_of_removed_files: usize,
pub number_of_failed_to_remove_files: usize,
pub gained_space: u64,
}
impl Info {
pub fn new() -> Self {
Default::default()
}
}
/// Method implementation for EmptyFolder
impl SimilarVideos {
/// New function providing basics values
pub fn new() -> Self {
Self {
information: Default::default(),
text_messages: Messages::new(),
directories: Directories::new(),
excluded_items: Default::default(),
allowed_extensions: Extensions::new(),
similar_vectors: vec![],
recursive_search: true,
minimal_file_size: 1024 * 16,
maximal_file_size: u64::MAX,
videos_hashes: Default::default(),
stopped_search: false,
videos_to_check: Default::default(),
use_cache: true,
tolerance: 10,
}
}
pub fn set_tolerance(&mut self, tolerance: i32) {
assert!((0..=MAX_TOLERANCE).contains(&tolerance));
self.tolerance = tolerance
}
pub fn get_stopped_search(&self) -> bool {
self.stopped_search
}
pub const fn get_text_messages(&self) -> &Messages {
&self.text_messages
}
pub fn set_allowed_extensions(&mut self, allowed_extensions: String) {
self.allowed_extensions.set_allowed_extensions(allowed_extensions, &mut self.text_messages);
}
pub const fn get_similar_videos(&self) -> &Vec<Vec<FileEntry>> {
&self.similar_vectors
}
pub const fn get_information(&self) -> &Info {
&self.information
}
pub fn set_use_cache(&mut self, use_cache: bool) {
self.use_cache = use_cache;
}
pub fn set_recursive_search(&mut self, recursive_search: bool) {
self.recursive_search = recursive_search;
}
pub fn set_minimal_file_size(&mut self, minimal_file_size: u64) {
self.minimal_file_size = match minimal_file_size {
0 => 1,
t => t,
};
}
pub fn set_maximal_file_size(&mut self, maximal_file_size: u64) {
self.maximal_file_size = match maximal_file_size {
0 => 1,
t => t,
};
}
/// Public function used by CLI to search for empty folders
pub fn find_similar_videos(&mut self, stop_receiver: Option<&Receiver<()>>, progress_sender: Option<&futures::channel::mpsc::UnboundedSender<ProgressData>>) {
if !check_if_ffmpeg_is_installed() {
self.text_messages.errors.push("Cannot find proper installation of FFmpeg.".to_string());
} else {
self.directories.optimize_directories(true, &mut self.text_messages);
if !self.check_for_similar_videos(stop_receiver, progress_sender) {
self.stopped_search = true;
return;
}
if !self.sort_videos(stop_receiver, progress_sender) {
self.stopped_search = true;
return;
}
// if self.delete_folders {
// self.delete_empty_folders();
// }
}
self.debug_print();
}
// pub fn set_delete_folder(&mut self, delete_folder: bool) {
// self.delete_folders = delete_folder;
// }
/// Function to check if folder are empty.
/// Parameter initial_checking for second check before deleting to be sure that checked folder is still empty
fn check_for_similar_videos(&mut self, stop_receiver: Option<&Receiver<()>>, progress_sender: Option<&futures::channel::mpsc::UnboundedSender<ProgressData>>) -> bool {
let start_time: SystemTime = SystemTime::now();
let mut folders_to_check: Vec<PathBuf> = Vec::with_capacity(1024 * 2); // This should be small enough too not see to big difference and big enough to store most of paths without needing to resize vector
// Add root folders for finding
for id in &self.directories.included_directories {
folders_to_check.push(id.clone());
}
//// PROGRESS THREAD START
const LOOP_DURATION: u32 = 200; //in ms
let progress_thread_run = Arc::new(AtomicBool::new(true));
let atomic_file_counter = Arc::new(AtomicUsize::new(0));
let progress_thread_handle;
if let Some(progress_sender) = progress_sender {
let progress_send = progress_sender.clone();
let progress_thread_run = progress_thread_run.clone();
let atomic_file_counter = atomic_file_counter.clone();
progress_thread_handle = thread::spawn(move || loop {
progress_send
.unbounded_send(ProgressData {
current_stage: 0,
max_stage: 1,
videos_checked: atomic_file_counter.load(Ordering::Relaxed) as usize,
videos_to_check: 0,
})
.unwrap();
if !progress_thread_run.load(Ordering::Relaxed) {
break;
}
sleep(Duration::from_millis(LOOP_DURATION as u64));
});
} else {
progress_thread_handle = thread::spawn(|| {});
}
//// PROGRESS THREAD END
while !folders_to_check.is_empty() {
if stop_receiver.is_some() && stop_receiver.unwrap().try_recv().is_ok() {
// End thread which send info to gui
progress_thread_run.store(false, Ordering::Relaxed);
progress_thread_handle.join().unwrap();
return false;
}
let current_folder = folders_to_check.pop().unwrap();
// Read current dir, if permission are denied just go to next
let read_dir = match fs::read_dir(&current_folder) {
Ok(t) => t,
Err(e) => {
self.text_messages.warnings.push(format!("Cannot open dir {}, reason {}", current_folder.display(), e));
continue;
} // Permissions denied
};
// Check every sub folder/file/link etc.
'dir: for entry in read_dir {
let entry_data = match entry {
Ok(t) => t,
Err(e) => {
self.text_messages.warnings.push(format!("Cannot read entry in dir {}, reason {}", current_folder.display(), e));
continue;
} //Permissions denied
};
let metadata: Metadata = match entry_data.metadata() {
Ok(t) => t,
Err(e) => {
self.text_messages.warnings.push(format!("Cannot read metadata in dir {}, reason {}", current_folder.display(), e));
continue;
} //Permissions denied
};
if metadata.is_dir() {
if !self.recursive_search {
continue;
}
let next_folder = current_folder.join(entry_data.file_name());
if self.directories.is_excluded(&next_folder) {
continue 'dir;
}
if self.excluded_items.is_excluded(&next_folder) {
continue 'dir;
}
folders_to_check.push(next_folder);
} else if metadata.is_file() {
atomic_file_counter.fetch_add(1, Ordering::Relaxed);
let file_name_lowercase: String = match entry_data.file_name().into_string() {
Ok(t) => t,
Err(_inspected) => {
println!("File {:?} has not valid UTF-8 name", entry_data);
continue 'dir;
}
}
.to_lowercase();
if !self.allowed_extensions.file_extensions.is_empty() {
let allowed = self.allowed_extensions.file_extensions.iter().any(|e| file_name_lowercase.ends_with((".".to_string() + e.to_lowercase().as_str()).as_str()));
if !allowed {
// Not an allowed extension, ignore it.
continue 'dir;
}
}
// Checking allowed video extensions
let allowed_video_extensions = [".mp4", ".mpv", ".flv", ".mp4a", ".webm", ".mpg", ".mp2", ".mpeg", ".m4p", ".m4v", ".avi", ".wmv", ".qt", ".mov", ".swf", ".mkv"];
if !allowed_video_extensions.iter().any(|e| file_name_lowercase.ends_with(e)) {
continue 'dir;
}
// Checking files
if (self.minimal_file_size..=self.maximal_file_size).contains(&metadata.len()) {
let current_file_name = current_folder.join(entry_data.file_name());
if self.excluded_items.is_excluded(&current_file_name) {
continue 'dir;
}
let fe: FileEntry = FileEntry {
path: current_file_name.clone(),
size: metadata.len(),
modified_date: match metadata.modified() {
Ok(t) => match t.duration_since(UNIX_EPOCH) {
Ok(d) => d.as_secs(),
Err(_inspected) => {
self.text_messages.warnings.push(format!("File {} seems to be modified before Unix Epoch.", current_file_name.display()));
0
}
},
Err(e) => {
self.text_messages.warnings.push(format!("Unable to get modification date from file {}, reason {}", current_file_name.display(), e));
0
} // Permissions Denied
},
vhash: Default::default(),
};
self.videos_to_check.insert(current_file_name.to_string_lossy().to_string(), fe);
}
}
}
}
// End thread which send info to gui
progress_thread_run.store(false, Ordering::Relaxed);
progress_thread_handle.join().unwrap();
Common::print_time(start_time, SystemTime::now(), "check_for_similar_videos".to_string());
true
}
fn sort_videos(&mut self, stop_receiver: Option<&Receiver<()>>, progress_sender: Option<&futures::channel::mpsc::UnboundedSender<ProgressData>>) -> bool {
let hash_map_modification = SystemTime::now();
let loaded_hash_map;
let mut records_already_cached: BTreeMap<String, FileEntry> = Default::default();
let mut non_cached_files_to_check: BTreeMap<String, FileEntry> = Default::default();
if self.use_cache {
loaded_hash_map = match load_hashes_from_file(&mut self.text_messages) {
Some(t) => t,
None => Default::default(),
};
for (name, file_entry) in &self.videos_to_check {
#[allow(clippy::if_same_then_else)]
if !loaded_hash_map.contains_key(name) {
// If loaded data doesn't contains current videos info
non_cached_files_to_check.insert(name.clone(), file_entry.clone());
} else if file_entry.size != loaded_hash_map.get(name).unwrap().size || file_entry.modified_date != loaded_hash_map.get(name).unwrap().modified_date {
// When size or modification date of video changed, then it is clear that is different video
non_cached_files_to_check.insert(name.clone(), file_entry.clone());
} else {
// Checking may be omitted when already there is entry with same size and modification date
records_already_cached.insert(name.clone(), loaded_hash_map.get(name).unwrap().clone());
}
}
} else {
loaded_hash_map = Default::default();
mem::swap(&mut self.videos_to_check, &mut non_cached_files_to_check);
}
Common::print_time(hash_map_modification, SystemTime::now(), "sort_videos - reading data from cache and preparing them".to_string());
let hash_map_modification = SystemTime::now();
//// PROGRESS THREAD START
const LOOP_DURATION: u32 = 200; //in ms
let progress_thread_run = Arc::new(AtomicBool::new(true));
let atomic_file_counter = Arc::new(AtomicUsize::new(0));
let progress_thread_handle;
if let Some(progress_sender) = progress_sender {
let progress_send = progress_sender.clone();
let progress_thread_run = progress_thread_run.clone();
let atomic_file_counter = atomic_file_counter.clone();
let videos_to_check = non_cached_files_to_check.len();
progress_thread_handle = thread::spawn(move || loop {
progress_send
.unbounded_send(ProgressData {
current_stage: 1,
max_stage: 1,
videos_checked: atomic_file_counter.load(Ordering::Relaxed) as usize,
videos_to_check,
})
.unwrap();
if !progress_thread_run.load(Ordering::Relaxed) {
break;
}
sleep(Duration::from_millis(LOOP_DURATION as u64));
});
} else {
progress_thread_handle = thread::spawn(|| {});
}
//// PROGRESS THREAD END
let old_vec_file_entry: Vec<std::result::Result<FileEntry, String>> = non_cached_files_to_check
.par_iter()
.map(|file_entry| {
atomic_file_counter.fetch_add(1, Ordering::Relaxed);
if stop_receiver.is_some() && stop_receiver.unwrap().try_recv().is_ok() {
// This will not break
return None;
}
let mut file_entry = file_entry.1.clone();
let vhash = match VideoHash::from_path(&file_entry.path) {
Ok(t) => t,
Err(e) => return Some(Err(format!("Failed to hash file, {}", e))),
};
file_entry.vhash = vhash;
Some(Ok(file_entry))
})
.while_some()
.collect::<Vec<std::result::Result<FileEntry, String>>>();
// End thread which send info to gui
progress_thread_run.store(false, Ordering::Relaxed);
progress_thread_handle.join().unwrap();
let mut vec_file_entry = Vec::new();
for result in old_vec_file_entry {
match result {
Ok(t) => vec_file_entry.push(t),
Err(e) => {
self.text_messages.errors.push(e);
}
}
}
Common::print_time(hash_map_modification, SystemTime::now(), "sort_videos - reading data from files in parallel".to_string());
let hash_map_modification = SystemTime::now();
// Just connect loaded results with already calculated hashes
for (_name, file_entry) in records_already_cached {
vec_file_entry.push(file_entry.clone());
}
let mut hashmap_with_file_entries: HashMap<String, FileEntry> = Default::default();
let mut vector_of_hashes: Vec<VideoHash> = Vec::new();
for i in &vec_file_entry {
hashmap_with_file_entries.insert(i.vhash.src_path().to_string_lossy().to_string(), i.clone());
vector_of_hashes.push(i.vhash.clone());
}
if self.use_cache {
// Must save all results to file, old loaded from file with all currently counted results
let mut all_results: BTreeMap<String, FileEntry> = loaded_hash_map;
for file_entry in vec_file_entry {
all_results.insert(file_entry.path.to_string_lossy().to_string(), file_entry);
}
save_hashes_to_file(&all_results, &mut self.text_messages);
}
Common::print_time(hash_map_modification, SystemTime::now(), "sort_videos - saving data to files".to_string());
let hash_map_modification = SystemTime::now();
let match_group = vid_dup_finder_lib::search(vector_of_hashes, NormalizedTolerance::new(self.tolerance as f64 / 100.0f64));
let mut collected_similar_videos: Vec<Vec<FileEntry>> = Default::default();
for i in match_group {
let mut temp_vector: Vec<FileEntry> = Vec::new();
for j in i.duplicates() {
temp_vector.push(hashmap_with_file_entries.get(&j.to_string_lossy().to_string()).unwrap().clone());
}
assert!(temp_vector.len() > 1);
collected_similar_videos.push(temp_vector);
}
self.similar_vectors = collected_similar_videos;
Common::print_time(hash_map_modification, SystemTime::now(), "sort_videos - selecting data from BtreeMap".to_string());
// Clean unused data
self.videos_hashes = Default::default();
self.videos_to_check = Default::default();
true
}
/// Set included dir which needs to be relative, exists etc.
pub fn set_included_directory(&mut self, included_directory: Vec<PathBuf>) {
self.directories.set_included_directory(included_directory, &mut self.text_messages);
}
pub fn set_excluded_directory(&mut self, excluded_directory: Vec<PathBuf>) {
self.directories.set_excluded_directory(excluded_directory, &mut self.text_messages);
}
pub fn set_excluded_items(&mut self, excluded_items: Vec<String>) {
self.excluded_items.set_excluded_items(excluded_items, &mut self.text_messages);
}
}
impl Default for SimilarVideos {
fn default() -> Self {
Self::new()
}
}
impl DebugPrint for SimilarVideos {
#[allow(dead_code)]
#[allow(unreachable_code)]
fn debug_print(&self) {
#[cfg(not(debug_assertions))]
{
return;
}
println!("---------------DEBUG PRINT---------------");
println!("Included directories - {:?}", self.directories.included_directories);
println!("-----------------------------------------");
}
}
impl SaveResults for SimilarVideos {
fn save_results_to_file(&mut self, file_name: &str) -> bool {
let start_time: SystemTime = SystemTime::now();
let file_name: String = match file_name {
"" => "results.txt".to_string(),
k => k.to_string(),
};
let file_handler = match File::create(&file_name) {
Ok(t) => t,
Err(e) => {
self.text_messages.errors.push(format!("Failed to create file {}, reason {}", file_name, e));
return false;
}
};
let mut writer = BufWriter::new(file_handler);
if let Err(e) = writeln!(
writer,
"Results of searching {:?} with excluded directories {:?} and excluded items {:?}",
self.directories.included_directories, self.directories.excluded_directories, self.excluded_items.items
) {
self.text_messages.errors.push(format!("Failed to save results to file {}, reason {}", file_name, e));
return false;
}
if !self.similar_vectors.is_empty() {
write!(writer, "{} videos which have similar friends\n\n", self.similar_vectors.len()).unwrap();
for struct_similar in self.similar_vectors.iter() {
writeln!(writer, "Found {} videos which have similar friends", self.similar_vectors.len()).unwrap();
for file_entry in struct_similar {
writeln!(writer, "{} - {}", file_entry.path.display(), file_entry.size.file_size(options::BINARY).unwrap(),).unwrap();
}
writeln!(writer).unwrap();
}
} else {
write!(writer, "Not found any similar videos.").unwrap();
}
Common::print_time(start_time, SystemTime::now(), "save_results_to_file".to_string());
true
}
}
impl PrintResults for SimilarVideos {
fn print_results(&self) {
if !self.similar_vectors.is_empty() {
println!("Found {} videos which have similar friends", self.similar_vectors.len());
for vec_file_entry in &self.similar_vectors {
for file_entry in vec_file_entry {
println!("{} - {}", file_entry.path.display(), file_entry.size.file_size(options::BINARY).unwrap());
}
println!();
}
}
}
}
fn save_hashes_to_file(hashmap: &BTreeMap<String, FileEntry>, text_messages: &mut Messages) {
if let Some(proj_dirs) = ProjectDirs::from("pl", "Qarmin", "Czkawka") {
// Lin: /home/username/.cache/czkawka
// Win: C:\Users\Username\AppData\Local\Qarmin\Czkawka\cache
// Mac: /Users/Username/Library/Caches/pl.Qarmin.Czkawka
// Saves data
// path//file_size//modified_date//num_frames//duration//hash1//hash2 etc.
// number of hashes is equal to HASH_QWORDS(19 at this moment)
let cache_dir = PathBuf::from(proj_dirs.cache_dir());
if cache_dir.exists() {
if !cache_dir.is_dir() {
text_messages.messages.push(format!("Config dir {} is a file!", cache_dir.display()));
return;
}
} else if let Err(e) = fs::create_dir_all(&cache_dir) {
text_messages.messages.push(format!("Cannot create config dir {}, reason {}", cache_dir.display(), e));
return;
}
let cache_file = cache_dir.join("cache_similar_videos.txt");
let file_handler = match OpenOptions::new().truncate(true).write(true).create(true).open(&cache_file) {
Ok(t) => t,
Err(e) => {
text_messages.messages.push(format!("Cannot create or open cache file {}, reason {}", cache_file.display(), e));
return;
}
};
let mut writer = BufWriter::new(file_handler);
for file_entry in hashmap.values() {
let mut string: String = String::with_capacity(256);
string += format!("{}//{}//{}//{}//{}", file_entry.path.display(), file_entry.size, file_entry.modified_date, file_entry.vhash.num_frames(), file_entry.vhash.duration()).as_str();
for i in file_entry.vhash.hash() {
string.push_str("//");
string.push_str(i.to_string().as_str());
}
if let Err(e) = writeln!(writer, "{}", string) {
text_messages.messages.push(format!("Failed to save some data to cache file {}, reason {}", cache_file.display(), e));
return;
};
}
}
}
fn load_hashes_from_file(text_messages: &mut Messages) -> Option<BTreeMap<String, FileEntry>> {
if let Some(proj_dirs) = ProjectDirs::from("pl", "Qarmin", "Czkawka") {
let cache_dir = PathBuf::from(proj_dirs.cache_dir());
let cache_file = cache_dir.join("cache_similar_videos.txt");
let file_handler = match OpenOptions::new().read(true).open(&cache_file) {
Ok(t) => t,
Err(_inspected) => {
// text_messages.messages.push(format!("Cannot find or open cache file {}", cache_file.display())); // This shouldn't be write to output
return None;
}
};
let reader = BufReader::new(file_handler);
let mut hashmap_loaded_entries: BTreeMap<String, FileEntry> = Default::default();
// Read the file line by line using the lines() iterator from std::io::BufRead.
for (index, line) in reader.lines().enumerate() {
let line = match line {
Ok(t) => t,
Err(e) => {
text_messages.warnings.push(format!("Failed to load line number {} from cache file {}, reason {}", index + 1, cache_file.display(), e));
return None;
}
};
let uuu = line.split("//").collect::<Vec<&str>>();
let hash_size = 19;
// Hash size + other things
if uuu.len() != (hash_size + 5) {
text_messages.warnings.push(format!(
"Found invalid data in line {} - ({}) in cache file {}, expected {} values, found {}",
index + 1,
line,
cache_file.display(),
hash_size + 5,
uuu.len(),
));
continue;
};
// Don't load cache data if destination file not exists
if Path::new(uuu[0]).exists() {
let mut hash: [u64; 19] = [0; 19];
for i in 0..hash_size {
hash[i] = match uuu[5 + i as usize].parse::<u64>() {
Ok(t) => t,
Err(e) => {
text_messages
.warnings
.push(format!("Found invalid hash value in line {} - ({}) in cache file {}, reason {}", index + 1, line, cache_file.display(), e));
continue;
}
};
}
hashmap_loaded_entries.insert(
uuu[0].to_string(),
FileEntry {
path: PathBuf::from(uuu[0]),
size: match uuu[1].parse::<u64>() {
Ok(t) => t,
Err(e) => {
text_messages
.warnings
.push(format!("Found invalid size value in line {} - ({}) in cache file {}, reason {}", index + 1, line, cache_file.display(), e));
continue;
}
},
modified_date: match uuu[2].parse::<u64>() {
Ok(t) => t,
Err(e) => {
text_messages
.warnings
.push(format!("Found invalid modified date value in line {} - ({}) in cache file {}, reason {}", index + 1, line, cache_file.display(), e));
continue;
}
},
vhash: VideoHash::with_start_data(uuu[4].parse::<u32>().unwrap_or(0), uuu[0], hash, uuu[3].parse::<u32>().unwrap_or(10)),
},
);
}
}
return Some(hashmap_loaded_entries);
}
text_messages.messages.push("Cannot find or open system config dir to save cache file".to_string());
None
}
pub fn check_if_ffmpeg_is_installed() -> bool {
let vid = "999999999999999999.txt";
if let Err(DetermineVideo { src_path: _a, error: FfmpegNotFound }) = VideoHash::from_path(&vid) {
return false;
}
true
}

@ -305,7 +305,7 @@ impl DebugPrint for Temporary {
println!("Excluded items - {:?}", self.excluded_items.items);
println!("Included directories - {:?}", self.directories.included_directories);
println!("Excluded directories - {:?}", self.directories.excluded_directories);
println!("Recursive search - {}", self.recursive_search.to_string());
println!("Recursive search - {}", self.recursive_search);
println!("Delete Method - {:?}", self.delete_method);
println!("-----------------------------------------");
}

@ -454,7 +454,7 @@ impl DebugPrint for ZeroedFiles {
println!("Excluded items - {:?}", self.excluded_items.items);
println!("Included directories - {:?}", self.directories.included_directories);
println!("Excluded directories - {:?}", self.directories.excluded_directories);
println!("Recursive search - {}", self.recursive_search.to_string());
println!("Recursive search - {}", self.recursive_search);
println!("Delete Method - {:?}", self.delete_method);
println!("Minimal File Size - {:?}", self.minimal_file_size);
println!("-----------------------------------------");

@ -20,6 +20,7 @@ pub fn connect_button_delete(gui_data: &GuiData) {
let tree_view_empty_files_finder = gui_data.main_notebook.tree_view_empty_files_finder.clone();
let tree_view_temporary_files_finder = gui_data.main_notebook.tree_view_temporary_files_finder.clone();
let tree_view_similar_images_finder = gui_data.main_notebook.tree_view_similar_images_finder.clone();
let tree_view_similar_videos_finder = gui_data.main_notebook.tree_view_similar_videos_finder.clone();
let tree_view_zeroed_files_finder = gui_data.main_notebook.tree_view_zeroed_files_finder.clone();
let tree_view_same_music_finder = gui_data.main_notebook.tree_view_same_music_finder.clone();
let tree_view_invalid_symlinks = gui_data.main_notebook.tree_view_invalid_symlinks.clone();
@ -105,6 +106,26 @@ pub fn connect_button_delete(gui_data: &GuiData) {
image_preview_similar_images.hide();
}
}
NotebookMainEnum::SimilarVideos => {
if !check_button_settings_confirm_group_deletion.is_active()
|| !check_if_deleting_all_files_in_group(
&tree_view_similar_videos_finder.clone(),
ColumnsSimilarVideos::Color as i32,
ColumnsSimilarVideos::ActiveSelectButton as i32,
&window_main,
&check_button_settings_confirm_group_deletion,
)
{
tree_remove(
&tree_view_similar_videos_finder.clone(),
ColumnsSimilarVideos::Name as i32,
ColumnsSimilarVideos::Path as i32,
ColumnsSimilarVideos::Color as i32,
ColumnsSimilarVideos::ActiveSelectButton as i32,
&gui_data,
);
}
}
NotebookMainEnum::Zeroed => {
basic_remove(
&tree_view_zeroed_files_finder.clone(),

@ -15,6 +15,7 @@ pub fn connect_button_hardlink(gui_data: &GuiData) {
let tree_view_duplicate_finder = gui_data.main_notebook.tree_view_duplicate_finder.clone();
let tree_view_similar_images_finder = gui_data.main_notebook.tree_view_similar_images_finder.clone();
let tree_view_similar_videos_finder = gui_data.main_notebook.tree_view_similar_videos_finder.clone();
let tree_view_same_music_finder = gui_data.main_notebook.tree_view_same_music_finder.clone();
let image_preview_similar_images = gui_data.main_notebook.image_preview_similar_images.clone();
@ -54,6 +55,17 @@ pub fn connect_button_hardlink(gui_data: &GuiData) {
);
image_preview_similar_images.hide();
}
NotebookMainEnum::SimilarVideos => {
hardlink_symlink(
tree_view_similar_videos_finder.clone(),
ColumnsSimilarVideos::Name as i32,
ColumnsSimilarVideos::Path as i32,
ColumnsSimilarVideos::Color as i32,
ColumnsSimilarVideos::ActiveSelectButton as i32,
true,
&gui_data,
);
}
e => panic!("Not existent {:?}", e),