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