+
+/*----- Common variables used by the copying machinery --------------------*/
+
+/* General reading state. */
+static dvd_reader_t *dvd; /* `libdvdread' state for device */
+static int dvdfd = -1, outfd = -1; /* input device and output image */
+static struct file *file; /* currently active file */
+static dvd_file_t *vob; /* current `.VOB' file, or null */
+static const char *mapfile; static FILE *mapfp; /* skipped regions map */
+static const char *errfile; static FILE *errfp; /* bad-sector log */
+static secaddr limit; /* upper bound on sectors */
+
+static secaddr bad_start; /* start of current bad region */
+static unsigned retry, max_retries = 4; /* retry state */
+
+/*----- Progress reporting ------------------------------------------------*/
+
+static secaddr nsectors, ndone; /* number of sectors done/to do */
+static double total_linear, done_linear; /* linear progress tracking */
+static secaddr last_pos; /* position last time we updated */
+static struct timeval last_time; /* time last time we updated */
+static struct geometry geom; /* disc geometry for progress */
+static struct avg avg_rate = AVG_INIT, avg_linear = AVG_INIT;
+static int bad_err; /* most recent error code */
+static FILE *progressfp; /* file on which to trace progress data */
+
+static const char throbber[] = "|<-<|>->"; /* throbber pattern */
+static unsigned throbix = 0; /* current throbber index */
+
+static struct progress_item /* stock progress items */
+ copy_progress, disc_progress,
+ file_progress, badblock_progress;
+
+static double scale_bytes(double n, const char **unit_out)
+ /* Determine a human-readable representation for N bytes. Divide N
+ * by some power of 1024, and store in *UNIT_OUT a string
+ * representing the conventional unit-prefix for that power of 1024.
+ */
+{
+ const char *unit = "";
+
+ if (n > 1600) { n /= 1024; unit = "k"; }
+ if (n > 1600) { n /= 1024; unit = "M"; }
+ if (n > 1600) { n /= 1024; unit = "G"; }
+ if (n > 1600) { n /= 1024; unit = "T"; }
+ *unit_out = unit; return (n);
+}
+
+#define TIMESTRMAX 16 /* maximum length of a duration string */
+static char *fmttime(unsigned long t, char *buf)
+ /* Format a count T of seconds. Write a suitable string to BUF,
+ * which will be no longer than `TIMESTRMAX' bytes including the
+ * terminating zero. Return BUF.
+ */
+{
+ if (t < 60) sprintf(buf, "%ld s", t);
+ else if (t < 3600) sprintf(buf, "%ld:%02ld", t/60, t%60);
+ else sprintf(buf, "%ld:%02ld:%02ld", t/3600, (t/60)%60, t%60);
+ return (buf);
+}
+
+static void render_perfstats(struct progress_render_state *render)
+ /* Add performance statistics to RENDER.
+ *
+ * Specifically: the average transfer rate, and the estimated time to
+ * completion. (See `update_progress' for how the average
+ * computation works.)
+ */
+{
+ int eta;
+ char timebuf[TIMESTRMAX];
+ double rate, linrate;
+ const char *unit;
+
+ /* If there's no average computed yet, then use some placeholder values. */
+ rate = current_avg(&avg_rate);
+ linrate = current_avg(&avg_linear);
+ eta = (int)((total_linear - done_linear)/linrate + 0.5);
+
+ /* Write out the statistics. */
+ rate = scale_bytes(rate*SECTORSZ, &unit);
+ progress_putright(render, "ETA %s ",
+ avg_linear.avg ? fmttime(eta, timebuf) : "???");
+ progress_putright(render, "%.1f %sB/s, ", rate, unit);
+}
+
+static void render_copy_progress(struct progress_item *item,
+ struct progress_render_state *render)
+ /* Render the progress for the copy, i.e., the number of sectors
+ * copied against the total number to be copied.
+ */
+{
+ double frac = (double)ndone/nsectors;
+
+ progress_putleft(render, " %c copied %.1f%%",
+ throbber[throbix], 100.0*frac);
+ render_perfstats(render);
+ progress_putleft(render, " (%"PRIuSEC" of %"PRIuSEC")", ndone, nsectors);
+
+ progress_showbar(render, frac);
+}
+
+static void render_disc_progress(struct progress_item *item,
+ struct progress_render_state *render)
+ /* Render the progress for the disc, i.e., the current position
+ * against the total number of sectors on the disc.
+ */
+{
+ double frac = (double)last_pos/limit;
+
+ progress_putleft(render, " disc %.1f%% (%"PRIuSEC" of %"PRIuSEC")",
+ 100.0*frac, last_pos, limit);
+ progress_showbar(render, frac);
+}
+
+static void render_file_progress(struct progress_item *item,
+ struct progress_render_state *render)
+ /* Render the progress for the current file, i.e., the current
+ * position within the file against the file size.
+ */
+{
+ secaddr off = last_pos - file->start, len = file->end - file->start;
+ char fn[MAXFNSZ];
+ double frac;
+
+ store_filename(fn, file->id);
+ frac = (double)off/len;
+ progress_putleft(render, " `%s' %.1f%% (%"PRIuSEC" of %"PRIuSEC")",
+ fn, 100.0*frac, off, len);
+ progress_showbar(render, frac);
+}
+
+static void render_badblock_progress(struct progress_item *item,
+ struct progress_render_state *render)
+ /* Render a notice about the progress through the current bad block
+ * region.
+ */
+{
+ secaddr n = last_pos - bad_start;
+ int bg;
+
+ if (!n) {
+ progress_putleft(render, " Retrying bad sector %"PRIuSEC"", bad_start);
+ progress_putright(render, "attempt %u/%u ", retry + 1, max_retries);
+ bg = 4;
+ } else {
+ progress_putleft(render, " Found %"PRIuSEC" bad %s",
+ n, n == 1 ? "sector" : "sectors");
+ progress_putright(render, "%"PRIuSEC" .. %"PRIuSEC" ",
+ bad_start, last_pos);
+ bg = 1;
+ }
+ if (bad_err && bad_err != EIO)
+ progress_putleft(render, " (%s)", strerror(bad_err));
+ progress_shownotice(render, bg, 7);
+}
+
+static void update_progress(secaddr pos)
+ /* Recompute the data displayed by the progress renderer functions
+ * above, based on the new current sector POS.
+ */
+{
+ struct timeval now;
+ double t, delta_r;
+
+ /* Find the current time and the delta since the last time we updated.
+ * This will be the length of the current interval.
+ */
+ gettimeofday(&now, 0); t = tvdiff(&last_time, &now);
+
+ /* If no time at all has passed (unlikely!) then skip the rate
+ * calculation. (The moving average wouldn't be affected anyway.)
+ */
+ if (t) {
+ /* Update the moving average and the correction term, and start the next
+ * interval.
+ */
+
+ delta_r = linear_progress(&geom, last_pos, pos);
+ update_avg(&avg_rate, t, pos - last_pos);
+ update_avg(&avg_linear, t, delta_r);
+ ndone += pos - last_pos; done_linear += delta_r;
+ last_time = now; last_pos = pos;
+ }
+
+ /* Trace progress state if requested. */
+ if (progressfp) {
+ fprintf(progressfp, "%10ju.%06ld %"PRIuSEC" %f %f\n",
+ (uintmax_t)now.tv_sec, now.tv_usec,
+ ndone, done_linear,
+ (total_linear - done_linear)/current_avg(&avg_linear));
+ check_write(progressfp, "progress trace file");
+ }
+
+ /* Advance the throbber character. */
+ throbix++; if (!throbber[throbix]) throbix = 0;
+}
+
+static void report_progress(secaddr pos)
+ /* Update the progress variables (as `update_progress') and redraw
+ * the progress display.
+ */
+ { update_progress(pos); progress_update(&progress); }
+
+/*----- Basic disc I/O ----------------------------------------------------*/
+
+struct badblock { secaddr start, end; };
+DEFVEC(badblock_v, struct badblock);
+static badblock_v badblocks = VEC_INIT;
+ /* This is a list of /fake/ bad-block ranges, used to test the
+ * recovery algorithm. It's a rule that the ranges in this table
+ * mustn't overlap -- though it's OK if they abut.
+ */
+
+static int compare_badblock(const void *a, const void *b)
+ /* A `qsort' comparison function for the fake bad-blocks list.
+ * Ranges which start earlier are sorted before rangers which start
+ * later.
+ */
+{
+ const struct badblock *ba = a, *bb = b;
+
+ /* Order by start sector. */
+ if (ba->start < bb->start) return (-1);
+ else if (ba->start > bb->start) return (+1);
+
+ /* Order by end sector as a tiebreak. This shouldn't be possible. */
+ if (ba->end < bb->end) return (-1);
+ else if (ba->end > bb->end) return (+1);
+
+ /* They're equal. This shouldn't be possible either. */
+ return (0);
+}
+
+static double bad_block_delay = 0.0, good_block_delay = 0.0;
+ /* delay parameters for performance testing */
+
+static ssize_t read_sectors(secaddr pos, void *buf, secaddr want)
+ /* Try to read WANT sectors from the input, starting with sector POS,
+ * and write the contents to BUF. Return the number of /whole
+ * sectors/ read; this will be 0 at end-of-file (though that
+ * shouldn't happen). The returned length will be smaller than WANT
+ * only if end-of-file or a system error prevents reading further.
+ * Returns -1 on a system error if that prevented us from reading
+ * anything at all.
+ *
+ * This function is where the fake bad-blocks list is handled.
+ */
+{
+ ssize_t n, done;
+ size_t lo, mid, hi;
+ int fakeerr = 0;
+ struct badblock *bad, *best;
+ unsigned char *p = buf;
+
+ /* See whether the requested range intersects a bad-blocks range. */
+ if (badblocks.n) {
+ /* Since the list is sorted, we use a binary search. We're looking for
+ * the earliest-starting range which /ends after/ POS. If this starts
+ * /at or before/ POS, then POS itself is a bad sector, and we should
+ * pretend an I/O error; otherwise, if the bad range /starts/ somewhere
+ * in the range we're trying to read then we must pretend a short read;
+ * and otherwise there's nothing to do.
+ */
+
+ /* Throughout, `best' points to the earliest-starting range we've found
+ * which (starts and) finishes after POS. Ranges with indices below LO
+ * end too early to be interesting; similarly, ranges with indices HI or
+ * above start later than POS. If we find a range which actually covers
+ * POS exactly then we'll stop early.
+ */
+ best = 0; lo = 0; hi = badblocks.n;
+#ifdef DEBUG
+ progress_clear(&progress);
+ printf(";; searching badblocks for %"PRIuSEC" .. %"PRIuSEC"\n",
+ pos, pos + want);
+#endif
+ while (lo < hi) {
+ /* Standard binary-search loop: we continue until the pointers
+ * converge.
+ */
+
+ /* Try the midpoint between the two bounds. */
+ mid = lo + (hi - lo)/2; bad = &badblocks.v[mid];
+#ifdef DEBUG
+ printf(";; try %zu (%"PRIuSEC" .. %"PRIuSEC")... ",
+ mid, bad->start, bad->end);
+#endif
+
+ /* Follow our invariant. If the range starts strictly after POS, then
+ * it's too late to overlap, so bring down HI to cover it; but it must
+ * be closer than any previous block we've found, so remember it in
+ * `best'. Similarly, if the range ends /at or before/ POS then it
+ * stops too early, so bring up LO to cover it (but otherwise forget
+ * about it because it can't affect what we're doing).
+ *
+ * If we get a match then we stop immediately and fake a bad block.
+ */
+ if (pos < bad->start) { D( printf("high\n"); ) best = bad; hi = mid; }
+ else if (pos >= bad->end) { D( printf("low\n"); ) lo = mid + 1; }
+ else {
+ D( printf("match!\n"); )
+ errno = EIO; sit(bad_block_delay); return (-1);
+ }
+ }
+
+ /* We're done. Check to see whether the bad range starts early enough.
+ * If so, remember that we're simulating an error, apply the delay, and
+ * bamboozle the rest of the code into performing a short read.
+ */
+#ifdef DEBUG
+ if (best)
+ printf(";; next is %"PRIuSEC" .. %"PRIuSEC"\n",
+ best->start, best->end);
+#endif
+ if (best && pos + want > best->start)
+ { want = best->start - pos; fakeerr = EIO; sit(bad_block_delay); }
+ }
+
+ /* Try to read stuff into the buffer until we find a reason why we can't
+ * continue. Obviously we need to keep track of how much stuff we've read
+ * on previous iterations.
+ */
+ done = 0; errno = 0;
+ while (want) {
+
+ /* Read from the current file's input source. If that's a scrambled
+ * video file, then use `libdvdread'; if it's the `raw' file, then go to
+ * the block device; if it's nothing at all, then fill with zeros.
+ * Always force a seek to the right place, in case things got messed up
+ * by some previous error.
+ */
+ if (vob)
+ { errno = 0; n = DVDReadBlocks(vob, pos - file->start, want, p); }
+ else if (file) {
+ if (lseek(dvdfd, (off_t)pos*SECTORSZ, SEEK_SET) < 0)
+ bail_syserr(errno, "failed to seek to sector %"PRIuSEC"", pos);
+ errno = 0; n = read(dvdfd, p, want*SECTORSZ);
+ if (n >= 0) n /= SECTORSZ;
+ } else {
+ memset(p, 0, want*SECTORSZ);
+ n = want;
+ }
+
+ /* If we read some stuff then update the buffer pointer and lengths. If
+ * we hit end-of-file then stop. If we hit a bad sector then maybe make
+ * a note of it in the bad-sector log. On any other kind of error, just
+ * stop.
+ */
+ if (n > 0) { done += n; pos += n; p += n*SECTORSZ; want -= n; }
+ else if (!n) break;
+ else if (errno == EIO && errfile) {
+ open_file_on_demand(errfile, &errfp, "bad-sector error log");
+ fprintf(errfp, "%"PRIuSEC" %"PRIuSEC"\n", pos, pos + 1);
+ check_write(errfp, "bad-sector error log");
+ break;
+ } else if (errno != EINTR) break;
+ }
+
+ /* We made it. If we saved up a fake error, and there wasn't a real error
+ * (which should obviously take priority) then present the fake error to
+ * the caller. If there wasn't an error, then everything must have been
+ * good so impose the good-block delay -- note that a bad-block delay will
+ * already have been imposed above. Finally, return the accumulated count
+ * of sectors successfully read, or report the end-of-file or error
+ * condition as applicable.
+ */
+ if (fakeerr && !errno) errno = fakeerr;
+ else if (done > 0 && good_block_delay) sit(done*good_block_delay);
+ return (!done && errno ? -1 : done);
+}
+
+/*----- Tracking machinery for the bad-sector algorithm -------------------*
+ *
+ * While we're probing around trying to find the end of the bad region, we'll
+ * have read some good data. We want to try to keep as much good data as we
+ * can, and avoid re-reading it because (a) it's pointless I/O work, but more
+ * importantly (b) it might not work the second time. The machinery here
+ * is for making this work properly.
+ *
+ * There are two parts to this which don't really intersect, but for
+ * convenience the tracking information for them is kept in the same
+ * `recoverybuf' structure.
+ *
+ * * The `short-range' machinery keeps track of a contiguous region of good
+ * data stored in the caller's buffer.
+ *
+ * * The `long-range' machinery keeps track of a contiguous region of good
+ * data that's beyond the range of the buffer.
+ */
+
+struct recoverybuf {
+ /* Information used to keep track of where good and bad sectors are
+ * while we're trying to find the end of a region of bad sectors.
+ */
+
+ /* Short-range buffer tracking. */
+ unsigned char *buf; /* pointer to the actual buffer */
+ secaddr sz; /* size of the buffer in sectors */
+ secaddr pos; /* sector address corresponding to
+ * the start of the buffer */
+ secaddr start, end; /* bounds of the live region within
+ * the buffer, as offsets in
+ * sectors from the buffer start */
+
+ /* Long-range tracking. */
+ secaddr good_lo, good_hi; /* known-good region, as absolute
+ * sector addresses */
+};
+
+static void rearrange_sectors(struct recoverybuf *r,
+ secaddr dest, secaddr src, secaddr len)
+ /* Shuffle data about in R's buffer. Specifically, move LEN sectors
+ * starting SRC sectors from the start of the buffer to a new
+ * position DEST sectors from the start.
+ *
+ * Unsurprisingly, this is a trivial wrapper around `memmove', with
+ * some range checking thrown in; it's only used by `recovery_read_-
+ * buffer' and `find_good_sector' below.
+ */
+{
+ assert(dest + len <= r->sz); assert(src + len <= r->sz);
+ memmove(r->buf + dest*SECTORSZ, r->buf + src*SECTORSZ, len*SECTORSZ);
+}
+
+#ifdef DEBUG
+static PRINTF_LIKE(2, 3)
+ void show_recovery_buffer_map(const struct recoverybuf *r,
+ const char *what, ...)
+ /* Dump a simple visualization of the short-range tracking state. */