forked from AddictedCS/soundfingerprinting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DuplicatesDetectorFacade.cs
257 lines (227 loc) · 9.94 KB
/
DuplicatesDetectorFacade.cs
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
namespace SoundFingerprinting.DuplicatesDetector
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SoundFingerprinting.Data;
using SoundFingerprinting.DuplicatesDetector.Infrastructure;
using SoundFingerprinting.DuplicatesDetector.Model;
using SoundFingerprinting.DuplicatesDetector.ViewModel;
/// <summary>
/// Facade which prepares the data for analysis of the tracks (does all the "dirty job")
/// </summary>
public class DuplicatesDetectorFacade : IDisposable
{
/// <summary>
/// Maximum track length (track's bigger than this value will be discarded)
/// </summary>
private const int MaxTrackLength = 60 * 10; /*10 min - maximal track length*/
/// <summary>
/// Number of seconds to process from each song
/// </summary>
private const int SecondsToProcess = 10;
/// <summary>
/// Starting processing point
/// </summary>
private const int StartProcessingAtSecond = 20;
/// <summary>
/// Buffer size of the application reading songs
/// </summary>
/// <remarks>
/// Represented in MB.
/// Max 100MB will be reserved for the samples read from songs
/// </remarks>
private const int BufferSize = 100;
/// <summary>
/// Minimum track length (track's less than this value will be discarded)
/// </summary>
private const int MinTrackLength = SecondsToProcess + StartProcessingAtSecond + 1;
/// <summary>
/// Down sampling rate
/// </summary>
/// <remarks>
/// If you want to change this, contact ciumac.sergiu@gmail.com
/// </remarks>
private const int SampleRate = 5512;
private readonly DuplicatesDetectorService duplicatesDetectorService;
private readonly TrackHelper trackHelper;
private CancellationTokenSource cts;
public DuplicatesDetectorFacade(DuplicatesDetectorService duplicatesDetectorService, TrackHelper trackHelper)
{
cts = new CancellationTokenSource();
this.duplicatesDetectorService = duplicatesDetectorService;
this.trackHelper = trackHelper;
}
~DuplicatesDetectorFacade()
{
Dispose(false);
}
/// <summary>
/// Process the tracks asynchronously (get their path location, fingerprint content, hash fingerprint into storage)
/// </summary>
/// <param name = "paths">Paths to be processed</param>
/// <param name = "fileFilters">File filters used</param>
/// <param name = "callback">Callback invoked once processing ends</param>
/// <param name = "trackProcessed">Callback invoked once 1 track is processed</param>
public void ProcessTracksAsync(
IEnumerable<Item> paths,
string[] fileFilters,
Action<List<TrackData>, Exception> callback,
Action<TrackData> trackProcessed)
{
var files = new List<string>();
foreach (var path in paths)
{
if (path.IsFolder)
{
files.AddRange(Helper.GetMusicFiles(path.Path, fileFilters)); // get music file names
}
else
{
files.Add(path.Path);
}
}
Task.Factory.StartNew(
() =>
{
try
{
var tracks = ProcessFiles(files, trackProcessed);
callback.Invoke(tracks, null);
}
catch (AggregateException) /*here we are sure all consumers are done processing*/
{
callback.Invoke(null, null);
duplicatesDetectorService.ClearStorage(); /*its safe to clear the storage, no more thread is executing*/
}
catch (Exception ex)
{
callback.Invoke(null, ex);
}
},
cts.Token);
}
/// <summary>
/// Find all duplicate files from the storage
/// </summary>
/// <param name = "callback">Callback invoked at each processed track</param>
/// <returns>Set of tracks that are duplicate</returns>
public HashSet<TrackData>[] FindAllDuplicates(Action<TrackData, int, int> callback)
{
return duplicatesDetectorService.FindDuplicates(callback);
}
/// <summary>
/// Abort processing the files (at any stage)
/// </summary>
public void AbortProcessing()
{
cts.Cancel();
cts = new CancellationTokenSource();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isDisposing)
{
if (isDisposing)
{
cts.Dispose();
}
}
/// <summary>
/// Process files (get fingerprint signatures, hash them into storage)
/// </summary>
/// <param name = "files">List of files to be hashed</param>
/// <param name = "processed">Callback invoked once 1 track is processed</param>
/// <returns>List of processed tracks</returns>
private List<TrackData> ProcessFiles(IEnumerable<string> files, Action<TrackData> processed)
{
/*preprocessing stage ended, now make sure to do the actual job*/
int numProcs = Environment.ProcessorCount;
// 1024 (Kb) * BufferSize / SampleRate * SecondsRead * 4 (1 float = 4 bytes) / 1024 (Kb)
const int Buffersize =
(int)((1024.0 * BufferSize) / ((double)SampleRate * SecondsToProcess / 1000 * 4 / 1024));
// ~317 songs are allowed for 15 seconds snippet at 5512 Hz sample rate
var buffer = new BlockingCollection<Tuple<TrackData, float[]>>(Buffersize);
var processedtracks = new List<TrackData>();
var consumers = new List<Task>();
var producers = new List<Task>();
CancellationToken token = cts.Token;
var bag = new ConcurrentBag<string>(files);
int maxprod = numProcs > 2 ? 2 : numProcs;
for (var i = 0; i < maxprod; i++)
{
/*producers*/
producers.Add(Task.Factory.StartNew(
() =>
{
while (!bag.IsEmpty)
{
if (token.IsCancellationRequested)
{
return;
}
string file;
if (!bag.TryTake(out file))
{
return;
}
TrackData track;
float[] samples;
try
{
track = trackHelper.GetTrack(MinTrackLength, MaxTrackLength, file); // lame casting I know
samples = trackHelper.GetTrackSamples(track, SampleRate, SecondsToProcess, StartProcessingAtSecond);
}
catch
{
continue;
/*Continue processing even if getting samples failed*/
/*the failing might be caused by a bunch of File I/O factors, that cannot be considered critical*/
}
try
{
buffer.TryAdd(new Tuple<TrackData, float[]>(track, samples), 1, token); /*producer*/
}
catch (OperationCanceledException)
{
/*it is safe to break here, operation was canceled*/
break;
}
}
},
token));
}
/*When all producers ended with their operations, call the CompleteAdding() to tell Consumers no more items are available*/
Task.Factory.ContinueWhenAll(producers.ToArray(), p => buffer.CompleteAdding());
for (int i = 0; i < numProcs * 4; i++)
{
/*consumer*/
consumers.Add(Task.Factory.StartNew(
() =>
{
foreach (Tuple<TrackData, float[]> tuple in buffer.GetConsumingEnumerable()) /*If OCE is thrown it will be caught in the caller's AggregateException*/
{
if (tuple != null)
{
/*Long running procedure*/
duplicatesDetectorService.CreateInsertFingerprints(tuple.Item2, tuple.Item1);
processedtracks.Add(tuple.Item1);
if (processed != null)
{
processed.Invoke(tuple.Item1);
}
}
}
},
token));
}
Task.WaitAll(consumers.ToArray()); /*wait for all consumers to end*/
return processedtracks;
}
}
}