-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpar2repairer.cpp
executable file
·3496 lines (2964 loc) · 104 KB
/
par2repairer.cpp
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of par2cmdline (a PAR 2.0 compatible file verification and
// repair tool). See http://parchive.sourceforge.net for details of PAR 2.0.
//
// Copyright (c) 2003 Peter Brian Clements
//
// par2cmdline 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 2 of the License, or
// (at your option) any later version.
//
// par2cmdline 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 this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Modifications for concurrent processing, async I/O, Unicode support, and
// hierarchial directory support are Copyright (c) 2007-2008 Vincent Tan.
//
// Modifications for GPGPU support using nVidia CUDA technology are
// Copyright (c) 2008 Vincent Tan.
//
// Search for "#if WANT_CONCURRENT" for concurrent code.
// Concurrent processing utilises Intel Thread Building Blocks 2.0,
// Copyright (c) 2007 Intel Corp.
//
// par2cmdline-0.4-tbb is available at http://chuchusoft.com/par2_tbb
#include "par2cmdline.h"
//static unsigned gti;
//static tbb::atomic<unsigned> gti;
#if WANT_CONCURRENT
#include <set>
#if CONCURRENT_PIPELINE
class repair_buffer : public pipeline_buffer {
friend class repair_filter_read;
vector<DataBlock*>::iterator copyblock_;
bool copyblock_not_at_end_;
};
class repair_pipeline_state : public pipeline_state<repair_buffer> {
private:
friend class repair_filter_read;
vector<DataBlock*>& copyblocks_;
vector<DataBlock*>::iterator copyblock_;
public:
repair_pipeline_state(
size_t max_tokens,
u64 chunksize,
u32 missingblockcount,
size_t blocklength,
u64 blockoffset,
vector<DataBlock*>& inputblocks,
vector<DataBlock*>& copyblocks) :
pipeline_state<repair_buffer>(max_tokens, chunksize, missingblockcount, blocklength, blockoffset, inputblocks),
copyblocks_(copyblocks), copyblock_(copyblocks.begin()) {}
};
class repair_filter_read : public filter_read_base<repair_filter_read, repair_buffer> {
public:
repair_filter_read(repair_pipeline_state& s) : filter_read_base<repair_filter_read, repair_buffer>(s) {}
void on_mutex_held(repair_buffer* ib) {
repair_pipeline_state& s = static_cast<repair_pipeline_state&> (state_);
ib->copyblock_ = s.copyblock_; //copyblock_ = s.copyblock_;
ib->copyblock_not_at_end_ = s.copyblock_ != s.copyblocks_.end(); //copyblock_not_at_end_ = copyblock_ != s.copyblocks_.end();
if (ib->copyblock_not_at_end_)
++s.copyblock_;
}
bool on_inputbuffer_read(repair_buffer* ib) {
// Have we reached the last source data block
if (ib->copyblock_not_at_end_) {
// Does this block need to be copied to the target file
if ((*ib->copyblock_)->IsSet()) {
//DiskFile* df = (*copyblock)->GetDiskFile();
//printf("%p: start async write to %s\n", pthread_self(), df->FileName().c_str());
// Write the block back to disk in the new target file
//printf("filter_read::operator()\n");
assert(pipeline_buffer::NONE == ib->get_write_status());
#ifdef DEBUG_ASYNC_WRITE
// used to debug the problem where the last byte of the file was not being written to - the bug fix is
// in diskfile.cpp: DiskFile::Create()
printf("writing off=%llu len=%lu\n", (*ib->copyblock_)->GetOffset() + state_.blockoffset(), state_.blocklength());
if (102388 == (*ib->copyblock_)->GetOffset()) {
for (unsigned i = 0; i != state_.blocklength(); ++i)
printf("%02x ", ((const unsigned char*) ib->get())[i]);
printf("\n");
}
#endif
size_t wrote;
#if 0
// used to debug the problem where the last byte of the file was not being written to - the bug fix is
// in diskfile.cpp: DiskFile::Create()
if (!(*ib->copyblock_)->WriteData(state_.blockoffset(), state_.blocklength(), ib->get(), wrote))
return false;
#else
if (!(*ib->copyblock_)->WriteDataAsync(ib->get_aiocb(), state_.blockoffset(),
state_.blocklength(), ib->get(), wrote)) {
return false;
}
ib->set_write_status(pipeline_buffer::ASYNC_WRITE);
#endif
state_.add_to_totalwritten(wrote);
}
//++copyblock;
}
return true;
}
};
class repair_filter_process : public filter_process_base<repair_filter_process, repair_buffer, Par2Repairer> {
public:
repair_filter_process(Par2Repairer& delegate, pipeline_state<repair_buffer>& s) :
filter_process_base<repair_filter_process, repair_buffer, Par2Repairer>(delegate, s) {}
};
#endif
#endif
#ifdef _MSC_VER
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#endif
Par2Repairer::Par2Repairer(void)
{
noiselevel = CommandLine::nlNormal;
firstpacket = true;
mainpacket = NULL;
creatorpacket = NULL;
blocksize = 0;
//chunksize = 0; ???
sourceblockcount = 0;
availableblockcount = 0;
missingblockcount = 0;
blocksallocated = false;
//windowmask = 0; ???
//filechecksummer = NULL; cannot be allocated yet (needs windowtable)
//blockverifiable = false; ???
completefilecount = 0;
renamedfilecount = 0;
damagedfilecount = 0;
missingfilecount = 0;
#if WANT_CONCURRENT && CONCURRENT_PIPELINE
#else
//inputbuffer = NULL;
#endif
outputbuffer = NULL;
//totaldata = 0; ???
#if WANT_CONCURRENT
concurrent_processing_level = INVALID_CONCURRENCY_LEVEL; // ALL_CONCURRENT;
cout_in_use = 0;
last_cout = tbb::tick_count::now();
#endif
}
Par2Repairer::~Par2Repairer(void)
{
#if WANT_CONCURRENT && CONCURRENT_PIPELINE && GPGPU_CUDA
cuda::DeallocateResources();
#endif
#if WANT_CONCURRENT && CONCURRENT_PIPELINE
if (outputbuffer)
tbb::cache_aligned_allocator<u8>().deallocate((u8*)outputbuffer, 0);
#else
//delete [] (u8*)inputbuffer;
delete [] (u8*)outputbuffer;
#endif
#if WANT_CONCURRENT
tbb::concurrent_hash_map<u32, RecoveryPacket*, u32_hasher>::iterator rp = recoverypacketmap.begin();
#else
map<u32,RecoveryPacket*>::iterator rp = recoverypacketmap.begin();
#endif
while (rp != recoverypacketmap.end())
{
delete (*rp).second;
++rp;
}
map<MD5Hash,Par2RepairerSourceFile*>::iterator sf = sourcefilemap.begin();
while (sf != sourcefilemap.end())
{
Par2RepairerSourceFile *sourcefile = (*sf).second;
delete sourcefile;
++sf;
}
delete mainpacket;
delete creatorpacket;
// 2014/10/25
for (vector<FileCheckSummerPtr>::const_iterator it = filechecksummers.begin();
it != filechecksummers.end(); ++it)
delete *it;
}
Result Par2Repairer::Process(const CommandLine &commandline, bool dorepair)
{
//CTimeInterval ti_setup("Setup");
// What noiselevel are we using
noiselevel = commandline.GetNoiseLevel();
#if WANT_CONCURRENT
concurrent_processing_level = commandline.GetConcurrentProcessingLevel();
if (noiselevel > CommandLine::nlQuiet) {
cout << "Processing ";
#if 1
assert(INVALID_CONCURRENCY_LEVEL != concurrent_processing_level);
assert(0 != GetMaxConcurrency(concurrent_processing_level));
assert(GetMaxConcurrency(concurrent_processing_level) <= (unsigned) tbb::task_scheduler_init::default_num_threads());
if (1 == GetMaxConcurrency(concurrent_processing_level))
cout << "verifications and repairs serially.";
else if (SERIAL_VERIFICATION_MASK & concurrent_processing_level)
cout << "verifications serially and repairs concurrently.";
else
cout << "verifications and repairs concurrently using up to " << GetMaxConcurrency(concurrent_processing_level) << " logical CPUs.";
#elif 0
if (ALL_SERIAL == concurrent_processing_level)
cout << "verifications and repairs serially.";
else if (CHECKSUM_SERIALLY_BUT_PROCESS_CONCURRENTLY == concurrent_processing_level)
cout << "verifications serially and repairs concurrently.";
else if (ALL_CONCURRENT == concurrent_processing_level)
cout << "verifications and repairs concurrently.";
else
return eLogicError;
#endif
cout << endl;
}
#endif
// Get filesnames from the command line
string par2filename = commandline.GetParFilename();
const list<CommandLine::ExtraFile> &extrafiles = commandline.GetExtraFiles();
// Determine the searchpath from the location of the main PAR2 file
string name;
DiskFile::SplitFilename(par2filename, searchpath, name);
// Load packets from the main PAR2 file
if (!LoadPacketsFromFile(searchpath + name))
return eLogicError;
// Load packets from other PAR2 files with names based on the original PAR2 file
if (!LoadPacketsFromOtherFiles(par2filename))
return eLogicError;
// Load packets from any other PAR2 files whose names are given on the command line
if (!LoadPacketsFromExtraFiles(extrafiles))
return eLogicError;
if (noiselevel > CommandLine::nlQuiet)
cout << endl;
// Check that the packets are consistent and discard any that are not
if (!CheckPacketConsistency())
return eInsufficientCriticalData;
// Use the information in the main packet to get the source files
// into the correct order and determine their filenames
if (!CreateSourceFileList())
return eLogicError;
// Determine the total number of DataBlocks for the recoverable source files
// The allocate the DataBlocks and assign them to each source file
if (!AllocateSourceBlocks())
return eLogicError;
// Create a verification hash table for all files for which we have not
// found a complete version of the file and for which we have
// a verification packet
if (!PrepareVerificationHashTable())
return eLogicError;
// Compute the table for the sliding CRC computation
if (!ComputeWindowTable())
return eLogicError;
//ti_setup.emit();
if (noiselevel > CommandLine::nlQuiet)
cout << endl << "Verifying source files:" << endl << endl;
//CTimeInterval ti_vfy("Verify-source");
// Attempt to verify all of the source files
if (!VerifySourceFiles())
return eFileIOError;
//ti_vfy.emit();
if (completefilecount<mainpacket->RecoverableFileCount())
{
if (noiselevel > CommandLine::nlQuiet)
cout << endl << "Scanning extra files:" << endl << endl;
// Scan any extra files specified on the command line
if (!VerifyExtraFiles(extrafiles))
return eLogicError;
}
// Find out how much data we have found
UpdateVerificationResults();
if (noiselevel > CommandLine::nlSilent)
cout << endl;
// Check the verification results and report the results
if (!CheckVerificationResults())
return eRepairNotPossible;
// Are any of the files incomplete
if (completefilecount<mainpacket->RecoverableFileCount())
{
// Do we want to carry out a repair
if (dorepair)
{
if (noiselevel > CommandLine::nlSilent)
cout << endl;
// Rename any damaged or missnamed target files.
if (!RenameTargetFiles())
return eFileIOError;
// Are we still missing any files
if (completefilecount<mainpacket->RecoverableFileCount())
{
// Work out which files are being repaired, create them, and allocate
// target DataBlocks to them, and remember them for later verification.
if (!CreateTargetFiles())
return eFileIOError;
// Work out which data blocks are available, which need to be copied
// directly to the output, and which need to be recreated, and compute
// the appropriate Reed Solomon matrix.
if (!ComputeRSmatrix())
{
// Delete all of the partly reconstructed files
DeleteIncompleteTargetFiles();
return eFileIOError;
}
if (noiselevel > CommandLine::nlSilent)
cout << endl;
// Allocate memory buffers for reading and writing data to disk.
if (!AllocateBuffers(commandline.GetMemoryLimit()))
{
// Delete all of the partly reconstructed files
DeleteIncompleteTargetFiles();
return eMemoryError;
}
//CTimeInterval ti_repair("Repair");
// Set the total amount of data to be processed.
progress = 0;
totaldata = blocksize * sourceblockcount * (missingblockcount > 0 ? missingblockcount : 1);
//gti = 0;
// Start at an offset of 0 within a block.
u64 blockoffset = 0;
while (blockoffset < blocksize) // Continue until the end of the block.
{
//std::ostringstream s;
//s << "Repair-" << blockoffset;
//CTimeInterval ti_repair_inner(s.str());
// Work out how much data to process this time.
size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset);
// Read source data, process it through the RS matrix and write it to disk.
if (!ProcessData(blockoffset, blocklength))
{
// Delete all of the partly reconstructed files
DeleteIncompleteTargetFiles();
return eFileIOError;
}
//ti_repair_inner.emit();
// Advance to the need offset within each block
blockoffset += blocklength;
}
//cout << "total rs processing time = " << ((double) ((unsigned) gti)/1000000.0) << " seconds." << endl;
//ti_repair.emit();
if (noiselevel > CommandLine::nlSilent)
cout << endl << "Verifying repaired files:" << endl << endl;
// Verify that all of the reconstructed target files are now correct
if (!VerifyTargetFiles())
{
// Delete all of the partly reconstructed files
DeleteIncompleteTargetFiles();
return eFileIOError;
}
}
// Are all of the target files now complete?
if (completefilecount<mainpacket->RecoverableFileCount())
{
cerr << "Repair Failed." << endl;
return eRepairFailed;
}
else
{
if (noiselevel > CommandLine::nlSilent)
cout << endl << "Repair complete." << endl;
}
}
else
{
return eRepairPossible;
}
}
return eSuccess;
}
// Load the packets from the specified file
bool Par2Repairer::LoadPacketsFromFile(const string &filename)
{
// Skip the file if it has already been processed
if (diskFileMap.Find(filename) != 0)
{
return true;
}
DiskFile *diskfile = new DiskFile;
// Open the file
if (!diskfile->Open(filename))
{
// If we could not open the file, ignore the error and
// proceed to the next file
delete diskfile;
return true;
}
if (noiselevel > CommandLine::nlSilent) {
const string name(utf8_string_to_cout_parameter(CommandLine::FileOrPathForCout(filename)));
#if WANT_CONCURRENT
tbb::mutex::scoped_lock l(cout_mutex);
#endif
cout << "Loading \"" << name << "\"." << endl;
}
// How many useable packets have we found
u32 packets = 0;
// How many recovery packets were there
u32 recoverypackets = 0;
// How big is the file
u64 filesize = diskfile->FileSize();
if (filesize > 0)
{
// Allocate a buffer to read data into
// The buffer should be large enough to hold a whole
// critical packet (i.e. file verification, file description, main,
// and creator), but not necessarily a whole recovery packet.
size_t buffersize = (size_t)min((u64)1048576, filesize);
u8 *buffer = new u8[buffersize];
// Progress indicator
u64 progress = 0;
// Start at the beginning of the file
u64 offset = 0;
// Continue as long as there is at least enough for the packet header
while (offset + sizeof(PACKET_HEADER) <= filesize)
{
if (noiselevel > CommandLine::nlQuiet)
{
#if WANT_CONCURRENT
tbb::tick_count now = tbb::tick_count::now();
if ((now - last_cout).seconds() >= 0.1) { // only update every 0.1 seconds
#endif
// Update a progress indicator
u32 oldfraction = (u32)(1000 * progress / filesize);
u32 newfraction = (u32)(1000 * offset / filesize);
if (oldfraction != newfraction)
{
progress = offset;
#if WANT_CONCURRENT
last_cout = now;
tbb::mutex::scoped_lock l(cout_mutex);
#endif
cout << "Loading: " << newfraction/10 << '.' << newfraction%10 << "%\r" << flush;
}
#if WANT_CONCURRENT
}
#endif
}
// Attempt to read the next packet header
PACKET_HEADER header;
if (!diskfile->Read(offset, &header, sizeof(header)))
break;
// Does this look like it might be a packet
if (packet_magic != header.magic)
{
offset++;
// Is there still enough for at least a whole packet header
while (offset + sizeof(PACKET_HEADER) <= filesize)
{
// How much can we read into the buffer
size_t want = (size_t)min((u64)buffersize, filesize-offset);
// Fill the buffer
if (!diskfile->Read(offset, buffer, want))
{
offset = filesize;
break;
}
// Scan the buffer for the magic value
u8 *current = buffer;
u8 *limit = &buffer[want-sizeof(PACKET_HEADER)];
while (current <= limit && packet_magic != ((PACKET_HEADER*)current)->magic)
{
current++;
}
// What file offset did we reach
offset += current-buffer;
// Did we find the magic
if (current <= limit)
{
memcpy(&header, current, sizeof(header));
break;
}
}
// Did we reach the end of the file
if (offset + sizeof(PACKET_HEADER) > filesize)
{
break;
}
}
// We have found the magic
// Check the packet length
if (sizeof(PACKET_HEADER) > header.length || // packet length is too small
0 != (header.length & 3) || // packet length is not a multiple of 4
filesize < offset + header.length) // packet would extend beyond the end of the file
{
offset++;
continue;
}
// Compute the MD5 Hash of the packet
MD5Context context;
context.Update(&header.setid, sizeof(header)-offsetof(PACKET_HEADER, setid));
// How much more do I need to read to get the whole packet
u64 current = offset+sizeof(PACKET_HEADER);
u64 limit = offset+header.length;
while (current < limit)
{
size_t want = (size_t)min((u64)buffersize, limit-current);
if (!diskfile->Read(current, buffer, want))
break;
context.Update(buffer, want);
current += want;
}
// Did the whole packet get processed
if (current<limit)
{
offset++;
continue;
}
// Check the calculated packet hash against the value in the header
MD5Hash hash;
context.Final(hash);
if (hash != header.hash)
{
offset++;
continue;
}
// If this is the first packet that we have found then record the setid
if (firstpacket)
{
setid = header.setid;
firstpacket = false;
}
// Is the packet from the correct set
if (setid == header.setid)
{
// Is it a packet type that we are interested in
if (recoveryblockpacket_type == header.type)
{
if (LoadRecoveryPacket(diskfile, offset, header))
{
recoverypackets++;
packets++;
}
}
else if (fileverificationpacket_type == header.type)
{
if (LoadVerificationPacket(diskfile, offset, header))
{
packets++;
}
}
else if (filedescriptionpacket_type == header.type)
{
if (LoadDescriptionPacket(diskfile, offset, header))
{
packets++;
}
}
else if (mainpacket_type == header.type)
{
if (LoadMainPacket(diskfile, offset, header))
{
packets++;
}
}
else if (creatorpacket_type == header.type)
{
if (LoadCreatorPacket(diskfile, offset, header))
{
packets++;
}
}
}
// Advance to the next packet
offset += header.length;
}
delete [] buffer;
}
// We have finished with the file for now
diskfile->Close();
// Did we actually find any interesting packets
if (packets > 0)
{
if (noiselevel > CommandLine::nlQuiet)
{
#if WANT_CONCURRENT
tbb::mutex::scoped_lock l(cout_mutex);
#endif
cout << "Loaded " << packets << " new packets";
if (recoverypackets > 0) cout << " including " << recoverypackets << " recovery blocks";
cout << endl;
}
diskfile->SetBlockCount(recoverypackets); // for tbb::pipeline repairer
// Remember that the file was processed
#ifndef NDEBUG
bool success = diskFileMap.Insert(diskfile);
assert(success);
#else
(bool) diskFileMap.Insert(diskfile);
#endif
}
else
{
if (noiselevel > CommandLine::nlQuiet) {
#if WANT_CONCURRENT
tbb::mutex::scoped_lock l(cout_mutex);
#endif
cout << "No new packets found" << endl;
}
delete diskfile;
}
return true;
}
// Finish loading a recovery packet
bool Par2Repairer::LoadRecoveryPacket(DiskFile *diskfile, u64 offset, PACKET_HEADER &header)
{
RecoveryPacket *packet = new RecoveryPacket;
// Load the packet from disk
if (!packet->Load(diskfile, offset, header))
{
delete packet;
return false;
}
// What is the exponent value of this recovery packet
u32 exponent = packet->Exponent();
// Try to insert the new packet into the recovery packet map
#if WANT_CONCURRENT
{
tbb::concurrent_hash_map<u32, RecoveryPacket*, u32_hasher>::accessor a;
(bool) recoverypacketmap.insert(a, exponent); // returns whether exponent is new, and NOT whether insert succeeded
a->second = packet;
}
#else
pair<map<u32,RecoveryPacket*>::const_iterator, bool> location = recoverypacketmap.insert(pair<u32,RecoveryPacket*>(exponent, packet));
// Did the insert fail
if (!location.second)
{
// The packet must be a duplicate of one we already have
delete packet;
return false;
}
#endif
return true;
}
// Finish loading a file description packet
bool Par2Repairer::LoadDescriptionPacket(DiskFile *diskfile, u64 offset, PACKET_HEADER &header)
{
DescriptionPacket *packet = new DescriptionPacket;
// Load the packet from disk
if (!packet->Load(diskfile, offset, header))
{
delete packet;
return false;
}
// What is the fileid
const MD5Hash &fileid = packet->FileId();
// Look up the fileid in the source file map for an existing source file entry
map<MD5Hash, Par2RepairerSourceFile*>::iterator sfmi = sourcefilemap.find(fileid);
Par2RepairerSourceFile *sourcefile = (sfmi == sourcefilemap.end()) ? 0 :sfmi->second;
// Was there an existing source file
if (sourcefile)
{
// Does the source file already have a description packet
if (sourcefile->GetDescriptionPacket())
{
// Yes. We don't need another copy
delete packet;
return false;
}
else
{
// No. Store the packet in the source file
sourcefile->SetDescriptionPacket(packet);
return true;
}
}
else
{
// Create a new source file for the packet
sourcefile = new Par2RepairerSourceFile(packet, NULL);
// Record the source file in the source file map
sourcefilemap.insert(pair<MD5Hash, Par2RepairerSourceFile*>(fileid, sourcefile));
return true;
}
}
// Finish loading a file verification packet
bool Par2Repairer::LoadVerificationPacket(DiskFile *diskfile, u64 offset, PACKET_HEADER &header)
{
VerificationPacket *packet = new VerificationPacket;
// Load the packet from disk
if (!packet->Load(diskfile, offset, header))
{
delete packet;
return false;
}
// What is the fileid
const MD5Hash &fileid = packet->FileId();
// Look up the fileid in the source file map for an existing source file entry
map<MD5Hash, Par2RepairerSourceFile*>::iterator sfmi = sourcefilemap.find(fileid);
Par2RepairerSourceFile *sourcefile = (sfmi == sourcefilemap.end()) ? 0 :sfmi->second;
// Was there an existing source file
if (sourcefile)
{
// Does the source file already have a verification packet
if (sourcefile->GetVerificationPacket())
{
// Yes. We don't need another copy.
delete packet;
return false;
}
else
{
// No. Store the packet in the source file
sourcefile->SetVerificationPacket(packet);
return true;
}
}
else
{
// Create a new source file for the packet
sourcefile = new Par2RepairerSourceFile(NULL, packet);
// Record the source file in the source file map
sourcefilemap.insert(pair<MD5Hash, Par2RepairerSourceFile*>(fileid, sourcefile));
return true;
}
}
// Finish loading the main packet
bool Par2Repairer::LoadMainPacket(DiskFile *diskfile, u64 offset, PACKET_HEADER &header)
{
// Do we already have a main packet
if (!!mainpacket)
return false;
MainPacket *packet = new MainPacket;
// Load the packet from disk;
if (!packet->Load(diskfile, offset, header))
{
delete packet;
return false;
}
#if WANT_CONCURRENT
mainpacket.compare_and_swap(packet, NULL);
if (mainpacket != packet) {
delete packet;
return false;
}
#else
mainpacket = packet;
#endif
return true;
}
// Finish loading the creator packet
bool Par2Repairer::LoadCreatorPacket(DiskFile *diskfile, u64 offset, PACKET_HEADER &header)
{
// Do we already have a creator packet
if (!!creatorpacket)
return false;
CreatorPacket *packet = new CreatorPacket;
// Load the packet from disk;
if (!packet->Load(diskfile, offset, header))
{
delete packet;
return false;
}
#if WANT_CONCURRENT
creatorpacket.compare_and_swap(packet, NULL);
if (creatorpacket != packet) {
delete packet;
return false;
}
#else
creatorpacket = packet;
#endif
return true;
}
#if WANT_CONCURRENT
#if defined(WIN32) || defined(__APPLE_CC__)
struct less_istring {
bool operator()( const std::string& x, const std::string& y ) const
{ return stricmp(x.c_str(), y.c_str()) < 0; }
};
typedef less_istring less_string_type;
#else
typedef std::less<string> less_string_type;
#endif
#if 1
template <typename CONTAINER>
class pipeline_state_container_of_files {
private:
typedef ptrdiff_t index_delta_t;
typedef size_t index_t;
public:
pipeline_state_container_of_files(
const CONTAINER& files, Par2Repairer& delegate) :
files_(files), delegate_(delegate) { idx_ = 0; }
bool execute(void) {
const unsigned idx = add_idx(1) - 1;
const CONTAINER& files = this->files();
const size_t sz = files.size();
if (idx >= sz) {
add_idx(-1);
return false; // done
}
execute(files[idx]);
return (idx+1)<sz; // if not last file then tell pipeline to keep going
}
protected:
const CONTAINER& files(void) const { return files_; }
Par2Repairer& delegate(void) const { return delegate_; }
private:
void execute(typename CONTAINER::value_type file);
index_t add_idx(index_delta_t delta) { return idx_ += delta; }
const CONTAINER& files_;
Par2Repairer& delegate_;
tbb::atomic<index_t> idx_; // ranges from 0...files_.size() *inclusively*
};
template <typename STATE>
class filter_files : public tbb::filter {
private:
filter_files& operator=(const filter_files&); // assignment disallowed
protected:
STATE& state_;
public:
filter_files(STATE& state) : tbb::filter(tbb::filter::parallel), state_(state) {}
virtual void* operator()(void*) {
// execute() returns false if nothing more to do -> returns NULL to
// tell tbb::pipeline that there is no more to process
return state_.execute() ? this : NULL;
}
};
typedef pipeline_state_container_of_files< vector<string> > pipeline_state_load_par2_packets;
typedef filter_files<pipeline_state_load_par2_packets> filter_load_par2_packets;
template <>
void
pipeline_state_container_of_files< vector<string> >::execute(string file) {
(void) delegate().LoadPacketsFromFile(file); // LoadPacketsFromFile() always returns true
}
#else
class ApplyLoadPacketsFromFile {
Par2Repairer* const _obj;
const std::vector<string>& _v;
public:
void operator()( const tbb::blocked_range<size_t>& r ) const {
Par2Repairer* obj = _obj;
const std::vector<string>& v = _v;
for ( size_t i = r.begin(); i != r.end(); ++i )
(bool) obj->LoadPacketsFromFile(v[i]);
}
ApplyLoadPacketsFromFile( Par2Repairer* obj, const std::vector<string>& v ) :
_obj(obj), _v(v) {}
};
#endif
#endif
// Load packets from other PAR2 files with names based on the original PAR2 file