aboutsummaryrefslogtreecommitdiff
path: root/cuerecover.c
blob: 89a7e7a76c57fc789c6e1bddd59bab5b9fd742fd (plain)
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
/* references:
https://www.gnu.org/software/ccd2cue/manual/html_node/CUE-sheet-format.html
https://wiki.osdev.org/User:Combuster/CDRom_BS
https://en.wikipedia.org/wiki/CD-ROM */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <string.h>
#include <errno.h>

const char *self;

#define RAW_SECTOR_SIZE 2352
#define DATA_SECTOR_SIZE 2048

unsigned char mode1_sync[] = {
	0x00, 0xff, 0xff, 0xff,
	0xff, 0xff, 0xff, 0xff,
	0xff, 0xff, 0xff, 0x00 };

double silence_sec = 2.0l;
int silence_frames; /* same as above in 1/75 sec frames */
int silence_thresh = 0;
int multi_bin = 0;
int verbose = 0;
char *outfile = NULL;

void die(const char *msg) {
	if(!msg) msg = strerror(errno);
	fprintf(stderr, "%s: %s\n", self, msg);
	exit(1);
}

void usage() {
	fprintf(stderr, "cuerecover v" VERSION " by B. Watson, WTFPL\n");
	fprintf(stderr, "Usage: %s [-s sec] [-t thresh] bin-file [bin-file ...]\n", self);
	fprintf(stderr, "See man page for details\n");
	exit(0);
}

int looks_like_filesystem(const char *filename, FILE *f) {
	int have_apple_magic = 0, have_iso_magic = 0;
	char buf[2048];

	if(fseek(f, 0L, SEEK_SET) < 0)
		die(NULL);

	if(!fread(buf, 2048, 1, f)) {
		fprintf(stderr, "%s: file %s is too short to be a CD image file\n", self, filename);
		return 0;
	}

	if(buf[0] == 'E' && buf[1] == 'C' && buf[2] == 'M') {
		fprintf(stderr, "%s: file %s is ECM, use 'ecm2bin' to convert to raw bin\n", self, filename);
		exit(1);
	}

	if(buf[0] == 'E' && buf[1] == 'R' && buf[3] == 0 && (buf[2] == 0x02 || buf[2] == 0x08))
	{
		have_apple_magic++;
	}

	if(fseek(f, 16 * 2048L, SEEK_SET) < 0)
		die(NULL);

	if(!fread(buf, 2048, 1, f)) {
		fprintf(stderr, "%s: file %s is too short to be a CD image file\n", self, filename);
		return 0;
	}

	if(strncmp("\x01" "CD001", buf, 6) == 0) {
		have_iso_magic++;
	}

	if(fseek(f, 0L, SEEK_SET) < 0)
		die(NULL);

	if(have_apple_magic && have_iso_magic) {
		fprintf(stderr, "%s: file %s looks like hybrid ISO/HFS image\n", self, filename);
	} else if(have_apple_magic) {
		fprintf(stderr, "%s: file %s looks like Mac HFS image\n", self, filename);
	} else if(have_iso_magic) {
		fprintf(stderr, "%s: file %s looks like ISO9660 image\n", self, filename);
	}

	return have_apple_magic || have_iso_magic;
}

int frame_is_silent(const char *data) {
	int i, nonzero = 0;
	for(i=0; i<RAW_SECTOR_SIZE; i++)
		if(data[i]) nonzero++;

	if(nonzero <= silence_thresh)
		return 1;
	return 0;
}

const char *frame2time(int frame) {
	static char buf[10];
	int min, sec;

	min = frame / (75 * 60);
	frame %= (75 * 60);
	sec = frame / 75;
	frame %= 75;

	sprintf(buf, "%02d:%02d:%02d", min, sec, frame);

	return buf;
}

int read_sector(FILE *f, char *buf) {
	/*
	if(verbose)
		fprintf(stderr, "read_sector at pos %d\n", ftell(f));
	 */
	return fread(buf, RAW_SECTOR_SIZE, 1, f);
}

int has_mode1_sync(char *buf) {
	return (memcmp(buf, mode1_sync, sizeof(mode1_sync)) == 0);
}

int get_sector_mode(char *buf) {
	if(!has_mode1_sync(buf))
		return 0; /* audio, or something we don't grok */

	return buf[15];
}

int unbcd(int bcd) {
	int hi, lo;

	lo = bcd & 0x0f;
	hi = (bcd >> 4) & 0x0f;
	return hi * 10 + lo;
}

int get_sector_addr(char *buf) {
	int mm, ss, ff;
	mm = unbcd(buf[12]);
	ss = unbcd(buf[13]);
	ff = unbcd(buf[14]);
	return mm * 75 * 60 + ss * 75 + ff;
}

const char *mode_string(int mode) {
	switch(mode) {
		case 1: return "MODE1/2352";
		case 2: return "MODE2/2352";
		default: return "AUDIO";
	}
}

struct track {
	int mode;
	int index0;
	int index1;
};

void process_single(char *filename) {
	char buf[RAW_SECTOR_SIZE];
	FILE *f;
	int i;
	int track = 0;
	int sector = 0;
	int mode;
	int silence_start, in_silence = 0;
	struct track tracklist[100];
	struct track *t = tracklist;

	if(!(f = fopen(filename, "rb")))
		die(NULL);

	if(looks_like_filesystem(filename, f)) {
		fprintf(stderr, "%s: %s looks like 'cooked' data!\n", self, filename);
		/*
		// don't know all the details on how this works yet
		int skipped_sectors = 0;
		fprintf(stderr, "%s: %s looks like 'cooked' data, ", self, filename);
		if((skipped_sectors = skip_fs(filename, f))) {
		fprintf(stderr, "skipped %d 2048-byte sectors\n", skipped_sectors);
		} else {
		fprintf(stderr, "but not ISO9660, don't know how to skip it\n");
		}
		 */
	}

	/* only the first track can be data */
	if(read_sector(f, buf) && (mode = get_sector_mode(buf)) != 0) {
		if(verbose) fprintf(stderr, "track %d is data, mode %d\n", track, mode);
		t->index0 = sector;
		t->index1 = sector;
		t->mode = mode;

		/* skip over the data sectors */
		while(read_sector(f, buf) && (get_sector_mode(buf) == mode))
			sector++;

		/* now buf holds the first audio sector, which might or might not
			begin with silence */
		t++; track++;
		t->mode = 0;
		t->index0 = sector;
		t->index1 = sector;
	}

	if(silence_frames) while(read_sector(f, buf)) {
		if(frame_is_silent(buf)) {
			if(in_silence) {
				/* nothing */
			} else {
				t->index0 = sector;
				t->index1 = -1;
				silence_start = sector;
				in_silence = 1;
			}
		} else {
			if(in_silence) {
				if((sector - silence_start) >= silence_frames) {
					in_silence = 0;
					t->index1 = sector;
					t++;
					track++;
					if(track > 99) {
						fprintf(stderr, "%s: too many tracks (>99), skipping rest of file\n", self);
						break;
					}
					t->mode = 0;
				} else {
					/* nothing */
				}
			}
		}
		sector++;
	}

	fclose(f);

	t = tracklist;
	printf("FILE \"%s\" BINARY\r\n", filename);
	for(i=0; i<=track; t++, i++) {
		if(verbose) {
			fprintf(stderr, "track %d, mode %d, index0 %d, index1 %d\n",
					i, t->mode, t->index0, t->index1);
		}
		if(t->index1 > -1) {
			printf("  TRACK %02d %s\r\n", i + 1, mode_string(t->mode));
			if(t->index0 < t->index1) {
				if(silence_frames && t->index1 - t->index0 > silence_frames) {
					t->index0 = t->index1 - silence_frames;
					if(verbose)
						fprintf(stderr, "   (index0 adjusted to %d)\n", t->index0);
				}
				printf("    INDEX 00 %s\r\n", frame2time(t->index0));
			}
			printf("    INDEX 01 %s\r\n", frame2time(t->index1));
		}
	}
}

void process_multi(char **filenames) {
	char *filename;
	int track = 0;
	char buf[RAW_SECTOR_SIZE];
	FILE *f;

	while((filename = *filenames++)) {
		int index0 = 0, index1 = -1;
		int mode = -1;
		int sector = 0;

		track++;

		if(verbose) fprintf(stderr, "reading %s\n", filename);
		if(!(f = fopen(filename, "rb")))
			die(NULL);

		printf("FILE \"%s\" BINARY\r\n", filename);

		if(looks_like_filesystem(filename, f)) {
			fprintf(stderr, "%s: %s looks like 'cooked' data, assuming MODE1/2048\n",
					self, filename);
			printf("  TRACK %02d MODE1/2048\r\n", track);
			printf("    INDEX 01 00:00:00\r\n");
			continue;
		}

		while(read_sector(f, buf)) {
			mode = get_sector_mode(buf);

			/* if first sector is data, there's no index 01, we're done */
			if(mode > 0) {
				index0 = 0;
				index1 = -1;
				break;
			}

			/* for audio, keep reading silence until we hit sound */
			if(mode == 0 && index1 == -1 && !frame_is_silent(buf)) {
				index1 = (sector / 75) * 75; /* round to integer number of seconds */
				break;
			}

			sector++;
		}
		fclose(f);

		printf("  TRACK %02d %s\r\n", track, mode_string(mode));
		if(index1 < 1) {
			printf("    INDEX 01 %s\r\n", frame2time(index0));
		} else {
			printf("    INDEX 00 %s\r\n", frame2time(index0));
			printf("    INDEX 01 %s\r\n", frame2time(index1));
		}
	}
}

char **parse_args(int argc, char **argv) {
	if(argc == 1) usage();
	if(argc > 1 && strcmp(argv[1], "--help") == 0) usage();

	while(++argv, --argc) {
		if(argv[0][0] == '-') {
			char *nextarg = argv[1];
			switch(argv[0][1]) {
				case 'v':
					verbose++; break;
				case 'o':
					if(nextarg)
						outfile = nextarg;
					else
						die("-o requires an output filename");
					argv++, argc--;
					break;
				case 's':
					if(nextarg && ((*nextarg >= '0' && *nextarg <= '9') || (*nextarg == '.'))) {
						silence_sec = atof(nextarg);
						argv++, argc--;
					} else {
						die("-s requires numeric seconds argument");
					}
					break;
				case 't':
					if(nextarg &&
							(*nextarg >= '0' && *nextarg <= '9') &&
							(silence_thresh = atoi(nextarg) <= 100))
					{
						silence_thresh = (RAW_SECTOR_SIZE / 100.0) * atoi(nextarg);
						argv++, argc--;
					} else {
						die("-t requires numeric percentage argument, 0-100");
					}
					break;
				default:
					fprintf(stderr, "unrecognized option '%s', try --help\n", *argv);
					exit(1);
					break;
			}
		} else {
			break;
		}
	}

	silence_frames = (int)(75.0l * silence_sec);
	multi_bin = (argc > 1);
	return argv;
}

void redirect_output(void) {
	struct stat ss;

	if(lstat(outfile, &ss) >= 0)
		die("output file exists, not overwriting");

	if(!(freopen(outfile, "w", stdout)))
		die(NULL);
}

void set_exe_name(const char *argv0) {
	const char *p;
	self = argv0;
	for(p = self; *p; p++)
		if(p[0] == '/' && p[1]) self = p + 1;
}

int main(int argc, char **argv) {
	set_exe_name(argv[0]);

	argv = parse_args(argc, argv);

	if(verbose) fprintf(stderr, "writing %s CUE file to %s\n",
			(multi_bin ? "multi-bin" : "single-bin"),
			(outfile ? outfile : "<standard output>"));

	if(outfile) redirect_output();

	if(multi_bin)
		process_multi(argv);
	else
		process_single(*argv);

	return 0;
}