2 #define _FILE_OFFSET_BITS 64
18 #include <sys/ioctl.h>
26 #include <dvdread/dvd_reader.h>
27 #include <dvdread/dvd_udf.h>
28 #include <dvdread/ifo_read.h>
29 #include <dvdread/ifo_types.h>
32 #define SECTORS(n) (((n) + (SECTORSZ - 1))/SECTORSZ)
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)
38 #define N(v) (sizeof(v)/sizeof((v)[0]))
40 enum { RAW, IFO, VOB, BUP };
41 typedef uint_least32_t ident;
43 static inline ident mkident(unsigned kind, unsigned title, unsigned part)
44 { return (((ident)kind << 0) | ((ident)title << 8) | ((ident)part << 16)); }
45 static inline unsigned id_kind(ident id) { return ((id >> 0)&0x0ff); }
46 static inline unsigned id_title(ident id) { return ((id >> 8)&0x0ff); }
47 static inline unsigned id_part(ident id) { return ((id >> 16)&0x0ff); }
49 static const char *prog = "<unset>";
50 static int status = 0;
52 static void usage(FILE *fp)
55 "usage: %s [-c] [-D DEV] [-R MAP] "
56 "[-b OUTMAP] [-o OUTFILE] [-r [START]-[END]]\n",
60 static void vmoan(const char *fmt, va_list ap)
61 { fprintf(stderr, "%s: ", prog); vfprintf(stderr, fmt, ap); }
62 __attribute__((noreturn, format(printf, 1, 2)))
63 static void bail(const char *fmt, ...)
67 va_start(ap, fmt); vmoan(fmt, ap); va_end(ap);
71 __attribute__((noreturn, format(printf, 2, 3)))
72 static void bail_syserr(int err, const char *fmt, ...)
76 va_start(ap, fmt); vmoan(fmt, ap); va_end(ap);
77 if (err) fprintf(stderr, ": %s", strerror(errno));
82 #define MAXFNSZ (1 + 8 + 1 + 12 + 1)
84 static void store_filename(char *buf, ident id)
86 switch (id_kind(id)) {
88 sprintf(buf, "#<raw device>");
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));
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));
99 if (!id_title(id)) sprintf(buf, "/VIDEO_TS/VIDEO_TS.VOB");
101 sprintf(buf, "/VIDEO_TS/VTS_%02u_%u.VOB", id_title(id), id_part(id));
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; \
114 #define VEC_PUSH(p, vv) do { \
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); \
122 (p) = &(vv)->v[(vv)->n++]; \
125 typedef uint_least32_t secaddr;
126 #define PRIuSEC PRIuLEAST32
128 #define MAXFILES (1 + 2*99 + 1)
133 DEFVEC(file_v, struct file);
134 static file_v filetab = VEC_INIT;
136 enum { EV_STOP, EV_BEGIN, EV_END, EV_WRITE };
138 unsigned char ev, file;
141 DEFVEC(event_v, struct event);
142 static event_v eventq = VEC_INIT;
144 typedef uint_least32_t bits;
145 static bits live[(MAXFILES + 31)/32];
147 static inline int livep(unsigned i)
148 { return (live[i/32]&((bits)1 << (i%32))); }
149 static inline void set_live(unsigned i)
150 { live[i/32] |= (bits)1 << (i%32); }
151 static inline void clear_live(unsigned i)
152 { live[i/32] &= ~((bits)1 << (i%32)); }
153 static inline int least_live(void)
155 unsigned i, n = (filetab.n + 32)/32;
158 for (i = 0; i < n; i++) { b = live[i]; if (b) goto found; }
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; }
171 static void put_event(unsigned evtype, unsigned file, secaddr pos)
175 VEC_PUSH(ev, &eventq);
176 ev->ev = evtype; ev->file = file; ev->pos = pos;
179 static void put_file(ident id, secaddr start, secaddr end)
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);
190 static void put_menu(dvd_reader_t *dvd, unsigned title)
192 ident id = mkident(VOB, title, 0);
196 store_filename(fn, id);
197 start = UDFFindFile(dvd, fn, &len); if (!start) return;
199 printf(";; %8"PRIuSEC" .. %-8"PRIuSEC": %s\n",
200 start, start + SECTORS(len), fn);
202 put_file(id, start, start + SECTORS(len));
205 static void put_title(dvd_reader_t *dvd, unsigned title)
208 secaddr start[9], len[9];
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;
215 npart = i; if (!npart) return;
218 for (i = 0; i < npart; i++) {
219 store_filename(fn, mkident(VOB, title, i + 1));
220 printf(";; %8"PRIuSEC" .. %-8"PRIuSEC": %s\n",
221 start[i], start[i] + SECTORS(len[i]), fn);
226 for (i = 0; i < npart - 1; i++) {
228 bail("title %u part %u length = %"PRIuSEC" not a multiple of %d",
229 title, i, len[i], SECTORSZ);
230 if (start[i] + len[i]/SECTORSZ != start[i + 1])
232 ("title %u part %u end = %"PRIuSEC" /= part %u start = %"PRIuSEC"",
233 title, i, start[i] + len[i]/SECTORSZ, i + 1, start[i + 1]);
236 put_file(mkident(VOB, title, 1),
237 start[0], start[npart - 1] + SECTORS(len[npart - 1]));
240 static int compare_event(const void *a, const void *b)
242 const struct event *eva = a, *evb = b;
244 if (eva->pos < evb->pos) return (-1);
245 else if (eva->pos > evb->pos) return (+1);
247 if (eva->ev < evb->ev) return (-1);
248 else if (eva->ev > evb->ev) return (+1);
250 if (eva->file < evb->file) return (-1);
251 else if (eva->file > evb->file) return (+1);
256 static int progresslen = 0;
258 static void clear_progress_internal(void)
259 { while (progresslen) { fputs("\b \b", stdout); progresslen--; } }
260 static void clear_progress(void)
261 { clear_progress_internal(); fflush(stdout); }
262 static void vappend_progress(const char *fmt, va_list ap)
263 { progresslen += vprintf(fmt, ap); }
264 __attribute__((format(printf, 1, 2)))
265 static void append_progress(const char *fmt, ...)
270 vappend_progress(fmt, ap);
273 __attribute__((format(printf, 1, 2)))
274 static void print_progress(const char *fmt, ...)
279 clear_progress_internal();
280 vappend_progress(fmt, ap);
291 #define SRCF_ALLPROGRESS 1u
292 secaddr last_pos, limit, nsectors, ndone;
293 struct timeval last_time;
295 const char *mapfile; FILE *mapfp;
297 #define SOURCE_INIT { 0, -1, 0, 0, 0, 0, 0, 0, 0, { 0, 0 }, 0.0, 0.0, 0, 0 }
299 static void report_progress(struct source *src, secaddr pos)
304 double percent, t, f, g, rate;
308 #define BETA (1 - ALPHA)
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;
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;
322 if (!src->wsum || !src->wcount)
323 { rate = 0; strcpy(etastr, "???"); }
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);
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"; }
335 if (src->f&SRCF_ALLPROGRESS) percent = pos*100.0/src->limit;
336 else percent = src->ndone*100.0/src->nsectors;
338 ("copied %.1f%% (%"PRIuSEC" of %"PRIuSEC"; %.1f %sB/s, ETA %s)",
339 percent, pos, src->limit, rate, unit, etastr);
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));
352 static void report_bad_blocks_progress(struct source *src,
353 secaddr lo, secaddr hi, int err)
355 report_progress(src, hi);
357 if (lo == hi) append_progress(": retrying bad sector");
359 append_progress(": %"PRIuSEC" bad %s",
360 hi - lo, hi == lo + 1 ? "sector" : "sectors");
361 if (err != EIO) append_progress(" (%s)", strerror(err));
365 static ssize_t read_sectors(struct source *src, secaddr pos,
366 void *buf, secaddr want)
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)
375 bail_syserr(errno, "failed to seek to sector %"PRIuSEC"", pos);
376 n = read(src->dvdfd, buf, want*SECTORSZ);
377 if (n >= 0) n /= SECTORSZ;
379 memset(buf, 0, want*SECTORSZ);
383 if (n < 0 && errno == EINTR) goto again;
387 static void carefully_write(int fd, const void *buf, size_t sz)
389 const unsigned char *p = buf;
394 n = write(fd, p, sz);
396 if (errno == EINTR) continue;
397 bail_syserr(errno, "failed to write to output file");
399 if (!n) bail("unexpected short write to output file");
404 static void emit(struct source *src, int outfd, secaddr start, secaddr end)
406 #define BUFSECTORS 512
409 unsigned char buf[BUFSECTORS*SECTORSZ];
411 secaddr bad_lo, bad_hi, good, step;
414 static int first_time = 1;
421 least = least_live();
424 printf(";; %8"PRIuSEC" .. %"PRIuSEC"\n", start, end);
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);
430 printf(";;\t\t%8"PRIuSEC" .. %-8"PRIuSEC" %s\n",
431 start - f->start, end - f->start, fn);
433 if (act == -1) printf(";;\t\t#<no live source>\n");
434 assert(act == least);
438 { src->file = 0; src->vob = 0; }
440 src->file = &filetab.v[least];
441 switch (id_kind(src->file->id)) {
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);
452 bail("failed to open %s %u",
453 id_part(src->file->id) ? "title" : "menu",
454 id_title(src->file->id));
463 want = end - pos; if (want > BUFSECTORS) want = BUFSECTORS;
464 n = read_sectors(src, pos, buf, want);
467 report_bad_blocks_progress(src, pos, pos, errno);
468 for (i = 0; i < 4; i++) {
469 n = read_sectors(src, pos, buf, 1);
472 fprintf(stderr, "%s: sector %"PRIuSEC" read ok after retry\n",
474 bad_lo = bad_hi = pos;
479 bad_lo = pos; step = 1; bad_hi = pos + 1;
481 report_bad_blocks_progress(src, bad_lo, bad_hi, errno);
484 fprintf(stderr, "%s: giving up on this extent\n", prog);
485 n = 0; goto recovered;
488 if (step > end - bad_lo) step = end - bad_lo;
489 pos = bad_lo + step - 1;
490 n = read_sectors(src, pos, buf, 1);
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;
504 if (bad_hi > bad_lo) {
506 fprintf(stderr, "%s: skipping %"PRIuSEC" bad sectors "
507 "(%"PRIuSEC" .. %"PRIuSEC")\n",
508 prog, bad_hi - bad_lo, bad_lo, bad_hi);
511 src->mapfp = fopen(src->mapfile, "w");
513 bail_syserr(errno, "failed to open bad-sector map file `%s'",
515 fprintf(src->mapfp, "## bad sector map\n\n");
517 fprintf(src->mapfp, "%"PRIuSEC" %"PRIuSEC"\n", bad_lo, bad_hi);
519 if (ferror(src->mapfp))
520 bail_syserr(errno, "error writing bad-sector map file");
523 lseek(outfd, (off_t)(bad_hi - bad_lo)*SECTORSZ, SEEK_CUR) < 0)
524 bail_syserr(errno, "failed to seek past bad sectors");
530 if (n > 0) { carefully_write(outfd, buf, n*SECTORSZ); pos += n; }
531 report_progress(src, pos); fflush(stdout);
534 if (src->vob) { DVDCloseFile(src->vob); src->vob = 0; }
540 static void logfn(void *p, dvd_logger_level_t lev,
541 const char *fmt, va_list ap)
544 case DVD_LOGGER_LEVEL_ERROR:
545 fprintf("%s (libdvdread error): ", prog);
547 case DVD_LOGGER_LEVEL_WARN:
548 fprintf("%s (libdvdread warning): ", prog);
553 vfprintf(stderr, fmt, ap);
556 static const dvd_logger_cb logger = { logfn };
563 #define BUF_INIT { 0, 0, 0 }
564 #define BUF_REWIND(b) do { (b)->n = 0; } while (0)
565 #define BUF_FREE(b) do { \
567 free(_b->p); _b->p = 0; _b->n = _b->sz = 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); \
576 _b->p[_b->n] = (ch); \
579 static int read_line(FILE *fp, struct buf *b)
586 else if (ch != '\n') do {
587 BUF_PUTC(b, ch); b->n++;
589 } while (ch != EOF && ch != '\n');
594 int main(int argc, char *argv[])
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;
609 struct buf buf = BUF_INIT;
612 const struct file *file;
617 #define f_continue 2u
621 p = strrchr(argv[0], '/'); prog = p ? p + 1 : argv[0];
623 opt = getopt(argc, argv, "hD:FR:b:co:r:"); if (opt < 0) break;
625 case 'h': usage(stderr); exit(0);
626 case 'D': device = optarg; break;
627 case 'F': f |= f_fixup; break;
629 fp = fopen(optarg, "r");
631 bail_syserr(errno, "failed to open ranges file `%s'", optarg);
634 BUF_REWIND(&buf); if (read_line(fp, &buf)) break;
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;
649 put_event(EV_WRITE, 0, start);
650 put_event(EV_STOP, 0, end);
654 bail_syserr(errno, "failed to read ranges file `%s'", optarg);
657 bail("bad range `%s' at `%s' line %zu", buf.p, optarg, i);
659 if (src.mapfile) bail("can't have multiple map files");
660 src.mapfile = optarg;
662 case 'c': f |= f_continue; break;
663 case 'o': outfile = optarg; break;
665 err = errno; errno = 0;
670 if (!ISDIGIT(*p)) goto bad_range;
671 start = strtoul(p, &p, 0);
672 if (errno || *p != '-') goto bad_range;
676 put_event(EV_WRITE, 0, start);
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;
683 put_event(EV_WRITE, 0, start);
684 put_event(EV_STOP, 0, end);
690 bail("bad range `%s'", optarg);
692 default: f |= f_bogus; break;
695 if (optind < argc) f |= f_bogus;
696 if (f&f_bogus) { usage(stderr); exit(2); }
698 src.dvdfd = open(device, O_RDONLY);
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)) {
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);
712 bail("can't use `%s' as source: expected file or block device", device);
714 if (blksz != SECTORSZ)
715 bail("device `%s' block size %d /= %d", device, blksz, SECTORSZ);
717 bail("device `%s' volume size %"PRIu64" not a multiple of %d",
718 device, volsz, SECTORSZ);
721 outfd = open(outfile, O_WRONLY | O_CREAT, 0666);
723 bail_syserr(errno, "failed to create output file `%s'", outfile);
727 if (!outfile) bail("can't continue without output file");
728 off = lseek(outfd, 0, SEEK_END);
730 bail_syserr(errno, "failed to seek to end of output file `%s'",
732 put_event(EV_WRITE, 0, off/SECTORSZ);
733 } else if (!eventq.n && !(f&f_fixup))
734 put_event(EV_WRITE, 0, 0);
737 src.dvd = DVDOpen2(0, &logger, device);
739 src.dvd = DVDOpen(device);
741 if (!src.dvd) bail("failed to open DVD on `%s'", device);
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);
749 put_file(mkident(RAW, 0, 0), 0, volsz/SECTORSZ);
750 assert(filetab.n <= MAXFILES);
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;
755 if (end > src.limit) end = src.limit;
758 printf("\n;; files:\n");
759 for (i = 0; i < filetab.n; i++) {
760 file = &filetab.v[i];
761 store_filename(fn, file->id);
762 printf(";;\t%8"PRIuSEC" %s\n", file->start, fn);
766 qsort(eventq.v, eventq.n, sizeof(struct event), compare_event);
768 f &= ~f_write; start = 0; n = 0;
769 for (i = 0; i < eventq.n; i++) {
774 bail("overlapping ranges: range from %lu still open at %"PRIuSEC"",
776 n++; f |= f_write; start = ev->pos;
784 f &= ~f_write; start = 0;
785 for (i = 0; i < eventq.n; i++) {
788 case EV_WRITE: start = ev->pos; f |= f_write; break;
789 case EV_STOP: src.nsectors += ev->pos - start; f &= ~f_write; break;
791 if (ev->pos >= src.limit) break;
792 if (f&f_fixup) start = ev->pos;
796 put_event(EV_WRITE, 0, start);
800 src.nsectors += src.limit - start;
801 put_event(EV_STOP, 0, src.limit);
803 if (n == 1 && (f&f_write))
804 src.f |= SRCF_ALLPROGRESS;
808 printf("\n;; event sweep:\n");
810 for (pos = 0, i = 0; i < eventq.n; i++) {
813 if (f&f_write) emit(&src, outfd, pos, ev->pos);
824 store_filename(fn, filetab.v[ev->file].id);
826 printf(";; %8"PRIuSEC": begin `%s'\n", pos, fn);
830 gettimeofday(&src.last_time, 0); src.last_pos = pos;
832 lseek(outfd, (off_t)ev->pos*SECTORSZ, SEEK_SET) < 0)
834 "failed to seek to resume position "
835 "(sector %"PRIuSEC") in output file `%s'",
839 printf(";; %8"PRIuSEC": begin write\n", pos);
847 printf(";; %8"PRIuSEC": end write\n", pos);
851 clear_live(ev->file);
853 store_filename(fn, filetab.v[ev->file].id);
855 printf(";; %8"PRIuSEC": end `%s'\n", pos, fn);
862 if (progresslen) putchar('\n');
864 if (outfd >= 0 && ftruncate(outfd, (off_t)src.limit*SECTORSZ) < 0)
865 bail_syserr(errno, "failed to set output file `%s' length", outfile);
867 if (src.dvd) DVDClose(src.dvd);
868 if (src.dvdfd >= 0) close(src.dvdfd);
869 if (outfd >= 0) close(outfd);
871 if (ferror(src.mapfp) || fclose(src.mapfp))
872 bail_syserr(errno, "error writing bad-sector map file");