/
PeakFileService.cs
480 lines (418 loc) · 19 KB
/
PeakFileService.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
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
// Copyright © 2011-2013 Yanick Castonguay
//
// This file is part of MPfm.
//
// MPfm is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// MPfm is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with MPfm. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using MPfm.Core;
using MPfm.Sound.AudioFiles;
using MPfm.Sound.BassNetWrapper;
namespace MPfm.Sound.PeakFiles
{
/// <summary>
/// This class can generate peak files asynchronously. Use the ProcessData event to get the progress.
/// </summary>
public class PeakFileService : IPeakFileService
{
private Task _currentTask;
private CancellationTokenSource cancellationTokenSource = null;
private CancellationToken cancellationToken;
/// <summary>
/// Indicates if a peak file is generating.
/// </summary>
public bool IsLoading { get; private set; }
/// <summary>
/// Defines the current peak file version. Used when reading peak files to make sure
/// the format is compatible.
/// </summary>
private string version = "1.00";
/// <summary>
/// Delegate for the OnProcessStarted event.
/// </summary>
/// <param name="data">Event data</param>
public delegate void ProcessStarted(PeakFileStartedData data);
/// <summary>
/// Event called when a thread starts its work.
/// </summary>
public event ProcessStarted OnProcessStarted;
/// <summary>
/// Delegate for the OnProcessData event.
/// </summary>
/// <param name="data">Event data</param>
public delegate void ProcessData(PeakFileProgressData data);
/// <summary>
/// Event called every 20 blocks when generating a peak file.
/// </summary>
public event ProcessData OnProcessData;
/// <summary>
/// Delegate for the OnProcessDone event.
/// </summary>
/// <param name="data">Event data</param>
public delegate void ProcessDone(PeakFileDoneData data);
/// <summary>
/// Event called when all the GeneratePeakFiles threads have completed their work.
/// </summary>
public event ProcessDone OnProcessDone;
/// <summary>
/// Indicates if the class is currently generating peak files.
/// </summary>
public bool IsProcessing { get; private set; }
/// <summary>
/// Private value for the ProgressReportBlockInterval property.
/// </summary>
private int progressReportBlockInterval = 200;
/// <summary>
/// Defines when the OnProgressData event is called; it will be called
/// every x blocks (where x is ProgressReportBlockInterval).
/// The default value is 20.
/// </summary>
public int ProgressReportBlockInterval
{
get
{
return progressReportBlockInterval;
}
set
{
progressReportBlockInterval = value;
}
}
/// <summary>
/// Generates a peak file for an audio file.
/// Note: BASS should be initialized already before calling this method. This uses a decode stream.
/// </summary>
/// <param name="audioFilePath">Audio file path</param>
/// <param name="peakFilePath">Peak file path</param>
public void GeneratePeakFile(string audioFilePath, string peakFilePath)
{
// Declare variables
bool cancelled = false;
FileStream fileStream = null;
BinaryWriter binaryWriter = null;
GZipStream gzipStream = null;
int chunkSize = 0;
int currentBlock = 0;
long audioFileLength = 0;
int read = 0;
long bytesRead = 0;
float[] floatLeft = null;
float[] floatRight = null;
//byte[] buffer = null;
float[] buffer = null;
IntPtr data = new IntPtr(); // initialized properly later
WaveDataMinMax minMax = null;
List<WaveDataMinMax> listMinMaxForProgressData = new List<WaveDataMinMax>();
// Schedule operation in a new thread
IsLoading = true;
bool processSuccessful = false;
_currentTask = Task.Factory.StartNew(() =>
{
try
{
// Create a channel for decoding
Channel channelDecode = Channel.CreateFileStreamForDecoding(audioFilePath, true);
// Get audio file length
audioFileLength = channelDecode.GetLength();
// Divide it by two since we're using floating point
audioFileLength /= 2;
// Check if peak file exists
if (File.Exists(peakFilePath))
{
// Delete peak file
File.Delete(peakFilePath);
}
// Create streams and binary writer
fileStream = new FileStream(peakFilePath, FileMode.Create, FileAccess.Write);
binaryWriter = new BinaryWriter(fileStream);
gzipStream = new GZipStream(fileStream, CompressionMode.Compress);
// 4096 bytes for 16-bit PCM data
chunkSize = 4096;
// How many blocks will there be?
double blocks = Math.Ceiling(((double)audioFileLength / (double)chunkSize) * 2) + 1;
// Write file header (30 characters)
// 123456789012345678901234567890
// MPfm Peak File (version# 1.00)
string version = "MPfm Peak File (version# " + this.version + ")";
binaryWriter.Write(version);
// Write audio file length
binaryWriter.Write(audioFileLength);
// Write chunk size and number of blocks
binaryWriter.Write((Int32)chunkSize);
binaryWriter.Write((Int32)blocks);
// Create buffer
data = Marshal.AllocHGlobal(chunkSize);
buffer = new float[chunkSize];
// Is an event binded to OnProcessData?
if (OnProcessStarted != null)
{
// Report progress (started)
PeakFileStartedData dataStarted = new PeakFileStartedData(){
Length = audioFileLength,
TotalBlocks = (Int32)blocks
};
OnProcessStarted(dataStarted);
}
// Loop through file using chunk size
int dataBlockRead = 0;
do
{
// Check for cancel
//Console.WriteLine("PeakFileService - Bytes read: " + bytesRead.ToString());
if (cancellationToken.IsCancellationRequested)
{
// Set flags, exit loop
Console.WriteLine("PeakFileGenerator - Cancelling...");
cancelled = true;
IsLoading = false;
OnProcessDone(new PeakFileDoneData() {
AudioFilePath = audioFilePath,
Cancelled = true
});
break;
}
// Get data
read = channelDecode.GetData(buffer, chunkSize);
// Increment bytes read
bytesRead += read;
// Create arrays for left and right channel
floatLeft = new float[chunkSize / 2];
floatRight = new float[chunkSize / 2];
// Loop through sample data to split channels
for (int a = 0; a < chunkSize; a++)
{
// Check if left or right channel
if (a % 2 == 0)
{
// Left channel
floatLeft [a / 2] = buffer [a];
} else
{
// Left channel
floatRight [a / 2] = buffer [a];
}
}
// Calculate min/max and add it to the min/max list for event progress
minMax = AudioTools.GetMinMaxFromWaveData(floatLeft, floatRight, false);
listMinMaxForProgressData.Add(minMax);
// Write peak information
binaryWriter.Write((double)minMax.leftMin);
binaryWriter.Write((double)minMax.leftMax);
binaryWriter.Write((double)minMax.rightMin);
binaryWriter.Write((double)minMax.rightMax);
binaryWriter.Write((double)minMax.mixMin);
binaryWriter.Write((double)minMax.mixMax);
// Update progress every X blocks (m_progressReportBlockInterval) default = 20
dataBlockRead += read;
if (dataBlockRead >= read * progressReportBlockInterval)
{
// Reset flag
dataBlockRead = 0;
// Report progress
PeakFileProgressData dataProgress = new PeakFileProgressData();
dataProgress.AudioFilePath = audioFilePath;
dataProgress.PeakFilePath = peakFilePath;
dataProgress.PercentageDone = (((float)bytesRead / (float)audioFileLength) / 2) * 100;
dataProgress.Length = audioFileLength;
dataProgress.CurrentBlock = currentBlock;
dataProgress.TotalBlocks = (Int32)blocks;
dataProgress.MinMax = listMinMaxForProgressData;
OnProcessData(dataProgress);
// Reset min/max list
listMinMaxForProgressData = new List<WaveDataMinMax>();
}
// Increment current block
currentBlock++;
} while (read == chunkSize);
// Free channel
Console.WriteLine("PeakFileService - Freeing channel...");
channelDecode.Free();
// TODO: This should replace the IsCancelled status since cancelling the task doesn't go end well
Console.WriteLine("PeakFileService - Is process successful? bytesRead: " + bytesRead.ToString() + " audioFileLength: " + audioFileLength.ToString());
if(bytesRead >= audioFileLength)
processSuccessful = true;
// Set nulls for garbage collection
channelDecode = null;
floatLeft = null;
floatRight = null;
buffer = null;
minMax = null;
} catch (Exception ex)
{
// Return exception
//e.Result = ex;
Console.WriteLine("PeakFileService - Error: " + ex.Message);
throw ex;
} finally
{
// Close writer and stream
Console.WriteLine("PeakFileService - Closing file stream...");
gzipStream.Close();
binaryWriter.Close();
fileStream.Close();
// Set nulls
gzipStream = null;
binaryWriter = null;
fileStream = null;
// If the operation was cancelled, delete the files
if (cancelled)
{
// Check if file exists
if (File.Exists(peakFilePath))
{
try
{
// Delete file
File.Delete(peakFilePath);
} catch
{
// Just skip this step.
Tracing.Log("Could not delete peak file " + peakFilePath + ".");
}
}
}
}
// Set completed
IsLoading = false;
Console.WriteLine("PeakFileService - ProcessDone - processSuccessful: " + processSuccessful.ToString() + " filePath: " + audioFilePath);
OnProcessDone(new PeakFileDoneData() {
AudioFilePath = audioFilePath,
Cancelled = !processSuccessful
});
}, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}
/// <summary>
/// Cancels the peak file generation.
/// </summary>
public void Cancel()
{
if (IsLoading)
if(cancellationTokenSource != null)
cancellationTokenSource.Cancel();
}
/// <summary>
/// Reads a peak file and returns a min/max peak list.
/// </summary>
/// <param name="peakFilePath">Peak file path</param>
/// <returns>List of min/max peaks</returns>
public List<WaveDataMinMax> ReadPeakFile(string peakFilePath)
{
// Declare variables
FileStream fileStream = null;
GZipStream gzipStream = null;
BinaryReader binaryReader = null;
List<WaveDataMinMax> listMinMax = new List<WaveDataMinMax>();
string fileHeader = null;
long audioFileLength = 0;
int chunkSize = 0;
int numberOfBlocks = 0;
int currentBlock = 0;
try
{
// Create file stream
fileStream = new FileStream(peakFilePath, FileMode.Open, FileAccess.Read);
// Open binary reader
binaryReader = new BinaryReader(fileStream);
// Create GZip stream
gzipStream = new GZipStream(fileStream, CompressionMode.Decompress);
// Read file header (30 characters)
// Ex: MPfm Peak File (version# 1.00)
fileHeader = new string(binaryReader.ReadChars(31));
// Extract version and validate
string version = fileHeader.Substring(fileHeader.Length - 5, 4);
if (version != this.version)
{
throw new PeakFileFormatIncompatibleException("Error: The peak file format is not compatible. Expecting version " + this.version + " instead of version " + version + ".", null);
}
// Read audio file length
audioFileLength = binaryReader.ReadInt64();
// Read chunk size and number of blocks
chunkSize = binaryReader.ReadInt32();
numberOfBlocks = binaryReader.ReadInt32();
// Loop through data
while (binaryReader.PeekChar() != -1)
{
// Increment block
currentBlock++;
// Read peak information and add to list
WaveDataMinMax peak = new WaveDataMinMax();
peak.leftMin = (float)binaryReader.ReadDouble();
peak.leftMax = (float)binaryReader.ReadDouble();
peak.rightMin = (float)binaryReader.ReadDouble();
peak.rightMax = (float)binaryReader.ReadDouble();
peak.mixMin = (float)binaryReader.ReadDouble();
peak.mixMax = (float)binaryReader.ReadDouble();
listMinMax.Add(peak);
}
// Validate number of blocks read
if (currentBlock < numberOfBlocks - 1)
{
throw new PeakFileCorruptedException("Error: The peak file is corrupted (the number of blocks didn't match)!", null);
}
}
catch (Exception ex)
{
throw new PeakFileCorruptedException("Error: The peak file is corrupted!", ex);
}
finally
{
// Close stream and reader
gzipStream.Close();
binaryReader.Close();
fileStream.Close();
}
return listMinMax;
}
/// <summary>
/// Returns the total size of all files within a directory. Non-recursive.
/// </summary>
/// <param name="path">Path</param>
/// <returns>Total size (in bytes)</returns>
public static long CheckDirectorySize(string path)
{
// Get list of files
string[] files = Directory.GetFiles(path, "*.mpfmPeak");
// Loop through files and calculate total length
long length = 0;
foreach (string file in files)
{
// Get file information
FileInfo fileInfo = new FileInfo(file);
// Increment length
length += fileInfo.Length;
}
return length;
}
/// <summary>
/// Deletes all the peak files in a directory.
/// </summary>
/// <param name="path">Path</param>
public static void DeletePeakFiles(string path)
{
// Get list of files
string[] files = Directory.GetFiles(path, "*.mpfmPeak");
// Loop through files
foreach (string file in files)
{
// Delete file
File.Delete(file);
}
}
}
}