chiark / gitweb /
dvd-sector-copy.c: Introduce type alias and print macro for sector numbers.
[dvdrip] / dvd-sector-copy.c
CommitLineData
7fbe0fb9
MW
1#define _GNU_SOURCE
2#define _FILE_OFFSET_BITS 64
3
4#include <assert.h>
5#include <ctype.h>
6#include <errno.h>
7#include <inttypes.h>
8#include <math.h>
9#include <stdarg.h>
10#include <stdint.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <time.h>
15
16#include <unistd.h>
17#include <fcntl.h>
18#include <sys/ioctl.h>
d766561d 19#include <sys/stat.h>
7fbe0fb9
MW
20#include <sys/time.h>
21
22#include <getopt.h>
23
24#include <linux/fs.h>
25
26#include <dvdread/dvd_reader.h>
27#include <dvdread/dvd_udf.h>
28#include <dvdread/ifo_read.h>
29#include <dvdread/ifo_types.h>
30
31#define SECTORSZ 2048
32#define SECTORS(n) (((n) + (SECTORSZ - 1))/SECTORSZ)
33
34#define CTYPE_HACK(fn, ch) fn((unsigned char)(ch))
35#define ISDIGIT(ch) CTYPE_HACK(isdigit, ch)
36#define ISSPACE(ch) CTYPE_HACK(isspace, ch)
37
38#define N(v) (sizeof(v)/sizeof((v)[0]))
39
40enum { RAW, IFO, VOB, BUP };
41typedef uint_least32_t ident;
42
43static inline ident mkident(unsigned kind, unsigned title, unsigned part)
44 { return (((ident)kind << 0) | ((ident)title << 8) | ((ident)part << 16)); }
45static inline unsigned id_kind(ident id) { return ((id >> 0)&0x0ff); }
46static inline unsigned id_title(ident id) { return ((id >> 8)&0x0ff); }
47static inline unsigned id_part(ident id) { return ((id >> 16)&0x0ff); }
48
49static const char *prog = "<unset>";
50static int status = 0;
51
52static void usage(FILE *fp)
53{
54 fprintf(fp,
55 "usage: %s [-c] [-D DEV] [-R MAP] "
56 "[-b OUTMAP] [-o OUTFILE] [-r [START]-[END]]\n",
57 prog);
58}
59
60static void vmoan(const char *fmt, va_list ap)
61 { fprintf(stderr, "%s: ", prog); vfprintf(stderr, fmt, ap); }
62__attribute__((noreturn, format(printf, 1, 2)))
63static void bail(const char *fmt, ...)
64{
65 va_list ap;
66
67 va_start(ap, fmt); vmoan(fmt, ap); va_end(ap);
68 fputc('\n', stderr);
69 exit(2);
70}
71__attribute__((noreturn, format(printf, 2, 3)))
72static void bail_syserr(int err, const char *fmt, ...)
73{
74 va_list ap;
75
76 va_start(ap, fmt); vmoan(fmt, ap); va_end(ap);
77 if (err) fprintf(stderr, ": %s", strerror(errno));
78 fputc('\n', stderr);
79 exit(2);
80}
81
82#define MAXFNSZ (1 + 8 + 1 + 12 + 1)
83
84static void store_filename(char *buf, ident id)
85{
86 switch (id_kind(id)) {
87 case RAW:
88 sprintf(buf, "#<raw device>");
89 break;
90 case IFO:
91 if (!id_title(id)) sprintf(buf, "/VIDEO_TS/VIDEO_TS.IFO");
92 else sprintf(buf, "/VIDEO_TS/VTS_%02u_0.IFO", id_title(id));
93 break;
94 case BUP:
95 if (!id_title(id)) sprintf(buf, "/VIDEO_TS/VIDEO_TS.BUP");
96 else sprintf(buf, "/VIDEO_TS/VTS_%02u_0.BUP", id_title(id));
97 break;
98 case VOB:
99 if (!id_title(id)) sprintf(buf, "/VIDEO_TS/VIDEO_TS.VOB");
100 else
101 sprintf(buf, "/VIDEO_TS/VTS_%02u_%u.VOB", id_title(id), id_part(id));
102 break;
103 default:
104 abort();
105 }
106}
107
108#define DEFVEC(vtype, etype) \
109 typedef struct { etype *v; size_t n, sz; } vtype
110#define VEC_INIT { 0, 0, 0 }
111#define VEC_FREE(vv) do { \
112 free((vv)->v); (vv)->v 0; (vv)->n = (vv)->sz = 0; \
113} while (0)
114#define VEC_PUSH(p, vv) do { \
115 size_t _want; \
116 if ((vv)->n >= (vv)->sz) { \
117 (vv)->sz = (vv)->sz ? 2*(vv)->sz : 32; \
118 _want = (vv)->sz*sizeof(*(vv)->v); \
119 (vv)->v = realloc((vv)->v, _want); \
120 if (!(vv)->v) bail("out of memory allocating %zu bytes", _want); \
121 } \
122 (p) = &(vv)->v[(vv)->n++]; \
123} while (0)
124
788fe88a
MW
125typedef uint_least32_t secaddr;
126#define PRIuSEC PRIuLEAST32
127
7fbe0fb9
MW
128#define MAXFILES (1 + 2*99 + 1)
129struct file {
130 ident id;
788fe88a 131 secaddr start, end;
7fbe0fb9
MW
132};
133DEFVEC(file_v, struct file);
134static file_v filetab = VEC_INIT;
135
d79ff9c5 136enum { EV_STOP, EV_BEGIN, EV_END, EV_WRITE };
7fbe0fb9
MW
137struct event {
138 unsigned char ev, file;
788fe88a 139 secaddr pos;
7fbe0fb9
MW
140};
141DEFVEC(event_v, struct event);
142static event_v eventq = VEC_INIT;
143
144typedef uint_least32_t bits;
145static bits live[(MAXFILES + 31)/32];
146
147static inline int livep(unsigned i)
148 { return (live[i/32]&((bits)1 << (i%32))); }
149static inline void set_live(unsigned i)
150 { live[i/32] |= (bits)1 << (i%32); }
151static inline void clear_live(unsigned i)
152 { live[i/32] &= ~((bits)1 << (i%32)); }
153static inline int least_live(void)
154{
155 unsigned i, n = (filetab.n + 32)/32;
156 bits b;
157
158 for (i = 0; i < n; i++) { b = live[i]; if (b) goto found; }
159 return (-1);
160found:
161 i *= 32;
162 if (!(b&0x0000ffff)) { b >>= 16; i += 16; }
163 if (!(b&0x000000ff)) { b >>= 8; i += 8; }
164 if (!(b&0x0000000f)) { b >>= 4; i += 4; }
165 if (!(b&0x00000003)) { b >>= 2; i += 2; }
166 if (!(b&0x00000001)) { b >>= 1; i += 1; }
167 assert(b&1);
168 return (i);
169}
170
788fe88a 171static void put_event(unsigned evtype, unsigned file, secaddr pos)
7fbe0fb9
MW
172{
173 struct event *ev;
174
175 VEC_PUSH(ev, &eventq);
176 ev->ev = evtype; ev->file = file; ev->pos = pos;
177}
178
788fe88a 179static void put_file(ident id, secaddr start, secaddr end)
7fbe0fb9
MW
180{
181 struct file *f;
182 size_t i;
183
184 VEC_PUSH(f, &filetab); i = f - filetab.v;
185 f->id = id; f->start = start; f->end = end;
186 put_event(EV_BEGIN, i, start);
187 put_event(EV_END, i, end);
188}
189
190static void put_menu(dvd_reader_t *dvd, unsigned title)
191{
192 ident id = mkident(VOB, title, 0);
193 char fn[MAXFNSZ];
788fe88a 194 secaddr start, len;
7fbe0fb9
MW
195
196 store_filename(fn, id);
197 start = UDFFindFile(dvd, fn, &len); if (!start) return;
198#ifdef DEBUG
788fe88a 199 printf(";; %8"PRIuSEC" .. %-8"PRIuSEC": %s\n",
7fbe0fb9
MW
200 start, start + SECTORS(len), fn);
201#endif
202 put_file(id, start, start + SECTORS(len));
203}
204
205static void put_title(dvd_reader_t *dvd, unsigned title)
206{
207 char fn[MAXFNSZ];
788fe88a 208 secaddr start[9], len[9];
7fbe0fb9
MW
209 unsigned i, npart;
210
211 for (i = 0; i < 9; i++) {
212 store_filename(fn, mkident(VOB, title, i + 1));
213 start[i] = UDFFindFile(dvd, fn, &len[i]); if (!start[i]) break;
214 }
215 npart = i; if (!npart) return;
216
217#ifdef DEBUG
218 for (i = 0; i < npart; i++) {
219 store_filename(fn, mkident(VOB, title, i + 1));
788fe88a 220 printf(";; %8"PRIuSEC" .. %-8"PRIuSEC": %s\n",
7fbe0fb9
MW
221 start[i], start[i] + SECTORS(len[i]), fn);
222 }
223#endif
224
225 if (npart > 1)
226 for (i = 0; i < npart - 1; i++) {
227 if (len[i]%SECTORSZ)
788fe88a 228 bail("title %u part %u length = %"PRIuSEC" not a multiple of %d",
7fbe0fb9
MW
229 title, i, len[i], SECTORSZ);
230 if (start[i] + len[i]/SECTORSZ != start[i + 1])
788fe88a
MW
231 bail
232 ("title %u part %u end = %"PRIuSEC" /= part %u start = %"PRIuSEC"",
233 title, i, start[i] + len[i]/SECTORSZ, i + 1, start[i + 1]);
7fbe0fb9
MW
234 }
235
236 put_file(mkident(VOB, title, 1),
237 start[0], start[npart - 1] + SECTORS(len[npart - 1]));
238}
239
240static int compare_event(const void *a, const void *b)
241{
242 const struct event *eva = a, *evb = b;
243
244 if (eva->pos < evb->pos) return (-1);
245 else if (eva->pos > evb->pos) return (+1);
246
247 if (eva->ev < evb->ev) return (-1);
248 else if (eva->ev > evb->ev) return (+1);
249
250 if (eva->file < evb->file) return (-1);
251 else if (eva->file > evb->file) return (+1);
252
253 return (0);
254}
255
256static int progresslen = 0;
257
258static void clear_progress_internal(void)
259 { while (progresslen) { fputs("\b \b", stdout); progresslen--; } }
260static void clear_progress(void)
261 { clear_progress_internal(); fflush(stdout); }
262static void vappend_progress(const char *fmt, va_list ap)
263 { progresslen += vprintf(fmt, ap); }
264__attribute__((format(printf, 1, 2)))
265static void append_progress(const char *fmt, ...)
266{
267 va_list ap;
268
269 va_start(ap, fmt);
270 vappend_progress(fmt, ap);
271 va_end(ap);
272}
273__attribute__((format(printf, 1, 2)))
274static void print_progress(const char *fmt, ...)
275{
276 va_list ap;
277
278 va_start(ap, fmt);
279 clear_progress_internal();
280 vappend_progress(fmt, ap);
281 va_end(ap);
282}
283
284struct source {
285 dvd_reader_t *dvd;
286 int dvdfd;
287 struct file *file;
288 dvd_file_t *vob;
289
81a03df8
MW
290 unsigned f;
291#define SRCF_ALLPROGRESS 1u
788fe88a 292 secaddr last_pos, limit, nsectors, ndone;
7fbe0fb9
MW
293 struct timeval last_time;
294 double wsum, wcount;
295 const char *mapfile; FILE *mapfp;
296};
81a03df8 297#define SOURCE_INIT { 0, -1, 0, 0, 0, 0, 0, 0, 0, { 0, 0 }, 0.0, 0.0, 0, 0 }
7fbe0fb9 298
788fe88a 299static void report_progress(struct source *src, secaddr pos)
7fbe0fb9
MW
300{
301 char etastr[32];
302 struct timeval now;
303 int eta;
81a03df8 304 double percent, t, f, g, rate;
7fbe0fb9
MW
305 char *unit;
306
307#define ALPHA 0.02
308#define BETA (1 - ALPHA)
309
310 gettimeofday(&now, 0);
311 t = (now.tv_sec - src->last_time.tv_sec) +
312 (now.tv_usec - src->last_time.tv_usec)/1000000.0;
313
314 if (t) {
315 g = src->wcount ? pow(BETA, t) : 0.0; f = (1 - g)/(1 - BETA);
316 src->wsum = f*(pos - src->last_pos)/t + g*src->wsum;
317 src->wcount = f + g*src->wcount;
318 src->ndone += pos - src->last_pos;
319 src->last_time = now; src->last_pos = pos;
320 }
321
322 if (!src->wsum || !src->wcount)
323 { rate = 0; strcpy(etastr, "???"); }
324 else {
325 rate = src->wsum/src->wcount;
326 eta = (int)((src->nsectors - src->ndone)/rate);
327 sprintf(etastr, "%d:%02d:%02d", eta/3600, (eta/60)%60, eta%60);
328 }
329
330 rate *= SECTORSZ; unit = "";
331 if (rate > 128) { rate /= 1024; unit = "k"; }
332 if (rate > 128) { rate /= 1024; unit = "M"; }
333 if (rate > 128) { rate /= 1024; unit = "G"; }
334
81a03df8
MW
335 if (src->f&SRCF_ALLPROGRESS) percent = pos*100.0/src->limit;
336 else percent = src->ndone*100.0/src->nsectors;
788fe88a
MW
337 print_progress
338 ("copied %.1f%% (%"PRIuSEC" of %"PRIuSEC"; %.1f %sB/s, ETA %s)",
339 percent, pos, src->limit, rate, unit, etastr);
7fbe0fb9
MW
340 if (src->file && id_kind(src->file->id) == VOB) {
341 append_progress(" -- %s %d %3.1f%%",
342 id_part(src->file->id) ? "title" : "menu",
343 id_title(src->file->id),
344 (pos - src->file->start)*100.0/
345 (src->file->end - src->file->start));
346 }
347
348#undef ALPHA
349#undef BETA
350}
351
352static void report_bad_blocks_progress(struct source *src,
788fe88a 353 secaddr lo, secaddr hi, int err)
7fbe0fb9
MW
354{
355 report_progress(src, hi);
356
357 if (lo == hi) append_progress(": retrying bad sector");
358 else
788fe88a 359 append_progress(": %"PRIuSEC" bad %s",
7fbe0fb9
MW
360 hi - lo, hi == lo + 1 ? "sector" : "sectors");
361 if (err != EIO) append_progress(" (%s)", strerror(err));
362 fflush(stdout);
363}
364
788fe88a
MW
365static ssize_t read_sectors(struct source *src, secaddr pos,
366 void *buf, secaddr want)
7fbe0fb9
MW
367{
368 ssize_t n;
369
370again:
371 if (src->vob)
372 n = DVDReadBlocks(src->vob, pos - src->file->start, want, buf);
373 else if (src->file) {
374 if (lseek(src->dvdfd, (off_t)pos*SECTORSZ, SEEK_SET) < 0)
788fe88a 375 bail_syserr(errno, "failed to seek to sector %"PRIuSEC"", pos);
7fbe0fb9
MW
376 n = read(src->dvdfd, buf, want*SECTORSZ);
377 if (n >= 0) n /= SECTORSZ;
378 } else {
379 memset(buf, 0, want*SECTORSZ);
380 n = want;
381 }
382
383 if (n < 0 && errno == EINTR) goto again;
384 return (n);
385}
386
387static void carefully_write(int fd, const void *buf, size_t sz)
388{
389 const unsigned char *p = buf;
390 ssize_t n;
391
392 if (fd < 0) return;
393 while (sz) {
394 n = write(fd, p, sz);
395 if (n < 0) {
396 if (errno == EINTR) continue;
397 bail_syserr(errno, "failed to write to output file");
398 }
399 if (!n) bail("unexpected short write to output file");
400 p += n; sz -= n;
401 }
402}
403
788fe88a 404static void emit(struct source *src, int outfd, secaddr start, secaddr end)
7fbe0fb9
MW
405{
406#define BUFSECTORS 512
407
408 int least, i;
409 unsigned char buf[BUFSECTORS*SECTORSZ];
788fe88a
MW
410 secaddr pos;
411 secaddr bad_lo, bad_hi, good, step;
7fbe0fb9
MW
412 size_t want;
413 ssize_t n;
414 static int first_time = 1;
415#ifdef DEBUG
416 struct file *f;
417 char fn[MAXFNSZ];
418 int act = -1;
419#endif
420
421 least = least_live();
422
423#ifdef DEBUG
788fe88a 424 printf(";; %8"PRIuSEC" .. %"PRIuSEC"\n", start, end);
7fbe0fb9
MW
425
426 for (i = 0; i < filetab.n; i++) {
427 if (!livep(i)) continue;
428 if (act == -1) act = i;
429 f = &filetab.v[i]; store_filename(fn, f->id);
788fe88a 430 printf(";;\t\t%8"PRIuSEC" .. %-8"PRIuSEC" %s\n",
7fbe0fb9
MW
431 start - f->start, end - f->start, fn);
432 }
433 if (act == -1) printf(";;\t\t#<no live source>\n");
434 assert(act == least);
435#endif
436
437 if (least == -1)
438 { src->file = 0; src->vob = 0; }
439 else {
440 src->file = &filetab.v[least];
441 switch (id_kind(src->file->id)) {
442 case RAW:
443 src->vob = 0;
444 break;
445 case VOB:
446 if (first_time) { clear_progress(); first_time = 0; }
447 src->vob = DVDOpenFile(src->dvd, id_title(src->file->id),
448 id_part(src->file->id)
449 ? DVD_READ_TITLE_VOBS
450 : DVD_READ_MENU_VOBS);
451 if (!src->vob)
452 bail("failed to open %s %u",
453 id_part(src->file->id) ? "title" : "menu",
454 id_title(src->file->id));
455 break;
456 default:
457 abort();
458 }
459 }
460
461 pos = start;
462 while (pos < end) {
463 want = end - pos; if (want > BUFSECTORS) want = BUFSECTORS;
464 n = read_sectors(src, pos, buf, want);
465
466 if (n <= 0) {
467 report_bad_blocks_progress(src, pos, pos, errno);
468 for (i = 0; i < 4; i++) {
469 n = read_sectors(src, pos, buf, 1);
470 if (n > 0) {
471 clear_progress();
788fe88a 472 fprintf(stderr, "%s: sector %"PRIuSEC" read ok after retry\n",
7fbe0fb9
MW
473 prog, pos);
474 bad_lo = bad_hi = pos;
475 goto recovered;
476 }
477 }
478
479 bad_lo = pos; step = 1; bad_hi = pos + 1;
480 for (;;) {
481 report_bad_blocks_progress(src, bad_lo, bad_hi, errno);
482 if (bad_hi >= end) {
483 clear_progress();
484 fprintf(stderr, "%s: giving up on this extent\n", prog);
485 n = 0; goto recovered;
486 }
487 step *= 2;
488 if (step > end - bad_lo) step = end - bad_lo;
489 pos = bad_lo + step - 1;
490 n = read_sectors(src, pos, buf, 1);
491 if (n > 0) break;
492 bad_hi = pos + 1;
493 }
494
495 good = pos;
496 while (good > bad_hi) {
497 report_bad_blocks_progress(src, bad_lo, bad_hi, errno);
498 pos = bad_hi + (good - bad_hi)/2;
499 n = read_sectors(src, pos, buf, 1);
500 if (n > 0) good = pos;
501 else bad_hi = pos + 1;
502 }
503 recovered:
504 if (bad_hi > bad_lo) {
505 clear_progress();
788fe88a
MW
506 fprintf(stderr, "%s: skipping %"PRIuSEC" bad sectors "
507 "(%"PRIuSEC" .. %"PRIuSEC")\n",
7fbe0fb9
MW
508 prog, bad_hi - bad_lo, bad_lo, bad_hi);
509 if (src->mapfile) {
510 if (!src->mapfp) {
511 src->mapfp = fopen(src->mapfile, "w");
512 if (!src->mapfp)
513 bail_syserr(errno, "failed to open bad-sector map file `%s'",
514 optarg);
515 fprintf(src->mapfp, "## bad sector map\n\n");
516 }
788fe88a 517 fprintf(src->mapfp, "%"PRIuSEC" %"PRIuSEC"\n", bad_lo, bad_hi);
7fbe0fb9
MW
518 fflush(src->mapfp);
519 if (ferror(src->mapfp))
520 bail_syserr(errno, "error writing bad-sector map file");
521 }
522 if (outfd >= 0 &&
523 lseek(outfd, (off_t)(bad_hi - bad_lo)*SECTORSZ, SEEK_CUR) < 0)
524 bail_syserr(errno, "failed to seek past bad sectors");
525 status = 1;
526 }
527 pos = bad_hi;
528 }
529
530 if (n > 0) { carefully_write(outfd, buf, n*SECTORSZ); pos += n; }
531 report_progress(src, pos); fflush(stdout);
532 }
533
534 if (src->vob) { DVDCloseFile(src->vob); src->vob = 0; }
535
536#undef BUFSECTORS
537}
538
539#ifdef notdef
540static void logfn(void *p, dvd_logger_level_t lev,
541 const char *fmt, va_list ap)
542{
543 switch (lev) {
544 case DVD_LOGGER_LEVEL_ERROR:
545 fprintf("%s (libdvdread error): ", prog);
546 break;
547 case DVD_LOGGER_LEVEL_WARN:
548 fprintf("%s (libdvdread warning): ", prog);
549 break;
550 default:
551 return;
552 }
553 vfprintf(stderr, fmt, ap);
554 fputc('\n', stderr);
555}
556static const dvd_logger_cb logger = { logfn };
557#endif
558
559struct buf {
560 char *p;
561 size_t n, sz;
562};
563#define BUF_INIT { 0, 0, 0 }
564#define BUF_REWIND(b) do { (b)->n = 0; } while (0)
565#define BUF_FREE(b) do { \
566 buf *_b = (b); \
567 free(_b->p); _b->p = 0; _b->n = _b->sz = 0; \
568} while (0)
569#define BUF_PUTC(b, ch) do { \
570 struct buf *_b = (b); \
571 if (_b->n >= _b->sz) { \
572 _b->sz = _b->sz ? 2*_b->sz : 32; \
573 _b->p = realloc(_b->p, _b->sz); \
574 if (!_b->p) bail("out of memory allocating %zu bytes", _b->sz); \
575 } \
576 _b->p[_b->n] = (ch); \
577} while (0)
578
579static int read_line(FILE *fp, struct buf *b)
580{
581 int ch;
582
583 ch = getc(fp);
584 if (ch == EOF)
585 return (-1);
586 else if (ch != '\n') do {
587 BUF_PUTC(b, ch); b->n++;
588 ch = getc(fp);
589 } while (ch != EOF && ch != '\n');
590 BUF_PUTC(b, 0);
591 return (0);
592}
593
594int main(int argc, char *argv[])
595{
596 unsigned f = 0;
597 char *p;
598 uint64_t volsz;
788fe88a 599 secaddr pos;
7fbe0fb9
MW
600 off_t off;
601 struct source src = SOURCE_INIT;
602 unsigned long start, end;
603 const struct event *ev;
604 const char *device = "/dev/dvd", *outfile = 0;
605 int opt, err, outfd = -1, blksz;
81a03df8 606 unsigned n;
7fbe0fb9
MW
607 size_t i;
608 FILE *fp;
609 struct buf buf = BUF_INIT;
d766561d 610 struct stat st;
7fbe0fb9
MW
611#ifdef DEBUG
612 const struct file *file;
613 char fn[MAXFNSZ];
614#endif
615
616#define f_bogus 1u
617#define f_continue 2u
618#define f_fixup 4u
619#define f_write 256u
620
621 p = strrchr(argv[0], '/'); prog = p ? p + 1 : argv[0];
622 for (;;) {
623 opt = getopt(argc, argv, "hD:FR:b:co:r:"); if (opt < 0) break;
624 switch (opt) {
625 case 'h': usage(stderr); exit(0);
626 case 'D': device = optarg; break;
627 case 'F': f |= f_fixup; break;
628 case 'R':
629 fp = fopen(optarg, "r");
630 if (!fp)
631 bail_syserr(errno, "failed to open ranges file `%s'", optarg);
632 i = 0;
633 for (;;) {
634 BUF_REWIND(&buf); if (read_line(fp, &buf)) break;
635 p = buf.p; i++;
636 while (ISSPACE(*p)) p++;
637 if (!*p || *p == '#') continue;
638 if (!ISDIGIT(*p)) goto bad_range_file;
639 start = strtoul(p, &p, 0);
640 if (errno || !ISSPACE(*p)) goto bad_range_file;
641 do p++; while (ISSPACE(*p));
642 if (!ISDIGIT(*p)) goto bad_range_file;
643 end = strtoul(p, &p, 0);
644 if (errno || (*p && !ISSPACE(*p))) goto bad_range_file;
645 while (ISSPACE(*p)) p++;
646 if (*p) goto bad_range_file;
647 if (start > end) goto bad_range_file;
648 if (start < end) {
649 put_event(EV_WRITE, 0, start);
650 put_event(EV_STOP, 0, end);
651 }
652 }
653 if (ferror(fp))
654 bail_syserr(errno, "failed to read ranges file `%s'", optarg);
655 break;
656 bad_range_file:
657 bail("bad range `%s' at `%s' line %zu", buf.p, optarg, i);
658 case 'b':
659 if (src.mapfile) bail("can't have multiple map files");
660 src.mapfile = optarg;
661 break;
662 case 'c': f |= f_continue; break;
663 case 'o': outfile = optarg; break;
664 case 'r':
665 err = errno; errno = 0;
666 p = optarg;
667 if (*p == '-')
668 start = 0;
669 else {
670 if (!ISDIGIT(*p)) goto bad_range;
671 start = strtoul(p, &p, 0);
672 if (errno || *p != '-') goto bad_range;
673 }
674 p++;
675 if (!*p)
676 put_event(EV_WRITE, 0, start);
677 else {
678 if (!ISDIGIT(*p)) goto bad_range;
679 end = strtoul(p, &p, 0);
680 if (errno || *p) goto bad_range;
681 if (start > end) goto bad_range;
682 if (start < end) {
683 put_event(EV_WRITE, 0, start);
684 put_event(EV_STOP, 0, end);
685 }
686 }
687 errno = err;
688 break;
689 bad_range:
690 bail("bad range `%s'", optarg);
691 break;
692 default: f |= f_bogus; break;
693 }
694 }
695 if (optind < argc) f |= f_bogus;
696 if (f&f_bogus) { usage(stderr); exit(2); }
697
698 src.dvdfd = open(device, O_RDONLY);
d766561d
MW
699 if (src.dvdfd < 0)
700 bail_syserr(errno, "failed to open device `%s'", device);
701 if (fstat(src.dvdfd, &st))
702 bail_syserr(errno, "failed to stat device `%s'", device);
703 if (S_ISREG(st.st_mode)) {
704 blksz = SECTORSZ;
705 volsz = st.st_size;
706 } else if (S_ISBLK(st.st_mode)) {
707 if (ioctl(src.dvdfd, BLKSSZGET, &blksz))
708 bail_syserr(errno, "failed to get block size for `%s'", device);
709 if (ioctl(src.dvdfd, BLKGETSIZE64, &volsz))
710 bail_syserr(errno, "failed to get volume size for `%s'", device);
711 } else
712 bail("can't use `%s' as source: expected file or block device", device);
7fbe0fb9
MW
713
714 if (blksz != SECTORSZ)
715 bail("device `%s' block size %d /= %d", device, blksz, SECTORSZ);
716 if (volsz%SECTORSZ)
717 bail("device `%s' volume size %"PRIu64" not a multiple of %d",
718 device, volsz, SECTORSZ);
719
720 if (outfile) {
721 outfd = open(outfile, O_WRONLY | O_CREAT, 0666);
722 if (outfd < 0)
723 bail_syserr(errno, "failed to create output file `%s'", outfile);
724 }
725
726 if (f&f_continue) {
727 if (!outfile) bail("can't continue without output file");
728 off = lseek(outfd, 0, SEEK_END);
729 if (off < 0)
730 bail_syserr(errno, "failed to seek to end of output file `%s'",
731 outfile);
732 put_event(EV_WRITE, 0, off/SECTORSZ);
733 } else if (!eventq.n && !(f&f_fixup))
734 put_event(EV_WRITE, 0, 0);
735
736#ifdef notdef
737 src.dvd = DVDOpen2(0, &logger, device);
738#else
739 src.dvd = DVDOpen(device);
740#endif
741 if (!src.dvd) bail("failed to open DVD on `%s'", device);
742
743 /* It's fast enough just to check everything. */
744 put_menu(src.dvd, 0);
745 for (i = 1; i < 100; i++) {
746 put_menu(src.dvd, i);
747 put_title(src.dvd, i);
748 }
749 put_file(mkident(RAW, 0, 0), 0, volsz/SECTORSZ);
750 assert(filetab.n <= MAXFILES);
751
752 for (i = 0, src.limit = 0; i < filetab.n; i++)
753 if (filetab.v[i].end > src.limit) src.limit = filetab.v[i].end;
754
755 if (end > src.limit) end = src.limit;
756
757#ifdef DEBUG
758 printf("\n;; files:\n");
759 for (i = 0; i < filetab.n; i++) {
760 file = &filetab.v[i];
761 store_filename(fn, file->id);
788fe88a 762 printf(";;\t%8"PRIuSEC" %s\n", file->start, fn);
7fbe0fb9
MW
763 }
764#endif
765
766 qsort(eventq.v, eventq.n, sizeof(struct event), compare_event);
767
81a03df8 768 f &= ~f_write; start = 0; n = 0;
7fbe0fb9
MW
769 for (i = 0; i < eventq.n; i++) {
770 ev = &eventq.v[i];
771 switch (ev->ev) {
772 case EV_WRITE:
773 if (f&f_write)
788fe88a 774 bail("overlapping ranges: range from %lu still open at %"PRIuSEC"",
7fbe0fb9 775 start, ev->pos);
81a03df8 776 n++; f |= f_write; start = ev->pos;
7fbe0fb9
MW
777 break;
778 case EV_STOP:
779 f &= ~f_write;
780 break;
781 }
782 }
783
784 f &= ~f_write; start = 0;
785 for (i = 0; i < eventq.n; i++) {
786 ev = &eventq.v[i];
787 switch (ev->ev) {
788 case EV_WRITE: start = ev->pos; f |= f_write; break;
789 case EV_STOP: src.nsectors += ev->pos - start; f &= ~f_write; break;
790 }
791 if (ev->pos >= src.limit) break;
792 if (f&f_fixup) start = ev->pos;
793 }
794 eventq.n = i;
795 if (f&f_fixup) {
796 put_event(EV_WRITE, 0, start);
81a03df8 797 n++; f |= f_write;
7fbe0fb9
MW
798 }
799 if (f&f_write) {
800 src.nsectors += src.limit - start;
801 put_event(EV_STOP, 0, src.limit);
802 }
81a03df8
MW
803 if (n == 1 && (f&f_write))
804 src.f |= SRCF_ALLPROGRESS;
7fbe0fb9
MW
805 f &= ~f_write;
806
807#ifdef DEBUG
808 printf("\n;; event sweep:\n");
809#endif
810 for (pos = 0, i = 0; i < eventq.n; i++) {
811 ev = &eventq.v[i];
812 if (ev->pos > pos) {
813 if (f&f_write) emit(&src, outfd, pos, ev->pos);
814 pos = ev->pos;
815#ifdef DEBUG
816 clear_progress();
817 printf(";;\n");
818#endif
819 }
820 switch (ev->ev) {
821 case EV_BEGIN:
822 set_live(ev->file);
823#ifdef DEBUG
824 store_filename(fn, filetab.v[ev->file].id);
825 clear_progress();
788fe88a 826 printf(";; %8"PRIuSEC": begin `%s'\n", pos, fn);
7fbe0fb9
MW
827#endif
828 break;
829 case EV_WRITE:
830 gettimeofday(&src.last_time, 0); src.last_pos = pos;
831 if (outfd >= 0 &&
832 lseek(outfd, (off_t)ev->pos*SECTORSZ, SEEK_SET) < 0)
833 bail_syserr(errno,
834 "failed to seek to resume position "
788fe88a 835 "(sector %"PRIuSEC") in output file `%s'",
7fbe0fb9
MW
836 ev->pos, outfile);
837#ifdef DEBUG
838 clear_progress();
788fe88a 839 printf(";; %8"PRIuSEC": begin write\n", pos);
7fbe0fb9
MW
840#endif
841 f |= f_write;
842 break;
843 case EV_STOP:
844 f &= ~f_write;
845#ifdef DEBUG
846 clear_progress();
788fe88a 847 printf(";; %8"PRIuSEC": end write\n", pos);
7fbe0fb9
MW
848#endif
849 break;
850 case EV_END:
851 clear_live(ev->file);
852#ifdef DEBUG
853 store_filename(fn, filetab.v[ev->file].id);
854 clear_progress();
788fe88a 855 printf(";; %8"PRIuSEC": end `%s'\n", pos, fn);
7fbe0fb9
MW
856#endif
857 break;
858 default: abort();
859 }
860 }
861
862 if (progresslen) putchar('\n');
863
864 if (outfd >= 0 && ftruncate(outfd, (off_t)src.limit*SECTORSZ) < 0)
865 bail_syserr(errno, "failed to set output file `%s' length", outfile);
866
867 if (src.dvd) DVDClose(src.dvd);
868 if (src.dvdfd >= 0) close(src.dvdfd);
869 if (outfd >= 0) close(outfd);
870 if (src.mapfp) {
871 if (ferror(src.mapfp) || fclose(src.mapfp))
872 bail_syserr(errno, "error writing bad-sector map file");
873 }
874
875#undef f_bogus
876#undef f_continue
877#undef f_fixup
878#undef f_write
879
880 return (status);
881}