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