-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcyanrip_main.c
2286 lines (1947 loc) · 80.6 KB
/
cyanrip_main.c
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 cyanrip.
*
* cyanrip is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* cyanrip 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with cyanrip; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <time.h>
#include <getopt.h>
#include <sys/stat.h>
#ifdef _WIN32
#include <locale.h>
#endif
#include <libavutil/bprint.h>
#include <libavutil/avstring.h>
#include <libavutil/time.h>
#include "cyanrip_main.h"
#include "cyanrip_log.h"
#include "cue_writer.h"
#include "checksums.h"
#include "discid.h"
#include "musicbrainz.h"
#include "coverart.h"
#include "accurip.h"
#include "os_compat.h"
#include "cyanrip_encode.h"
int quit_now = 0;
const cyanrip_out_fmt crip_fmt_info[] = {
[CYANRIP_FORMAT_FLAC] = { "flac", "FLAC", "flac", "flac", 1, 11, 1, AV_CODEC_ID_FLAC, },
[CYANRIP_FORMAT_MP3] = { "mp3", "MP3", "mp3", "mp3", 1, 0, 0, AV_CODEC_ID_MP3, },
[CYANRIP_FORMAT_TTA] = { "tta", "TTA", "tta", "tta", 0, 0, 1, AV_CODEC_ID_TTA, },
[CYANRIP_FORMAT_OPUS] = { "opus", "OPUS", "opus", "ogg", 0, 10, 0, AV_CODEC_ID_OPUS, },
[CYANRIP_FORMAT_AAC] = { "aac", "AAC", "m4a", "adts", 0, 0, 0, AV_CODEC_ID_AAC, },
[CYANRIP_FORMAT_AAC_MP4] = { "aac_mp4", "AAC", "mp4", "mp4", 1, 0, 0, AV_CODEC_ID_AAC, },
[CYANRIP_FORMAT_WAVPACK] = { "wavpack", "WV", "wv", "wv", 0, 3, 1, AV_CODEC_ID_WAVPACK, },
[CYANRIP_FORMAT_VORBIS] = { "vorbis", "OGG", "ogg", "ogg", 0, 0, 0, AV_CODEC_ID_VORBIS, },
[CYANRIP_FORMAT_ALAC] = { "alac", "ALAC", "m4a", "ipod", 0, 2, 1, AV_CODEC_ID_ALAC, },
[CYANRIP_FORMAT_WAV] = { "wav", "WAV", "wav", "wav", 0, 0, 1, AV_CODEC_ID_NONE, },
[CYANRIP_FORMAT_OPUS_MP4] = { "opus_mp4", "OPUS", "mp4", "mp4", 1, 10, 0, AV_CODEC_ID_OPUS, },
[CYANRIP_FORMAT_PCM] = { "pcm", "PCM", "pcm", "s16le", 0, 0, 1, AV_CODEC_ID_NONE, },
};
static void free_track(cyanrip_ctx *ctx, cyanrip_track *t)
{
for (int i = 0; i < ctx->settings.outputs_num; i++)
cyanrip_end_track_encoding(&t->enc_ctx[i]);
cyanrip_free_dec_ctx(ctx, &t->dec_ctx);
crip_free_art(&t->art);
av_dict_free(&t->meta);
av_free(t->ar_db_entries);
}
static void cyanrip_ctx_end(cyanrip_ctx **s)
{
cyanrip_ctx *ctx;
if (!s || !*s)
return;
ctx = *s;
for (int i = 0; i < ctx->nb_tracks; i++)
free_track(ctx, &ctx->tracks[i]);
for (int i = 0; i < ctx->nb_cover_arts; i++)
crip_free_art(&ctx->cover_arts[i]);
cyanrip_finalize_ebur128(ctx, 0);
av_free(ctx->mb_submission_url);
if (ctx->paranoia)
cdio_paranoia_free(ctx->paranoia);
if (ctx->drive)
cdio_cddap_close_no_free_cdio(ctx->drive);
if (ctx->settings.eject_on_success_rip && !ctx->total_error_count &&
(ctx->mcap & CDIO_DRIVE_CAP_MISC_EJECT) && ctx->cdio && !quit_now)
cdio_eject_media(&ctx->cdio);
else if (ctx->cdio)
cdio_destroy(ctx->cdio);
free(ctx->settings.dev_path);
av_dict_free(&ctx->meta);
av_freep(&ctx);
*s = NULL;
}
static const paranoia_mode_t paranoia_level_map[] = {
[0] = PARANOIA_MODE_DISABLE, /* Disable everything */
[1] = PARANOIA_MODE_OVERLAP, /* Perform overlapped reads */
[2] = PARANOIA_MODE_OVERLAP | PARANOIA_MODE_VERIFY, /* Perform and verify overlapped reads */
[3] = PARANOIA_MODE_FULL ^ PARANOIA_MODE_NEVERSKIP, /* Maximum, but do allow skipping sectors */
};
const int crip_max_paranoia_level = (sizeof(paranoia_level_map) / sizeof(paranoia_level_map[0])) - 1;
static int cyanrip_ctx_init(cyanrip_ctx **s, cyanrip_settings *settings)
{
cyanrip_ctx *ctx = av_mallocz(sizeof(cyanrip_ctx));
memcpy(&ctx->settings, settings, sizeof(cyanrip_settings));
if (ctx->settings.print_info_only)
ctx->settings.eject_on_success_rip = 0;
cdio_init();
if (!ctx->settings.dev_path)
ctx->settings.dev_path = cdio_get_default_device(NULL);
if (!(ctx->cdio = cdio_open(ctx->settings.dev_path, DRIVER_UNKNOWN))) {
cyanrip_log(ctx, 0, "Unable to init cdio context\n");
return AVERROR(EINVAL);
}
cdio_get_drive_cap(ctx->cdio, &ctx->rcap, &ctx->wcap, &ctx->mcap);
char *msg = NULL;
if (!(ctx->drive = cdio_cddap_identify_cdio(ctx->cdio, CDDA_MESSAGE_LOGIT, &msg))) {
cyanrip_log(ctx, 0, "Unable to init cddap context!\n");
if (msg) {
cyanrip_log(ctx, 0, "cdio: \"%s\"\n", msg);
cdio_cddap_free_messages(msg);
}
return AVERROR(EINVAL);
}
if (msg) {
cyanrip_log(ctx, 0, "%s\n", msg);
cdio_cddap_free_messages(msg);
}
cyanrip_log(ctx, 0, "Opening drive...\n");
int ret = cdio_cddap_open(ctx->drive);
if (ret < 0) {
cyanrip_log(ctx, 0, "Unable to open device!\n");
cyanrip_ctx_end(&ctx);
return AVERROR(EINVAL);
}
cdio_cddap_verbose_set(ctx->drive, CDDA_MESSAGE_LOGIT, CDDA_MESSAGE_FORGETIT);
if (settings->speed) {
if (!(ctx->mcap & CDIO_DRIVE_CAP_MISC_SELECT_SPEED)) {
cyanrip_log(ctx, 0, "Device does not support changing speeds!\n");
cyanrip_ctx_end(&ctx);
return AVERROR(EINVAL);
}
ret = cdio_cddap_speed_set(ctx->drive, settings->speed);
msg = cdio_cddap_errors(ctx->drive);
if (msg) {
cyanrip_log(ctx, 0, "cdio error: %s\n", msg);
cdio_cddap_free_messages(msg);
}
if (ret)
return AVERROR(EINVAL);
}
ctx->paranoia = cdio_paranoia_init(ctx->drive);
if (!ctx->paranoia) {
cyanrip_log(ctx, 0, "Unable to init paranoia!\n");
cyanrip_ctx_end(&ctx);
return AVERROR(EINVAL);
}
cdio_paranoia_modeset(ctx->paranoia, paranoia_level_map[settings->paranoia_level]);
ctx->start_lsn = 0;
ctx->end_lsn = cdio_get_track_lsn(ctx->cdio, CDIO_CDROM_LEADOUT_TRACK) - 1;
ctx->duration_frames = ctx->end_lsn - ctx->start_lsn + 1;
ctx->nb_tracks = ctx->nb_cd_tracks = cdio_cddap_tracks(ctx->drive);
if ((ctx->nb_tracks < 1) || (ctx->nb_tracks > CDIO_CD_MAX_TRACKS)) {
cyanrip_log(ctx, 0, "Invalid number of tracks: %i!\n", ctx->nb_tracks);
ctx->nb_tracks = 0;
cyanrip_ctx_end(&ctx);
return AVERROR(EINVAL);
}
int first_track_nb = cdio_get_first_track_num(ctx->cdio);
for (int i = 0; i < ctx->nb_cd_tracks; i++) {
cyanrip_track *t = &ctx->tracks[i];
t->index = i + 1;
t->number = t->cd_track_number = i + first_track_nb;
t->track_is_data = !cdio_cddap_track_audiop(ctx->drive, t->number);
t->pregap_lsn = cdio_get_track_pregap_lsn(ctx->cdio, t->number);
t->dropped_pregap_start = CDIO_INVALID_LSN;
t->merged_pregap_end = CDIO_INVALID_LSN;
t->start_lsn = cdio_get_track_lsn(ctx->cdio, t->number);
t->end_lsn = cdio_get_track_last_lsn(ctx->cdio, t->number);
t->start_lsn_sig = t->start_lsn;
t->end_lsn_sig = t->end_lsn;
if (t->track_is_data) {
if (ctx->settings.pregap_action[t->number - 1] == CYANRIP_PREGAP_DEFAULT)
ctx->settings.pregap_action[t->number - 1] = CYANRIP_PREGAP_DROP;
if (ctx->settings.pregap_action[t->number - 0] == CYANRIP_PREGAP_DEFAULT)
ctx->settings.pregap_action[t->number - 0] = CYANRIP_PREGAP_DROP;
if (i == (ctx->nb_cd_tracks - 1)) {
ctx->tracks[i - 1].end_lsn -= 11400;
t->pregap_lsn = ctx->tracks[i - 1].end_lsn + 1;
}
}
}
for (int i = 0; i < ctx->nb_cd_tracks; i++) {
cyanrip_track *t = &ctx->tracks[i];
if (t->track_is_data)
continue;
t->acurip_track_is_first = 1;
break;
}
for (int i = ctx->nb_cd_tracks - 1; i >= 0; i--) {
cyanrip_track *t = &ctx->tracks[i];
if (t->track_is_data)
continue;
t->acurip_track_is_last = 1;
break;
}
/* For hot removal detection - init this so we can detect changes */
cdio_get_media_changed(ctx->cdio);
*s = ctx;
return 0;
}
#define REPLAYGAIN_REF_LOUDNESS (-18.0)
static int crip_replaygain_meta_track(cyanrip_ctx *ctx, cyanrip_track *t)
{
char temp[32];
snprintf(temp, sizeof(temp), "%.2f dB", REPLAYGAIN_REF_LOUDNESS - t->ebu_integrated);
av_dict_set(&t->meta, "REPLAYGAIN_TRACK_GAIN", temp, 0);
av_dict_set_int(&t->meta, "R128_TRACK_GAIN", lrintf((REPLAYGAIN_REF_LOUDNESS - t->ebu_integrated + 5) * 256), 0);
snprintf(temp, sizeof(temp), "%.2f dB", t->ebu_range);
av_dict_set(&t->meta, "REPLAYGAIN_TRACK_RANGE", temp, 0);
snprintf(temp, sizeof(temp), "%.6f", powf(10, t->ebu_true_peak / 20.0));
av_dict_set(&t->meta, "REPLAYGAIN_TRACK_PEAK", temp, 0);
snprintf(temp, sizeof(temp), "%.2f LUFS", REPLAYGAIN_REF_LOUDNESS);
av_dict_set(&t->meta, "REPLAYGAIN_REFERENCE_LOUDNESS", temp, 0);
return 0;
}
static int crip_replaygain_meta_album(cyanrip_ctx *ctx)
{
char temp[32];
for (int i = 0; i < ctx->nb_cd_tracks; i++) {
cyanrip_track *t = &ctx->tracks[i];
snprintf(temp, sizeof(temp), "%.2f dB", REPLAYGAIN_REF_LOUDNESS - ctx->ebu_integrated);
av_dict_set(&t->meta, "REPLAYGAIN_ALBUM_GAIN", temp, 0);
av_dict_set_int(&t->meta, "R128_ALBUM_GAIN", lrintf((REPLAYGAIN_REF_LOUDNESS - ctx->ebu_integrated + 5) * 256), 0);
snprintf(temp, sizeof(temp), "%.2f dB", ctx->ebu_range);
av_dict_set(&t->meta, "REPLAYGAIN_ALBUM_RANGE", temp, 0);
snprintf(temp, sizeof(temp), "%.6f", powf(10, ctx->ebu_true_peak / 20.0));
av_dict_set(&t->meta, "REPLAYGAIN_ALBUM_PEAK", temp, 0);
}
return 0;
}
static void crip_fill_mcn(cyanrip_ctx *ctx)
{
/* Get disc MCN */
if (ctx->rcap & CDIO_DRIVE_CAP_READ_MCN) {
const char *mcn = cdio_get_mcn(ctx->cdio);
if (mcn) {
if (strlen(mcn))
av_dict_set(&ctx->meta, "disc_mcn", mcn, 0);
cdio_free((void *)mcn);
}
}
}
static void track_set_creation_time(cyanrip_ctx *ctx, cyanrip_track *t)
{
if (dict_get(t->meta, "creation_time"))
return;
char t_s[64];
time_t t_c = time(NULL);
struct tm *t_l = localtime(&t_c);
strftime(t_s, sizeof(t_s), "%Y-%m-%dT%H:%M:%S", t_l);
av_dict_set(&t->meta, "creation_time", t_s, 0);
}
static void copy_album_to_track_meta(cyanrip_ctx *ctx)
{
for (int i = 0; i < ctx->nb_tracks; i++) {
av_dict_set_int(&ctx->tracks[i].meta, "track", ctx->tracks[i].number, 0);
av_dict_set_int(&ctx->tracks[i].meta, "tracktotal", ctx->nb_tracks, 0);
av_dict_copy(&ctx->tracks[i].meta, ctx->meta, AV_DICT_DONT_OVERWRITE);
}
}
static const uint8_t silent_frame[CDIO_CD_FRAMESIZE_RAW] = { 0 };
uint64_t paranoia_status[PARANOIA_CB_FINISHED + 1] = { 0 };
static void status_cb(long int n, paranoia_cb_mode_t status)
{
if (status >= PARANOIA_CB_READ && status <= PARANOIA_CB_FINISHED)
paranoia_status[status]++;
}
static const uint8_t *cyanrip_read_frame(cyanrip_ctx *ctx)
{
int err = 0;
char *msg = NULL;
const uint8_t *data;
data = (void *)cdio_paranoia_read_limited(ctx->paranoia, &status_cb,
ctx->settings.max_retries);
msg = cdio_cddap_errors(ctx->drive);
if (msg) {
cyanrip_log(ctx, 0, "\ncdio error: %s\n", msg);
cdio_cddap_free_messages(msg);
err = 1;
}
if (!data) {
if (!msg) {
cyanrip_log(ctx, 0, "\nFrame read failed!\n");
err = 1;
}
data = silent_frame;
}
ctx->total_error_count += err;
return data;
}
static int search_for_offset(cyanrip_track *t, int *offset_found,
const uint8_t *mem, int dir,
int guess, int bytes)
{
if (guess) {
const uint8_t *start_addr = mem + guess*4;
uint32_t accurip_v1 = 0x0;
for (int j = 0; j < (CDIO_CD_FRAMESIZE_RAW >> 2); j++)
accurip_v1 += AV_RL32(&start_addr[j*4]) * (j + 1);
if (crip_find_ar(t, accurip_v1, 1) == t->ar_db_max_confidence && accurip_v1) {
*offset_found = guess;
return 1;
}
}
for (int byte_off = ((dir < 0) * 4); byte_off < bytes; byte_off += 4) {
if (quit_now)
return 0;
int offset = dir * (byte_off >> 2);
if (guess == offset)
continue;
const uint8_t *start_addr = mem + dir * byte_off;
uint32_t accurip_v1 = 0x0;
for (int j = 0; j < (CDIO_CD_FRAMESIZE_RAW >> 2); j++)
accurip_v1 += AV_RL32(&start_addr[j*4]) * (j + 1);
if (crip_find_ar(t, accurip_v1, 1) == t->ar_db_max_confidence && accurip_v1) {
*offset_found = offset;
return 1;
}
}
return 0;
}
static void search_for_drive_offset(cyanrip_ctx *ctx, int range)
{
int had_ar = 0, did_check = 0;
int offset_found = 0, offset_found_samples = 0;
uint8_t *mem = av_malloc(2 * range * CDIO_CD_FRAMESIZE_RAW);
if (ctx->ar_db_status != CYANRIP_ACCUDB_FOUND)
goto end;
for (int t_idx = 0; t_idx < ctx->nb_tracks; t_idx++) {
cyanrip_track *t = &ctx->tracks[t_idx];
lsn_t start = cdio_get_track_lsn(ctx->cdio, t_idx + 1);
lsn_t end = cdio_get_track_last_lsn(ctx->cdio, t_idx + 1);
if (ctx->tracks[t_idx].ar_db_status != CYANRIP_ACCUDB_FOUND)
continue;
else
had_ar |= 1;
if ((end - start) < (450 + range))
continue;
did_check |= 1;
/* Set start/end ranges */
start += 450 - range;
end = start + 2*range;
size_t bytes = 0;
cyanrip_log(ctx, 0, "Loading data for track %i...\n", t_idx + 1);
cdio_paranoia_seek(ctx->paranoia, start, SEEK_SET);
for (int i = 0; i < 2*range; i++) {
const uint8_t *data = cyanrip_read_frame(ctx);
memcpy(mem + bytes, data, CDIO_CD_FRAMESIZE_RAW);
bytes += CDIO_CD_FRAMESIZE_RAW;
if (quit_now) {
cyanrip_log(ctx, 0, "Stopping, offset finding incomplete!\n");
goto end;
}
}
int found, offset;
int dir = (offset_found && (offset_found_samples < 0)) ? -1 : +1;
cyanrip_log(ctx, 0, "Data loaded, searching for offsets...\n");
found = search_for_offset(t, &offset, mem + (bytes >> 1), dir, offset_found_samples,
range * CDIO_CD_FRAMESIZE_RAW);
if (!found)
found = search_for_offset(t, &offset, mem + (bytes >> 1), -dir, 0,
range * CDIO_CD_FRAMESIZE_RAW);
if (!found) {
cyanrip_log(ctx, 0, "Nothing found for track %i%s\n", t_idx + 1,
t_idx != (ctx->nb_tracks - 1) ? ", trying another track" : "");
} else if (!offset_found) {
offset_found_samples = offset;
offset_found++;
cyanrip_log(ctx, 0, "Offset of %c%i found in track %i%s\n",
offset >= 0 ? '+' : '-', abs(offset), t_idx + 1,
t_idx != (ctx->nb_tracks - 1) ? ", trying to confirm with another track" : "");
} else if (offset_found_samples == offset) {
offset_found++;
cyanrip_log(ctx, 0, "Offset of %c%i confirmed (confidence: %i) in track %i%s\n",
offset >= 0 ? '+' : '-', abs(offset), offset_found, t_idx + 1,
t_idx != (ctx->nb_tracks - 1) ? ", trying to confirm with another track" : "");
} else {
cyanrip_log(ctx, 0, "New offset of %c%i found at track %i, scrapping old offset of %c%i%s\n",
offset >= 0 ? '+' : '-', abs(offset), t_idx + 1,
offset_found_samples >= 0 ? '+' : '-', abs(offset_found_samples),
t_idx != (ctx->nb_tracks - 1) ? ", trying to confirm with another track" : "");
offset_found_samples = offset;
offset_found = 1;
}
}
end:
av_free(mem);
if (!offset_found) {
if (!had_ar) {
cyanrip_log(ctx, 0, "No track had AccuRip entry, cannot find offset!\n");
} else if (had_ar && !did_check) {
cyanrip_log(ctx, 0, "No track was long enough, unable to find drive offset!\n");
} else {
cyanrip_log(ctx, 0, "Was not able to find drive offset with a radius of %i frames"
", trying again with a larger radius...\n", range);
search_for_drive_offset(ctx, 2*range);
}
return;
} else {
cyanrip_log(ctx, 0, "Drive offset of %c%i found (confidence: %i)!\n",
offset_found_samples >= 0 ? '+' : '-', abs(offset_found_samples), offset_found);
}
}
static void track_read_extra(cyanrip_ctx *ctx, cyanrip_track *t)
{
if (!t->track_is_data) {
/* ISRC code */
if (!ctx->disregard_cd_isrc && (ctx->rcap & CDIO_DRIVE_CAP_READ_ISRC) && !dict_get(t->meta, "isrc")) {
const char *isrc_str = cdio_get_track_isrc(ctx->cdio, t->cd_track_number);
if (isrc_str) {
if (strlen(isrc_str))
av_dict_set(&t->meta, "isrc", isrc_str, 0);
else
ctx->disregard_cd_isrc = 1;
cdio_free((void *)isrc_str);
} else {
ctx->disregard_cd_isrc = 1;
}
}
/* TOC preemphasis flag*/
t->preemphasis = cdio_cddap_track_preemp(ctx->drive, t->cd_track_number);
/* Subcode preemphasis flag */
if (!t->preemphasis && (ctx->rcap & CDIO_DRIVE_CAP_READ_ISRC)) {
cdio_subchannel_t subchannel_data = { 0 };
driver_return_code_t ret = cdio_audio_read_subchannel(ctx->cdio, &subchannel_data);
if (ret != DRIVER_OP_SUCCESS) {
cyanrip_log(ctx, 0, "Unable to read track %i subchannel info!\n", t->number);
} else {
t->preemphasis = t->preemphasis_in_subcode = subchannel_data.control & 0x01;
}
}
}
}
static int cyanrip_rip_track(cyanrip_ctx *ctx, cyanrip_track *t)
{
int ret = 0;
int line_len = 0;
int max_line_len = 0;
char line[4096];
if (t->track_is_data) {
cyanrip_log(ctx, 0, "Track %i is data:\n", t->number);
cyanrip_log_track_end(ctx, t);
cyanrip_cue_track(ctx, t);
return 0;
}
/* Hopefully reduce seeking by reading this here */
track_read_extra(ctx, t);
/* Set creation time at the start of ripping */
track_set_creation_time(ctx, t);
uint32_t start_frames_read;
uint32_t *last_checksums = NULL;
uint32_t nb_last_checksums = 0;
uint32_t repeat_mode_encode = 0;
uint32_t total_repeats = 0;
int calc_global_peak_set = 0;
int calc_global_peak = !ctx->settings.ripping_retries;
repeat_ripping:;
const int frames_before_disc_start = t->frames_before_disc_start;
const int frames = t->frames;
const int frames_after_disc_end = t->frames_after_disc_end;
const ptrdiff_t offs = t->partial_frame_byte_offs;
start_frames_read = ctx->frames_read;
cdio_paranoia_seek(ctx->paranoia, t->start_lsn, SEEK_SET);
int start_err = ctx->total_error_count;
/* Checksum */
cyanrip_checksum_ctx checksum_ctx;
crip_init_checksum_ctx(ctx, &checksum_ctx, t);
/* Fill with silence to maintain track length */
for (int i = 0; i < frames_before_disc_start; i++) {
int bytes = CDIO_CD_FRAMESIZE_RAW;
const uint8_t *data = silent_frame;
if (!i && offs) {
data += CDIO_CD_FRAMESIZE_RAW + offs;
bytes = -offs;
}
crip_process_checksums(&checksum_ctx, data, bytes);
if (!ctx->settings.ripping_retries || repeat_mode_encode) {
ret = cyanrip_send_pcm_to_encoders(ctx, t->enc_ctx, ctx->settings.outputs_num,
t->dec_ctx, data, bytes, calc_global_peak);
if (ret) {
cyanrip_log(ctx, 0, "Error in decoding/sending frame: %s\n", av_err2str(ret));
goto fail;
}
}
}
int64_t frame_last_read = av_gettime_relative();
/* Read the actual CD data */
for (int i = 0; i < frames; i++) {
/* Detect disc removals */
if (cdio_get_media_changed(ctx->cdio)) {
cyanrip_log(ctx, 0, "\nDrive media changed, stopping!\n");
ret = AVERROR(EINVAL);
goto fail;
}
/* Flush paranoia cache if overreading into lead-out - no idea why */
if ((t->start_lsn + i) > ctx->end_lsn)
cdio_paranoia_seek(ctx->paranoia, t->start_lsn + i, SEEK_SET);
int bytes = CDIO_CD_FRAMESIZE_RAW;
const uint8_t *data = cyanrip_read_frame(ctx);
/* Account for partial frames caused by the offset */
if (offs > 0) {
if (!i) {
data += offs;
bytes -= offs;
} else if ((i == (frames - 1)) && !frames_after_disc_end) {
bytes = offs;
}
} else if (offs < 0) {
if (!i && !frames_before_disc_start) {
data += CDIO_CD_FRAMESIZE_RAW + offs;
bytes = -offs;
} else if (i == (frames - 1)) {
bytes += offs;
}
}
/* Stop now if requested */
if (quit_now) {
cyanrip_log(ctx, 0, "\nStopping, ripping incomplete!\n");
break;
}
/* Update checksums */
crip_process_checksums(&checksum_ctx, data, bytes);
/* Decode and encode */
if (!ctx->settings.ripping_retries || repeat_mode_encode) {
ret = cyanrip_send_pcm_to_encoders(ctx, t->enc_ctx, ctx->settings.outputs_num,
t->dec_ctx, data, bytes, calc_global_peak);
if (ret < 0) {
cyanrip_log(ctx, 0, "\nError in decoding/sending frame: %s\n", av_err2str(ret));
goto fail;
}
}
if (line_len > 0) {
cyanrip_log(NULL, 0, "\r", line);
line_len = 0;
}
/* Report progress */
line_len += snprintf(line, sizeof(line),
"Ripping%strack %i, progress - %0.2f%%",
(!ctx->settings.ripping_retries || repeat_mode_encode) ? " and encoding " : " ",
t->number, ((double)(i + 1)/frames)*100.0f);
ctx->frames_read++;
int64_t cur_time = av_gettime_relative();
int64_t frame_diff = cur_time - frame_last_read;
frame_last_read = cur_time;
int64_t diff = cr_sliding_win(&ctx->eta_ctx, frame_diff, cur_time,
av_make_q(1, 1000000),
1000000LL * 1200LL, 1);
int64_t seconds = (ctx->frames_to_read - ctx->frames_read) * diff;
int hours = 0;
while (seconds >= (3600LL * 1000000LL)) {
seconds -= (3600LL * 1000000LL);
hours++;
}
int minutes = 0;
while (seconds >= (60LL * 1000000LL)) {
seconds -= (60LL * 1000000LL);
minutes++;
}
seconds = av_rescale(seconds, 1, 1000000);
if (seconds == 60) {
minutes++;
seconds = 0;
}
if (minutes == 60) {
hours++;
minutes = 0;
}
if (hours)
line_len += snprintf(line + line_len, sizeof(line) - line_len,
", ETA - %ih %im", hours, minutes);
else if (minutes)
line_len += snprintf(line + line_len, sizeof(line) - line_len,
", ETA - %im", minutes);
else
line_len += snprintf(line + line_len, sizeof(line) - line_len,
", ETA - %" PRId64 "s", seconds);
if (ctx->total_error_count - start_err)
line_len += snprintf(line + line_len, sizeof(line) - line_len,
", errors - %i", ctx->total_error_count - start_err);
max_line_len = FFMAX(line_len, max_line_len);
if (line_len < max_line_len) {
for (int c = line_len; c < max_line_len; c++)
line_len += snprintf(line + line_len, sizeof(line) - line_len, " ");
}
cyanrip_log(NULL, 0, "%s", line);
}
/* Fill with silence to maintain track length */
for (int i = 0; i < frames_after_disc_end; i++) {
int bytes = CDIO_CD_FRAMESIZE_RAW;
const uint8_t *data = silent_frame;
if ((i == (frames_after_disc_end - 1)) && offs)
bytes = offs;
crip_process_checksums(&checksum_ctx, data, bytes);
if (!ctx->settings.ripping_retries || repeat_mode_encode) {
ret = cyanrip_send_pcm_to_encoders(ctx, t->enc_ctx, ctx->settings.outputs_num,
t->dec_ctx, data, bytes, calc_global_peak);
if (ret < 0) {
cyanrip_log(ctx, 0, "Error in decoding/sending frame: %s\n", av_err2str(ret));
goto fail;
}
}
}
calc_global_peak = 0;
crip_finalize_checksums(&checksum_ctx, t);
if (ctx->settings.ripping_retries) {
int matches = 0;
for (int i = 0; i < nb_last_checksums; i++)
matches += last_checksums[i] == checksum_ctx.eac_crc;
total_repeats++;
if (matches >= ctx->settings.ripping_retries) {
cyanrip_log(ctx, 0, "\nDone; (%i out of %i matches for current checksum %08X)\n",
matches, ctx->settings.ripping_retries, checksum_ctx.eac_crc);
goto finalize_ripping;
}
if (total_repeats >= ctx->settings.max_retries) {
cyanrip_log(ctx, 0, "\nDone; (no matches found, but hit repeat limit of %i)\n",
ctx->settings.max_retries);
goto finalize_ripping;
}
/* If the next match may be the last one, start encoding */
if ((matches + 1) >= ctx->settings.ripping_retries ||
(total_repeats + 1) >= ctx->settings.max_retries) {
repeat_mode_encode = 1;
if (!calc_global_peak_set) {
calc_global_peak_set = 1;
calc_global_peak = 1;
}
}
cyanrip_log(ctx, 0, "\nRepeating ripping (%i out of %i matches for current checksum %08X)\n",
matches, ctx->settings.ripping_retries, checksum_ctx.eac_crc);
last_checksums = av_realloc(last_checksums,
(nb_last_checksums + 1)*sizeof(*last_checksums));
if (!last_checksums) {
ret = AVERROR(ENOMEM);
goto end;
}
last_checksums[nb_last_checksums] = checksum_ctx.eac_crc;
nb_last_checksums++;
int err = cyanrip_reset_encoding(ctx, t);
if (err < 0) {
cyanrip_log(ctx, 0, "Error in encoding: %s\n", av_err2str(err));
ret = err;
goto end;
}
ctx->frames_read = start_frames_read;
goto repeat_ripping;
}
finalize_ripping:
cyanrip_log(NULL, 0, "\nFlushing encoders...\n");
/* Flush encoders */
ret = cyanrip_send_pcm_to_encoders(ctx, t->enc_ctx, ctx->settings.outputs_num,
t->dec_ctx, NULL, 0, 0);
if (ret) {
cyanrip_log(ctx, 0, "Error sending flush signal to encoders: %s\n", av_err2str(ret));
return ret;
}
fail:
if (!ret && !quit_now)
cyanrip_log(ctx, 0, "Track %i ripped and encoded successfully!\n", t->number);
end:
av_free(last_checksums);
t->total_repeats = total_repeats;
if (!ret) {
cyanrip_finalize_encoding(ctx, t);
if (ctx->settings.enable_replaygain)
crip_replaygain_meta_track(ctx, t);
cyanrip_log_track_end(ctx, t);
cyanrip_cue_track(ctx, t);
} else {
ctx->total_error_count++;
}
return ret;
}
static void on_quit_signal(int signo)
{
if (quit_now) {
cyanrip_log(NULL, 0, "Force quitting\n");
exit(1);
}
cyanrip_log(NULL, 0, "\r\nTrying to quit\n");
quit_now = 1;
}
static void setup_track_lsn(cyanrip_ctx *ctx, cyanrip_track *t)
{
lsn_t first_frame = t->start_lsn;
lsn_t last_frame = t->end_lsn;
/* Duration doesn't depend on adjustments we make to frames */
int frames = last_frame - first_frame + 1;
t->nb_samples = frames*(CDIO_CD_FRAMESIZE_RAW >> 2);
/* Move the seek position coarsely */
const int extra_frames = ctx->settings.over_under_read_frames;
int sign = (extra_frames < 0) ? -1 : ((extra_frames > 0) ? +1 : 0);
first_frame += sign*FFMAX(FFABS(extra_frames) - 1, 0);
last_frame += sign*FFMAX(FFABS(extra_frames) - 1, 0);
/* Bump the lower/higher frame in the offset direction */
first_frame -= sign < 0;
last_frame += sign > 0;
/* Don't read into the lead in/out */
if (!ctx->settings.overread_leadinout) {
t->frames_before_disc_start = FFMAX(ctx->start_lsn - first_frame, 0);
t->frames_after_disc_end = FFMAX(last_frame - ctx->end_lsn, 0);
first_frame += t->frames_before_disc_start;
last_frame -= t->frames_after_disc_end;
} else {
t->frames_before_disc_start = 0;
t->frames_after_disc_end = 0;
}
/* Offset accounted start/end sectors */
t->start_lsn = first_frame;
t->end_lsn = last_frame;
t->frames = last_frame - first_frame + 1;
/* Last/first frame partial offset */
ptrdiff_t offs = ctx->settings.offset*4;
offs -= sign*FFMAX(FFABS(extra_frames) - 1, 0)*CDIO_CD_FRAMESIZE_RAW;
t->partial_frame_byte_offs = offs;
}
static void setup_track_offsets_and_report(cyanrip_ctx *ctx)
{
int gaps = 0;
cyanrip_log(ctx, 0, "Gaps:\n");
/* Before pregap */
if (ctx->tracks[0].pregap_lsn != CDIO_INVALID_LSN &&
ctx->tracks[0].pregap_lsn > ctx->start_lsn) {
cyanrip_log(ctx, 0, " %i frame gap between lead-in and track 1 pregap, merging into pregap\n",
ctx->tracks[0].pregap_lsn - ctx->start_lsn);
gaps++;
ctx->tracks[0].pregap_lsn = ctx->start_lsn;
} else if (ctx->tracks[0].pregap_lsn == CDIO_INVALID_LSN &&
ctx->tracks[0].start_lsn > ctx->start_lsn) {
cyanrip_log(ctx, 0, " %i frame unmarked gap between lead-in and track 1, marking as a pregap\n",
ctx->tracks[0].start_lsn - ctx->start_lsn);
gaps++;
ctx->tracks[0].pregap_lsn = ctx->start_lsn;
}
/* Pregaps */
for (int i = 0; i < ctx->nb_tracks; i++) {
cyanrip_track *ct = &ctx->tracks[i - 0];
cyanrip_track *lt = ct->number > 1 ? &ctx->tracks[i - 1] : NULL;
if (ct->pregap_lsn == CDIO_INVALID_LSN)
continue;
cyanrip_log(ctx, 0, " %i frame pregap in track %i, ",
ct->start_lsn - ct->pregap_lsn, ct->number);
gaps++;
switch (ctx->settings.pregap_action[ct->number - 1]) {
case CYANRIP_PREGAP_DEFAULT:
if (!lt)
cyanrip_log(ctx, 0, "unmerged\n");
else
cyanrip_log(ctx, 0, "merging into track %i\n", lt->number);
if ((ct->number - 1) == 0)
ct->dropped_pregap_start = ct->pregap_lsn;
break;
case CYANRIP_PREGAP_DROP:
cyanrip_log(ctx, 0, "dropping\n");
ct->dropped_pregap_start = ct->pregap_lsn;
if (lt)
lt->end_lsn = ct->pregap_lsn - 1;
break;
case CYANRIP_PREGAP_MERGE:
cyanrip_log(ctx, 0, "merging\n");
ct->merged_pregap_end = ct->start_lsn;
ct->start_lsn = ct->pregap_lsn;
if (lt)
lt->end_lsn = ct->pregap_lsn - 1;
break;
case CYANRIP_PREGAP_TRACK:
cyanrip_log(ctx, 0, "splitting off into a new track, number %i\n", ct->number > 1 ? ct->number : 0);
if (lt)
lt->end_lsn = ct->pregap_lsn - 1;
if (ct->number > 1) /* Push all track numbers up if needed */
for (int j = i; j < ctx->nb_tracks; j++)
ctx->tracks[j].number++;
memmove(&ctx->tracks[i + 1], &ctx->tracks[i],
sizeof(cyanrip_track)*(ctx->nb_tracks - i));
ct = &ctx->tracks[i + 1];
ctx->nb_tracks++;
cyanrip_track *nt = &ctx->tracks[i];
memset(nt, 0, sizeof(*nt));
nt->number = ct->number - 1;
nt->pregap_lsn = CDIO_INVALID_LSN;
nt->dropped_pregap_start = CDIO_INVALID_LSN;
nt->merged_pregap_end = CDIO_INVALID_LSN;
nt->start_lsn = ct->pregap_lsn;
nt->end_lsn = ct->start_lsn - 1;
nt->cd_track_number = ct->cd_track_number;
ct->pregap_lsn = CDIO_INVALID_LSN;
}
}
/* Between tracks */
for (int i = 1; i < ctx->nb_tracks; i++) {
cyanrip_track *ct = &ctx->tracks[i - 0];
cyanrip_track *lt = &ctx->tracks[i - 1];
if (ct->start_lsn == (lt->end_lsn + 1))
continue;
int discont_frames = ct->start_lsn - lt->end_lsn;
cyanrip_log(ctx, 0, " %i frame discontinuity between tracks %i and %i, ",
discont_frames, ct->number, lt->number);
gaps++;
if (ctx->settings.pregap_action[ct->number - 1] != CYANRIP_PREGAP_DROP) {
cyanrip_log(ctx, 0, "padding track %i\n", lt->number);
lt->end_lsn = ct->start_lsn - 1;
} else {
cyanrip_log(ctx, 0, "ignoring\n");
}
}
/* After last track */
cyanrip_track *lt = &ctx->tracks[ctx->nb_tracks - 1];
if (ctx->end_lsn > lt->end_lsn && !lt->track_is_data) {
int discont_frames = ctx->end_lsn - lt->end_lsn;
cyanrip_log(ctx, 0, " %i frame gap between last track and lead-out, padding track\n",
discont_frames);
gaps++;