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