-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecmtool.cpp
1730 lines (1504 loc) · 62.1 KB
/
ecmtool.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
/*******************************************************************************
*
* Created by Daniel Carrasco at https://www.electrosoftcloud.com
*
* This program 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.
*
* This program 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, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
#include "ecmtool.h"
#define ECM_FILE_VERSION 3
// Some necessary variables
static uint8_t mycounter_analyze = 0;
static uint8_t mycounter_encode = 0;
static uint64_t mycounter_decode = 0;
static uint64_t mycounter_total = 0;
static struct option long_options[] = {
{"input", required_argument, NULL, 'i'},
{"output", required_argument, NULL, 'o'},
{"acompression", required_argument, NULL, 'a'},
{"dcompression", required_argument, NULL, 'd'},
{"clevel", required_argument, NULL, 'c'},
{"extreme-compression", no_argument, NULL, 'e'},
{"seekable", no_argument, NULL, 's'},
{"sectors-per-block", required_argument, NULL, 'p'},
{"force", required_argument, NULL, 'f'},
{"keep-output", required_argument, NULL, 'k'},
{NULL, 0, NULL, 0}
};
int main(int argc, char **argv) {
std::ios_base::sync_with_stdio(false);
// ECM processor options
ecm_options options;
// Input file will be decoded
bool decode = false;
// Input/Output files
std::ifstream in_file;
std::fstream out_file;
// blocks toc vector
std::vector<blocks_toc> file_blocks_toc;
// Start the timer to measure execution time
auto start = std::chrono::high_resolution_clock::now();
// Return code.
int return_code = 0;
return_code = get_options(argc, argv, &options);
if (return_code) {
goto exit;
}
if (options.in_filename.empty()) {
fprintf(stderr, "ERROR: input file is required.\n");
print_help();
return 1;
}
// Open the input file
in_file.open(options.in_filename.c_str(), std::ios::binary);
// Tricky way to check if was oppened correctly.
// The "is_open" method was failing on cross compiled EXE
{
char dummy;
if (!in_file.read(&dummy, 0)) {
fprintf(stderr, "ERROR: input file cannot be opened.\n");
return 1;
}
}
// Check if the file is an ECM3 File
{
char file_format[5];
in_file.read(file_format, 4);
if (
file_format[0] == 'E' &&
file_format[1] == 'C' &&
file_format[2] == 'M'
) {
// File is an ECM2 file, but we need to check the version
if (file_format[3] == ECM_FILE_VERSION) {
fprintf(stdout, "An ECM2 file was detected... will be decoded\n");
decode = true;
}
else {
fprintf(stderr, "The input file ECM version is not supported.\n");
return_code = 1;
goto exit;
}
}
else {
fprintf(stdout, "A BIN file was detected... will be encoded\n");
}
}
// If no output filename was provided, generate it using the input filename
if (options.out_filename.empty()) {
// Input file will be decoded, so ecm2 extension must be removed (if exists)
if (decode) {
// Copy the original string into a tmp string to force the same length
std::string tmp_filename = options.in_filename;
// Convert it to lowercase to easily check file extension
std::transform(options.in_filename.begin(), options.in_filename.end(), tmp_filename.begin(), ::tolower);
if (tmp_filename.substr(tmp_filename.length() - 5) == std::string(".ecm2")) {
options.out_filename = options.in_filename.substr(0, options.in_filename.length() - 5);
}
// If there is no .ecm2 extension, then .unecm2 will be appended to avoid to use the same filename
else {
options.out_filename = options.in_filename + ".unecm2";
}
}
else {
options.out_filename = options.in_filename + ".ecm2";
}
}
// Check if output file exists only if force_rewrite is false
if (options.force_rewrite == false) {
char dummy;
out_file.open(options.out_filename.c_str(), std::ios::in|std::ios::binary);
if (out_file.read(&dummy, 0)) {
fprintf(stderr, "ERROR: Cowardly refusing to replace output file. Use the -f/--force-rewrite options to force it.\n");
options.keep_output = true;
return_code = 1;
goto exit;
}
out_file.close();
}
// Open the output file in replace mode
out_file.open(options.out_filename.c_str(), std::ios::out|std::ios::binary);
// Check if file was oppened correctly.
if (!out_file.good()) {
fprintf(stderr, "ERROR: output file cannot be opened.\n");
return_code = 1;
goto exit;
}
// Encoding process
if (!decode) {
// Set output ECM header
out_file << "ECM" << char(ECM_FILE_VERSION);
// Dummy TOC position
uint64_t toc_position = 0;
out_file.write(reinterpret_cast<char*>(&toc_position), sizeof(toc_position));
// File TOC header
block_header toc_block_header = {ECMFILE_BLOCK_TYPE_TOC, 0, 0, 0};
// Add the ECM data TOC
file_blocks_toc.push_back(blocks_toc());
file_blocks_toc.back().type = ECMFILE_BLOCK_TYPE_ECM;
file_blocks_toc.back().start_position = out_file.tellp();
std::vector<uint32_t> sectors_type_sumary;
sectors_type_sumary.resize(13);
return_code = image_to_ecm_block(in_file, out_file, &options, §ors_type_sumary);
if (return_code) {
fprintf(stderr, "\n\nERROR: there was an error processing the input file.\n\n");
return_code = 1;
goto exit;
}
else {
summary(
§ors_type_sumary,
&options,
(uint64_t)out_file.tellp() - file_blocks_toc.back().start_position
);
}
// Write the Table of content
toc_position = out_file.tellp();
toc_block_header.real_block_size = file_blocks_toc.size() * sizeof(struct blocks_toc);
toc_block_header.block_size = toc_block_header.real_block_size;
// Write the Table of content header
out_file.write(reinterpret_cast<char*>(&toc_block_header), sizeof(toc_block_header));
// Write the Table of content data
out_file.write(reinterpret_cast<char*>(file_blocks_toc.data()), toc_block_header.block_size);
// Rewrite the Table of content position
out_file.seekp(4);
out_file.write(reinterpret_cast<char*>(&toc_position), sizeof(toc_position));
}
// Decoding process
else {
// Variables
uint64_t toc_position = 0;
block_header toc_block_header;
in_file.seekg(4, std::ios_base::beg);
// Read TOC position
in_file.read(reinterpret_cast<char*>(&toc_position), sizeof(toc_position));
// Read the TOC block header
in_file.seekg(toc_position, std::ios_base::beg);
in_file.read(reinterpret_cast<char*>(&toc_block_header), sizeof(toc_block_header));
// Read the TOC
file_blocks_toc.resize(toc_block_header.real_block_size / sizeof(struct blocks_toc));
in_file.read(reinterpret_cast<char*>(file_blocks_toc.data()), toc_block_header.real_block_size);
for (int i = 0; i < file_blocks_toc.size(); i++) {
if (file_blocks_toc[i].type == ECMFILE_BLOCK_TYPE_ECM) {
in_file.seekg(file_blocks_toc[i].start_position, std::ios_base::beg);
return_code = ecm_block_to_image(in_file, out_file, &options);
if (return_code) { break; }
}
}
}
exit:
if (in_file.is_open()) {
in_file.close();
}
if (out_file.is_open()) {
out_file.close();
}
if (return_code == 0) {
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
fprintf(stdout, "\n\nThe file was processed without any problem\n");
fprintf(stdout, "Total execution time: %0.3fs\n\n", duration.count() / 1000.0F);
}
else {
if (!options.keep_output) {
// Something went wrong, so output file must be deleted if keep == false
// We will remove the file if something went wrong
fprintf(stderr, "\n\nERROR: there was an error processing the input file.\n\n");
std::ifstream out_remove_tmp(options.out_filename.c_str(), std::ios::binary);
char dummy;
if (out_remove_tmp.read(&dummy, 0)) {
out_remove_tmp.close();
if (remove(options.out_filename.c_str())) {
fprintf(stderr, "There was an error removing the output file... Please remove it manually.\n");
}
}
}
}
return return_code;
}
int image_to_ecm_block(
std::ifstream &in_file,
std::fstream &out_file,
ecm_options *options,
std::vector<uint32_t> *sectors_type_sumary
) {
// Input size
in_file.seekg(0, std::ios_base::end);
size_t in_total_size = in_file.tellg();
in_file.seekg(0, std::ios_base::beg);
// Stream script to the encode process
std::vector<stream_script> streams_script;
// Sectors TOC
sector *sectors_toc = NULL;
sec_str_size sectors_toc_header = {C_NONE, 0, 0, 0};
uint8_t *sectors_toc_c_buffer;
// Streams TOC
stream *streams_toc = NULL;
sec_str_size streams_toc_header = {C_NONE, 0, 0, 0};
uint8_t *streams_toc_c_buffer;
// Sector Tools object
sector_tools *sTools;
// Return code
int return_code = 0;
if (in_total_size % 2352) {
fprintf(stderr, "ERROR: The input file doesn't appear to be a CD-ROM image\n");
fprintf(stderr, " This program only allows to process CD-ROM images\n");
return ECMTOOL_FILE_READ_ERROR;
}
// Reset the counters
resetcounter(in_total_size);
// Sector Tools object
sTools = new sector_tools();
// Block header with type 2 (ECM data), no compression, and no size for now
// Later will be completed when data is known
block_header ecm_block_header = {2, 0, 0, 0};
// ECM Header
ecm_header ecm_data_header = {
options->optimizations,
options->seekable ? options->sectors_per_block : (uint8_t)0,
0,
0,
0,
0,
0,
0,
"",
""
};
// Struct size without the strings
uint32_t ecm_data_header_size = sizeof(ecm_data_header) - sizeof(ecm_data_header.title) - sizeof(ecm_data_header.id);
// First blocks byte
uint64_t block_start_position = out_file.tellp();
// Will be setted later
uint64_t ecm_block_start_position = 0;
// Write the "dummy" block header
return_code = write_block_header(out_file, &ecm_block_header);
if (return_code) {
goto exit;
}
// First ECM block byte
ecm_block_start_position = out_file.tellp();
// Analyze the disk to detect the sectors types
return_code = disk_analyzer (
sTools,
in_file,
in_total_size,
streams_script,
&ecm_data_header,
options
);
// Write the ECM dummy header
out_file.write(reinterpret_cast<char*>(&ecm_data_header), ecm_data_header_size);
if (!out_file.good()) {
return_code = 1;
goto exit;
}
out_file << ecm_data_header.title;
out_file << ecm_data_header.id;
//
// Now we will write the ECM data header
//
ecm_data_header.ecm_data_pos = (uint64_t)out_file.tellp() - ecm_block_start_position;
//
// Convert the image to ECM data
//
return_code = disk_encode (
sTools,
in_file,
out_file,
streams_script,
options,
sectors_type_sumary,
ecm_data_header.ecm_data_pos
);
if (return_code) {
goto exit;
}
//
// Streams and Sectors TOC will be wrritten at the end because streams is modified
// during the encoding process with required data if compression was used.
//
//
// Time to write the streams header
//
ecm_data_header.streams_toc_pos = (uint64_t)out_file.tellp() - ecm_block_start_position;
return_code = task_to_streams_header (
streams_toc,
streams_toc_header,
streams_script
);
if (return_code) {
goto exit;
}
// Compress the streams header. Sectors count is base 0, so one will be added to the size calculation
{
// Compressed size will be the uncompressed size + 6 zlib header bytes + 5 zlib block headers for every 16k (plus two extra for security)
uint32_t compressed_size = streams_toc_header.uncompressed_size + 6 + (((streams_toc_header.uncompressed_size / 16.384) + 3) * 5);
streams_toc_c_buffer = (uint8_t *)malloc(compressed_size);
if(!streams_toc_c_buffer) {
fprintf(stderr, "Out of memory\n");
return_code = ECMTOOL_BUFFER_MEMORY_ERROR;
goto exit;
}
if (compress_header(streams_toc_c_buffer, compressed_size, (uint8_t *)streams_toc, streams_toc_header.uncompressed_size, 9)) {
fprintf(stderr, "There was an error compressing the streams header.\n");
return_code = ECMTOOL_HEADER_COMPRESSION_ERROR;
goto exit;
}
streams_toc_header.compressed_size = compressed_size;
streams_toc_header.compression = C_ZLIB;
}
// Write the compressed header
out_file.write(reinterpret_cast<char*>(&streams_toc_header), sizeof(streams_toc_header));
out_file.write(reinterpret_cast<char*>(streams_toc_c_buffer), streams_toc_header.compressed_size);
// Free the header memory
free(streams_toc);
streams_toc = NULL;
free(streams_toc_c_buffer);
streams_toc_c_buffer = NULL;
//
// Time to write the sectors header
//
ecm_data_header.sectors_toc_pos = (uint64_t)out_file.tellp() - ecm_block_start_position;
return_code = task_to_sectors_header (
sectors_toc,
sectors_toc_header,
streams_script
);
if (return_code) {
goto exit;
}
// Compress the sectors header. Sectors count is base 0, so one will be added to the size calculation
{
// Compressed size will be the uncompressed size + 6 zlib header bytes + 5 zlib block headers for every 16k (plus two extra for security)
uint32_t compressed_size = sectors_toc_header.uncompressed_size + 6 + (((sectors_toc_header.uncompressed_size / 16.384) + 3) * 5);
sectors_toc_c_buffer = (uint8_t*) malloc(compressed_size);
if(!sectors_toc_c_buffer) {
fprintf(stderr, "Out of memory\n");
return_code = ECMTOOL_BUFFER_MEMORY_ERROR;
goto exit;
}
if (compress_header(sectors_toc_c_buffer, compressed_size, (uint8_t *)sectors_toc, sectors_toc_header.uncompressed_size, 9)) {
fprintf(stderr, "There was an error compressing the output sectors header.\n");
return_code = ECMTOOL_HEADER_COMPRESSION_ERROR;
goto exit;
}
sectors_toc_header.compressed_size = compressed_size;
sectors_toc_header.compression = C_ZLIB;
}
// Write the compressed header
out_file.write(reinterpret_cast<char*>(§ors_toc_header), sizeof(sectors_toc_header));
if (!out_file.good()) {
return_code = 1;
goto exit;
}
out_file.write(reinterpret_cast<char*>(sectors_toc_c_buffer), sectors_toc_header.compressed_size);
if (!out_file.good()) {
return_code = 1;
goto exit;
}
// Free the header memory
free(sectors_toc);
sectors_toc = NULL;
free(sectors_toc_c_buffer);
sectors_toc_c_buffer = NULL;
// Set the block sizes. Both are equal because this block will not use compression
ecm_block_header.real_block_size = (uint64_t)out_file.tellp() - ecm_block_start_position;
ecm_block_header.block_size = (uint64_t)out_file.tellp() - ecm_block_start_position;
// Write the new block heeader
out_file.seekp(block_start_position);
out_file.write(reinterpret_cast<char*>(&ecm_block_header), sizeof(ecm_block_header));
if (!out_file.good()) {
return_code = 1;
goto exit;
}
// Finally, write the ecm data block header
out_file.write(reinterpret_cast<char*>(&ecm_data_header), ecm_data_header_size);
if (!out_file.good()) {
return_code = 1;
goto exit;
}
out_file.seekp(0, std::ios_base::end);
exit:
// Free the reserved memory for objects
if (sTools) {
delete sTools;
}
if (streams_toc) {
delete [] streams_toc;
}
if (streams_toc_c_buffer) {
delete [] streams_toc_c_buffer;
}
if (sectors_toc) {
delete [] sectors_toc;
}
if (sectors_toc_c_buffer) {
delete [] sectors_toc_c_buffer;
}
return return_code;
}
int ecm_block_to_image(
std::ifstream &in_file,
std::fstream &out_file,
ecm_options *options
) {
// CRC calculation to check the decoded stream
uint32_t output_edc = 0;
// Stream script to the encode process
std::vector<stream_script> streams_script;
// ECM headers
block_header ecm_block_header;
ecm_header ecm_data_header;
// Struct size without the strings
uint32_t ecm_data_header_size = sizeof(ecm_data_header) - sizeof(ecm_data_header.title) - sizeof(ecm_data_header.id);
// Will be setted later
uint64_t ecm_block_start_position;
// Sectors TOC
sector *sectors_toc = NULL;
sec_str_size sectors_toc_header = {C_NONE, 0, 0, 0};
uint8_t *sectors_toc_c_buffer;
// Streams TOC
stream *streams_toc = NULL;
sec_str_size streams_toc_header = {C_NONE, 0, 0, 0};
uint8_t *streams_toc_c_buffer;
// Sector Tools object
sector_tools *sTools = new sector_tools();
// Return code
int return_code = 0;
// Read the block header
return_code = read_block_header(in_file, &ecm_block_header);
if (return_code) {
goto exit;
}
// First ECM block byte
ecm_block_start_position = in_file.tellg();
// Read the ECM data header
in_file.read(reinterpret_cast<char*>(&ecm_data_header), ecm_data_header_size);
if (!in_file.good()) {
return_code = 1;
goto exit;
}
// Read the title stored in file if exists
if (ecm_data_header.title_length) {
ecm_data_header.title.resize(ecm_data_header.title_length);
in_file.read((char *)ecm_data_header.title.data(), ecm_data_header.title_length);
if (!in_file.good()) {
return_code = 1;
goto exit;
}
}
// Read the ID stored in file if exists
if (ecm_data_header.id_length) {
ecm_data_header.id.resize(ecm_data_header.id_length);
in_file.read((char *)ecm_data_header.id.data(), ecm_data_header.id_length);
if (!in_file.good()) {
return_code = 1;
goto exit;
}
}
// Set the optimization options used in file
options->optimizations = (optimization_options)ecm_data_header.optimizations;
// Reset the counters
resetcounter(ecm_block_header.block_size);
//
// Read the streams toc header
in_file.seekg(ecm_data_header.streams_toc_pos + ecm_block_start_position, std::ios_base::beg);
in_file.read(reinterpret_cast<char*>(&streams_toc_header), sizeof(streams_toc_header));
// Read the compressed stream toc data
streams_toc_c_buffer = (uint8_t *)malloc(streams_toc_header.compressed_size);
if (!streams_toc_c_buffer) {
return_code = 1;
goto exit;
}
in_file.read(reinterpret_cast<char*>(streams_toc_c_buffer), streams_toc_header.compressed_size);
if (!in_file.good()) {
printf("Error reading the in file: %s\n", strerror(errno));
return_code = 1;
goto exit;
}
// Decompress the streams toc data
streams_toc = (stream *)malloc(streams_toc_header.uncompressed_size);
if (decompress_header((uint8_t *)streams_toc, streams_toc_header.uncompressed_size, streams_toc_c_buffer, streams_toc_header.compressed_size)) {
fprintf(stderr, "There was an error decompressing the streams header.\n");
return_code = ECMTOOL_HEADER_COMPRESSION_ERROR;
goto exit;
}
free(streams_toc_c_buffer);
streams_toc_c_buffer = NULL;
//
// Read the sectors toc header
in_file.seekg(ecm_data_header.sectors_toc_pos + ecm_block_start_position, std::ios_base::beg);
in_file.read(reinterpret_cast<char*>(§ors_toc_header), sizeof(sectors_toc_header));
// Read the compressed stream toc data
sectors_toc_c_buffer = (uint8_t *)malloc(sectors_toc_header.compressed_size);
if (!sectors_toc_c_buffer) {
return_code = 1;
goto exit;
}
in_file.read(reinterpret_cast<char*>(sectors_toc_c_buffer), sectors_toc_header.compressed_size);
if (!in_file.good()) {
return_code = 1;
goto exit;
}
// Decompress the strams toc data
sectors_toc = (sector *)malloc(sectors_toc_header.uncompressed_size);
if (decompress_header((uint8_t *)sectors_toc, sectors_toc_header.uncompressed_size, sectors_toc_c_buffer, sectors_toc_header.compressed_size)) {
fprintf(stderr, "There was an error decompressing the sectors header.\n");
return_code = ECMTOOL_HEADER_COMPRESSION_ERROR;
goto exit;
}
free(sectors_toc_c_buffer);
sectors_toc_c_buffer = NULL;
// Convert the headers to an script to be followed
return_code = task_maker (
streams_toc,
streams_toc_header,
sectors_toc,
sectors_toc_header,
streams_script
);
if (return_code) {
return_code = ECMTOOL_CORRUPTED_STREAM;
goto exit;
}
in_file.seekg(ecm_data_header.ecm_data_pos + ecm_block_start_position, std::ios_base::beg);
return_code = disk_decode (
sTools,
in_file,
out_file,
streams_script,
options,
ecm_data_header.ecm_data_pos
);
exit:
if (sTools) {
delete sTools;
}
if (streams_toc) {
delete [] streams_toc;
}
if (streams_toc_c_buffer) {
delete [] streams_toc_c_buffer;
}
if (sectors_toc) {
delete [] sectors_toc;
}
if (sectors_toc_c_buffer) {
delete [] sectors_toc_c_buffer;
}
return return_code;
}
int write_block_header(
std::fstream &out_file,
block_header *block_header_data
) {
if (out_file.good()) {
// Write the header data
out_file.write(reinterpret_cast<char*>(block_header_data), sizeof(*block_header_data));
if (out_file.good()) {
return 0;
}
else {
return 1;
}
}
else {
fprintf(stderr, "Error writting the header because the output file is not correct\n.");
return 1;
}
return 0;
}
int read_block_header(
std::ifstream &in_file,
block_header *block_header_data
) {
if (in_file.good()) {
// Write the header data
in_file.read(reinterpret_cast<char*>(block_header_data), sizeof(*block_header_data));
if (in_file.good()) {
return 0;
}
else {
return 1;
}
}
else {
fprintf(stderr, "Error reading the header because the input file is not correct\n.");
return 1;
}
return 0;
}
static ecmtool_return_code disk_analyzer (
sector_tools *sTools,
std::ifstream &in_file,
size_t image_file_size,
std::vector<stream_script> &streams_script,
ecm_header *ecm_data_header,
ecm_options *options
) {
// Sector count
size_t sectors_count = image_file_size / 2352;
// Sector buffer
uint8_t in_sector[2352];
// Sector counter
uint32_t current_sector = 0;
// Seek to the begin
in_file.seekg(0, std::ios_base::beg);
// ID Detection
std::string id;
int id_detection_return = -1;
// Loop through all the sectors
for (size_t i = 0; i < sectors_count; i++) {
// Read a sector
in_file.read(reinterpret_cast<char*>(in_sector), 2352);
if (in_file.good()) {
// Update the input file position
setcounter_analyze(in_file.tellg());
sector_tools_types detected_type = sTools->detect(in_sector);
//printf("Current sector: %d -> Type: %d\n", current_sector, detected_type);
// Try to detect the game ID to add it to header
if (id_detection_return != 0) {
id_detection_return = detect_id_psx(id, in_sector, 2352);
if (id_detection_return == 0) {
ecm_data_header->id = id;
ecm_data_header->id_length = id.length();
}
}
//printf("Detected sector type: %d\n", detected_type);
// Only check the sector info in data sectors
if (detected_type != STT_CDDA && detected_type != STT_CDDA_GAP) {
// Check if MSF can be regenerated (libcrypt protection)
uint8_t time_data[3];
sTools->sector_to_time(time_data, current_sector + 0x96);
if (
ecm_data_header->optimizations & OO_REMOVE_MSF &&
(time_data[0] != in_sector[0x0C] ||
time_data[1] != in_sector[0x0D] ||
time_data[2] != in_sector[0x0E])
) {
// Sector contains wrong MSF, so it cannot be recovered in a lossless way
// To avoid this problem, we will disable the sector MSF optimization
ecm_data_header->optimizations = (optimization_options)(ecm_data_header->optimizations & ~OO_REMOVE_MSF);
//printf("Disabled MSF optimization. current_sector: %d, %d\n\n", current_sector, ecm_data_header->optimizations);
}
// Check if redundant FLAG can be regenerated (Only Mode 2 XA modes)
if (
(
detected_type == STT_MODE2_1 ||
detected_type == STT_MODE2_1_GAP ||
detected_type == STT_MODE2_2 ||
detected_type == STT_MODE2_2_GAP
) &&
ecm_data_header->optimizations & OO_REMOVE_REDUNDANT_FLAG &&
(
in_sector[0x10] != in_sector[0x14] ||
in_sector[0x11] != in_sector[0x15] ||
in_sector[0x12] != in_sector[0x16] ||
in_sector[0x13] != in_sector[0x17]
)
) {
// Sector contains wrong subheader redundancy, so it cannot be recovered in a lossless way
// To avoid this problem, we will disable the sector redundant FLAG removal
//printf("Disabled redundant FLAG. current_sector: %d\n\n", current_sector);
ecm_data_header->optimizations = (optimization_options)(ecm_data_header->optimizations & ~OO_REMOVE_REDUNDANT_FLAG);
}
}
// Replace the current optimization options to match the header optimizations
options->optimizations = (optimization_options)ecm_data_header->optimizations;
sector_tools_stream_types stream_type = sTools->detect_stream(detected_type);
// If there are no streams or stream type is different, create a new streams entry.
if (
streams_script.size() == 0 ||
streams_script.back().stream_data.type != (stream_type - 1)
) {
// Push the new element to the end
streams_script.push_back(stream_script());
// Set the element data
streams_script.back().stream_data.type = stream_type - 1;
if (stream_type == STST_AUDIO) {
streams_script.back().stream_data.compression = options->audio_compression;
}
else {
streams_script.back().stream_data.compression = options->data_compression;
}
if (streams_script.size() > 1) {
streams_script.back().stream_data.end_sector = streams_script[streams_script.size() - 2].stream_data.end_sector;
}
else {
streams_script.back().stream_data.end_sector = 0;
}
}
if (
streams_script.back().sectors_data.size() == 0 ||
streams_script.back().sectors_data.back().mode != detected_type
) {
// Push the new element to the end
streams_script.back().sectors_data.push_back(sector());
// Set the element data
streams_script.back().sectors_data.back().mode = detected_type;
streams_script.back().sectors_data.back().sector_count = 0;
}
streams_script.back().stream_data.end_sector++;
streams_script.back().sectors_data.back().sector_count++;
}
else {
// There was an eror reading the new sector
fprintf(stderr, "There was an error reading the input file.\n");
return ECMTOOL_FILE_READ_ERROR;
}
current_sector++;
}
return ECMTOOL_OK;
}
static ecmtool_return_code disk_encode (
sector_tools *sTools,
std::ifstream &in_file,
std::fstream &out_file,
std::vector<stream_script> &streams_script,
ecm_options *options,
std::vector<uint32_t> *sectors_type,
uint64_t ecm_block_start_position
) {
// Sectors buffers
uint8_t in_sector[2352];
uint8_t out_sector[2352];
// Hash
uint32_t input_edc = 0;
uint8_t buffer_edc[4];
// Reference to sectors_type
std::vector<uint32_t>& sectors_type_ref = *sectors_type;
// Seek to the begin
in_file.seekg(0, std::ios_base::beg);
// Stream processing
for (uint32_t i = 0; i < streams_script.size(); i++) {
// Compressor object
compressor *compobj = NULL;
// Buffer object
uint8_t *comp_buffer = NULL;
// Initialize the compressor and the buffer if required
if (streams_script[i].stream_data.compression) {
// Set compression level with extreme option if compression is LZMA
int32_t compression_option = options->compression_level;
if (options->extreme_compression) {
if ((sector_tools_compression)streams_script[i].stream_data.compression == C_LZMA) {
compression_option |= LZMA_PRESET_EXTREME;
}
else if ((sector_tools_compression)streams_script[i].stream_data.compression == C_FLAC) {
compression_option |= FLACZLIB_EXTREME_COMPRESSION;
}
}
compobj = new compressor(
(sector_tools_compression)streams_script[i].stream_data.compression,
true,
compression_option
);
// Initialize the compressor buffer
comp_buffer = (uint8_t*) malloc(BUFFER_SIZE);
if(!comp_buffer) {
fprintf(stderr, "Out of memory\n");
return ECMTOOL_BUFFER_MEMORY_ERROR;
}
// Set the compressor buffer as output
size_t output_size = BUFFER_SIZE;
compobj -> set_output(comp_buffer, output_size);
}
// Walk through all the sector types in stream
for (uint32_t j = 0; j < streams_script[i].sectors_data.size(); j++) {
// Process the number of sectors of every type
for (uint32_t k = 0; k < streams_script[i].sectors_data[j].sector_count; k++) {
if (in_file.eof()){
fprintf(stderr, "Unexpected EOF detected.\n");
return ECMTOOL_FILE_READ_ERROR;
}
in_file.read(reinterpret_cast<char*>(in_sector), 2352);
// Compute the crc of the readed data
input_edc = sTools->edc_compute(
input_edc,
in_sector,
2352
);
// Current sector
uint32_t current_sector = in_file.tellg() / 2352;
// We will clean the sector to keep only the data that we want
uint16_t output_size = 0;
int8_t res = sTools->clean_sector(
out_sector,
in_sector,
(sector_tools_types)streams_script[i].sectors_data[j].mode,
output_size,
options->optimizations
);
if (res) {
fprintf(stderr, "There was an error cleaning the sector\n");
return ECMTOOL_PROCESSING_ERROR;
}
sectors_type_ref[streams_script[i].sectors_data[j].mode]++;
// Compress the sector using the selected compression (or none)
switch (streams_script[i].stream_data.compression) {
// No compression
case C_NONE:
out_file.write(reinterpret_cast<char*>(out_sector), output_size);
if (!out_file.good()) {
fprintf(stderr, "\nThere was an error writting the output file");
return ECMTOOL_FILE_WRITE_ERROR;
}
break;
// Zlib compression
case C_ZLIB:
case C_LZMA:
case C_LZ4:
case C_FLAC:
size_t compress_buffer_left = 0;
// Current sector is the last stream sector
if (current_sector == streams_script[i].stream_data.end_sector) {
res = compobj -> compress(compress_buffer_left, out_sector, output_size, Z_FINISH);
}
else if (options->seekable && (options->sectors_per_block == 1 || !((current_sector + 1) % options->sectors_per_block))) {
// A new compressor block is required
res = compobj -> compress(compress_buffer_left, out_sector, output_size, Z_FULL_FLUSH);
}
else {
res = compobj -> compress(compress_buffer_left, out_sector, output_size, Z_NO_FLUSH);
}
if (res != 0) {
fprintf(stderr, "There was an error compressing the stream: %d.\n", res);