Commit message: 64-bit tjbench: Fix signed int overflow/segfault

... that occurred when attempting to decompress images with more than
715827882 (2048*1024*1024 / 3) pixels.

Fixes #388
CVE: CVE-2019-2201
CWE: CWE-787
Vulnerability description: In generate_jsimd_ycc_rgb_convert_neon of jsimd_arm64_neon.S, there is a possible out of bounds write due to a missing bounds check. This could lead to remote code execution in an unprivileged process with no additional execution privileges needed. User interaction is needed for exploitation.Product: AndroidVersions: Android-8.0 Android-8.1 Android-9 Android-10Android ID: A-120551338

Project: libjpeg-turbo
File: tjbench.c

static int decompTest(char *fileName)
{
  FILE *file = NULL;
  tjhandle handle = NULL;
  unsigned char **jpegBuf = NULL, *srcBuf = NULL;
  unsigned long *jpegSize = NULL, srcSize, totalJpegSize;
  tjtransform *t = NULL;
  double start, elapsed;
  int ps = tjPixelSize[pf], tile, row, col, i, iter, retval = 0, decompsrc = 0;
  char *temp = NULL, tempStr[80], tempStr2[80];
  /* Original image */
  int w = 0, h = 0, tilew, tileh, ntilesw = 1, ntilesh = 1, subsamp = -1,
    cs = -1;
  /* Transformed image */
  int tw, th, ttilew, ttileh, tntilesw, tntilesh, tsubsamp;

  if ((file = fopen(fileName, "rb")) == NULL)
    THROW_UNIX("opening file");
  if (fseek(file, 0, SEEK_END) < 0 ||
      (srcSize = ftell(file)) == (unsigned long)-1)
    THROW_UNIX("determining file size");
  if ((srcBuf = (unsigned char *)malloc(srcSize)) == NULL)
    THROW_UNIX("allocating memory");
  if (fseek(file, 0, SEEK_SET) < 0)
    THROW_UNIX("setting file position");
  if (fread(srcBuf, srcSize, 1, file) < 1)
    THROW_UNIX("reading JPEG data");
  fclose(file);  file = NULL;

  temp = strrchr(fileName, '.');
  if (temp != NULL) *temp = '\0';

  if ((handle = tjInitTransform()) == NULL)
    THROW_TJ("executing tjInitTransform()");
  if (tjDecompressHeader3(handle, srcBuf, srcSize, &w, &h, &subsamp,
                          &cs) == -1)
    THROW_TJ("executing tjDecompressHeader3()");
  if (w < 1 || h < 1)
    THROW("reading JPEG header", "Invalid image dimensions");
  if (cs == TJCS_YCCK || cs == TJCS_CMYK) {
    pf = TJPF_CMYK;  ps = tjPixelSize[pf];
  }

  if (quiet == 1) {
    printf("All performance values in Mpixels/sec\n\n");
    printf("Bitmap     JPEG   JPEG     %s  %s   Xform   Comp    Decomp  ",
           doTile ? "Tile " : "Image", doTile ? "Tile " : "Image");
    if (doYUV) printf("Decode");
    printf("\n");
    printf("Format     CS     Subsamp  Width  Height  Perf    Ratio   Perf    ");
    if (doYUV) printf("Perf");
    printf("\n\n");
  } else if (!quiet)
    printf(">>>>>  JPEG %s --> %s (%s)  <<<<<\n",
           formatName(subsamp, cs, tempStr), pixFormatStr[pf],
           (flags & TJFLAG_BOTTOMUP) ? "Bottom-up" : "Top-down");

  for (tilew = doTile ? 16 : w, tileh = doTile ? 16 : h; ;
       tilew *= 2, tileh *= 2) {
    if (tilew > w) tilew = w;
    if (tileh > h) tileh = h;
    ntilesw = (w + tilew - 1) / tilew;
    ntilesh = (h + tileh - 1) / tileh;

    if ((jpegBuf = (unsigned char **)malloc(sizeof(unsigned char *) *
                                            ntilesw * ntilesh)) == NULL)
      THROW_UNIX("allocating JPEG tile array");
    memset(jpegBuf, 0, sizeof(unsigned char *) * ntilesw * ntilesh);
    if ((jpegSize = (unsigned long *)malloc(sizeof(unsigned long) *
                                            ntilesw * ntilesh)) == NULL)
      THROW_UNIX("allocating JPEG size array");
    memset(jpegSize, 0, sizeof(unsigned long) * ntilesw * ntilesh);

    if ((flags & TJFLAG_NOREALLOC) != 0 &&
        (doTile || xformOp != TJXOP_NONE || xformOpt != 0 || customFilter))
      for (i = 0; i < ntilesw * ntilesh; i++) {
        if (tjBufSize(tilew, tileh, subsamp) > (unsigned long)INT_MAX)
          THROW("getting buffer size", "Image is too large");
        if ((jpegBuf[i] = (unsigned char *)
                          tjAlloc(tjBufSize(tilew, tileh, subsamp))) == NULL)
          THROW_UNIX("allocating JPEG tiles");
      }

    tw = w;  th = h;  ttilew = tilew;  ttileh = tileh;
    if (!quiet) {
      printf("\n%s size: %d x %d", doTile ? "Tile" : "Image", ttilew, ttileh);
      if (sf.num != 1 || sf.denom != 1)
        printf(" --> %d x %d", TJSCALED(tw, sf), TJSCALED(th, sf));
      printf("\n");
    } else if (quiet == 1) {
      printf("%-4s (%s)  %-5s  %-5s    ", pixFormatStr[pf],
             (flags & TJFLAG_BOTTOMUP) ? "BU" : "TD", csName[cs],
             subNameLong[subsamp]);
      printf("%-5d  %-5d   ", tilew, tileh);
    }

    tsubsamp = subsamp;
    if (doTile || xformOp != TJXOP_NONE || xformOpt != 0 || customFilter) {
      if ((t = (tjtransform *)malloc(sizeof(tjtransform) * ntilesw *
                                     ntilesh)) == NULL)
        THROW_UNIX("allocating image transform array");

      if (xformOp == TJXOP_TRANSPOSE || xformOp == TJXOP_TRANSVERSE ||
          xformOp == TJXOP_ROT90 || xformOp == TJXOP_ROT270) {
        tw = h;  th = w;  ttilew = tileh;  ttileh = tilew;
      }

      if (xformOpt & TJXOPT_GRAY) tsubsamp = TJ_GRAYSCALE;
      if (xformOp == TJXOP_HFLIP || xformOp == TJXOP_ROT180)
        tw = tw - (tw % tjMCUWidth[tsubsamp]);
      if (xformOp == TJXOP_VFLIP || xformOp == TJXOP_ROT180)
        th = th - (th % tjMCUHeight[tsubsamp]);
      if (xformOp == TJXOP_TRANSVERSE || xformOp == TJXOP_ROT90)
        tw = tw - (tw % tjMCUHeight[tsubsamp]);
      if (xformOp == TJXOP_TRANSVERSE || xformOp == TJXOP_ROT270)
        th = th - (th % tjMCUWidth[tsubsamp]);
      tntilesw = (tw + ttilew - 1) / ttilew;
      tntilesh = (th + ttileh - 1) / ttileh;

      if (xformOp == TJXOP_TRANSPOSE || xformOp == TJXOP_TRANSVERSE ||
          xformOp == TJXOP_ROT90 || xformOp == TJXOP_ROT270) {
        if (tsubsamp == TJSAMP_422) tsubsamp = TJSAMP_440;
        else if (tsubsamp == TJSAMP_440) tsubsamp = TJSAMP_422;
      }

      for (row = 0, tile = 0; row < tntilesh; row++) {
        for (col = 0; col < tntilesw; col++, tile++) {
          t[tile].r.w = min(ttilew, tw - col * ttilew);
          t[tile].r.h = min(ttileh, th - row * ttileh);
          t[tile].r.x = col * ttilew;
          t[tile].r.y = row * ttileh;
          t[tile].op = xformOp;
          t[tile].options = xformOpt | TJXOPT_TRIM;
          t[tile].customFilter = customFilter;
          if (t[tile].options & TJXOPT_NOOUTPUT && jpegBuf[tile]) {
            tjFree(jpegBuf[tile]);  jpegBuf[tile] = NULL;
          }
        }
      }

      iter = -1;
      elapsed = 0.;
      while (1) {
        start = getTime();
        if (tjTransform(handle, srcBuf, srcSize, tntilesw * tntilesh, jpegBuf,
                        jpegSize, t, flags) == -1)
          THROW_TJ("executing tjTransform()");
        elapsed += getTime() - start;
        if (iter >= 0) {
          iter++;
          if (elapsed >= benchTime) break;
        } else if (elapsed >= warmup) {
          iter = 0;
          elapsed = 0.;
        }
      }

      free(t);  t = NULL;

      for (tile = 0, totalJpegSize = 0; tile < tntilesw * tntilesh; tile++)
        totalJpegSize += jpegSize[tile];

      if (quiet) {
        printf("%-6s%s%-6s%s",
               sigfig((double)(w * h) / 1000000. / elapsed, 4, tempStr, 80),
               quiet == 2 ? "\n" : "  ",
               sigfig((double)(w * h * ps) / (double)totalJpegSize, 4,
                      tempStr2, 80),
               quiet == 2 ? "\n" : "  ");
      } else if (!quiet) {
        printf("Transform     --> Frame rate:         %f fps\n",
               1.0 / elapsed);
        printf("                  Output image size:  %lu bytes\n",
               totalJpegSize);
        printf("                  Compression ratio:  %f:1\n",
               (double)(w * h * ps) / (double)totalJpegSize);
        printf("                  Throughput:         %f Megapixels/sec\n",
               (double)(w * h) / 1000000. / elapsed);
        printf("                  Output bit stream:  %f Megabits/sec\n",
               (double)totalJpegSize * 8. / 1000000. / elapsed);
      }
    } else {
      if (quiet == 1) printf("N/A     N/A     ");
      if (jpegBuf[0]) tjFree(jpegBuf[0]);
      jpegBuf[0] = NULL;
      decompsrc = 1;
    }

    if (w == tilew) ttilew = tw;
    if (h == tileh) ttileh = th;
    if (!(xformOpt & TJXOPT_NOOUTPUT)) {
      if (decomp(NULL, decompsrc ? &srcBuf : jpegBuf,
                 decompsrc ? &srcSize : jpegSize, NULL, tw, th, tsubsamp, 0,
                 fileName, ttilew, ttileh) == -1)
        goto bailout;
    } else if (quiet == 1) printf("N/A\n");

    for (i = 0; i < ntilesw * ntilesh; i++) {
      if (jpegBuf[i]) tjFree(jpegBuf[i]);
      jpegBuf[i] = NULL;
    }
    free(jpegBuf);  jpegBuf = NULL;
    if (jpegSize) { free(jpegSize);  jpegSize = NULL; }

    if (tilew == w && tileh == h) break;
  }

bailout:
  if (file) { fclose(file);  file = NULL; }
  if (jpegBuf) {
    for (i = 0; i < ntilesw * ntilesh; i++) {
      if (jpegBuf[i]) tjFree(jpegBuf[i]);
      jpegBuf[i] = NULL;
    }
    free(jpegBuf);  jpegBuf = NULL;
  }
  if (jpegSize) { free(jpegSize);  jpegSize = NULL; }
  if (srcBuf) { free(srcBuf);  srcBuf = NULL; }
  if (t) { free(t);  t = NULL; }
  if (handle) { tjDestroy(handle);  handle = NULL; }
  return retval;
}

Project: libjpeg-turbo
File: tjbench.c

static int fullTest(unsigned char *srcBuf, int w, int h, int subsamp,
                    int jpegQual, char *fileName)
{
  char tempStr[1024], tempStr2[80];
  FILE *file = NULL;
  tjhandle handle = NULL;
  unsigned char **jpegBuf = NULL, *yuvBuf = NULL, *tmpBuf = NULL, *srcPtr,
    *srcPtr2;
  double start, elapsed, elapsedEncode;
  int totalJpegSize = 0, row, col, i, tilew = w, tileh = h, retval = 0;
  int iter;
  unsigned long *jpegSize = NULL, yuvSize = 0;
  int ps = tjPixelSize[pf];
  int ntilesw = 1, ntilesh = 1, pitch = w * ps;
  const char *pfStr = pixFormatStr[pf];

  if ((unsigned long long)pitch * (unsigned long long)h >
      (unsigned long long)((size_t)-1))
    THROW("allocating temporary image buffer", "Image is too large");
  if ((tmpBuf = (unsigned char *)malloc((size_t)pitch * h)) == NULL)
    THROW_UNIX("allocating temporary image buffer");

  if (!quiet)
    printf(">>>>>  %s (%s) <--> JPEG %s Q%d  <<<<<\n", pfStr,
           (flags & TJFLAG_BOTTOMUP) ? "Bottom-up" : "Top-down",
           subNameLong[subsamp], jpegQual);

  for (tilew = doTile ? 8 : w, tileh = doTile ? 8 : h; ;
       tilew *= 2, tileh *= 2) {
    if (tilew > w) tilew = w;
    if (tileh > h) tileh = h;
    ntilesw = (w + tilew - 1) / tilew;
    ntilesh = (h + tileh - 1) / tileh;

    if ((jpegBuf = (unsigned char **)malloc(sizeof(unsigned char *) *
                                            ntilesw * ntilesh)) == NULL)
      THROW_UNIX("allocating JPEG tile array");
    memset(jpegBuf, 0, sizeof(unsigned char *) * ntilesw * ntilesh);
    if ((jpegSize = (unsigned long *)malloc(sizeof(unsigned long) *
                                            ntilesw * ntilesh)) == NULL)
      THROW_UNIX("allocating JPEG size array");
    memset(jpegSize, 0, sizeof(unsigned long) * ntilesw * ntilesh);

    if ((flags & TJFLAG_NOREALLOC) != 0)
      for (i = 0; i < ntilesw * ntilesh; i++) {
        if (tjBufSize(tilew, tileh, subsamp) > (unsigned long)INT_MAX)
          THROW("getting buffer size", "Image is too large");
        if ((jpegBuf[i] = (unsigned char *)
                          tjAlloc(tjBufSize(tilew, tileh, subsamp))) == NULL)
          THROW_UNIX("allocating JPEG tiles");
      }

    /* Compression test */
    if (quiet == 1)
      printf("%-4s (%s)  %-5s    %-3d   ", pfStr,
             (flags & TJFLAG_BOTTOMUP) ? "BU" : "TD", subNameLong[subsamp],
             jpegQual);
    for (i = 0; i < h; i++)
      memcpy(&tmpBuf[pitch * i], &srcBuf[w * ps * i], w * ps);
    if ((handle = tjInitCompress()) == NULL)
      THROW_TJ("executing tjInitCompress()");

    if (doYUV) {
      yuvSize = tjBufSizeYUV2(tilew, yuvPad, tileh, subsamp);
      if (yuvSize == (unsigned long)-1)
        THROW_TJ("allocating YUV buffer");
      if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL)
        THROW_UNIX("allocating YUV buffer");
      memset(yuvBuf, 127, yuvSize);
    }

    /* Benchmark */
    iter = -1;
    elapsed = elapsedEncode = 0.;
    while (1) {
      int tile = 0;

      totalJpegSize = 0;
      start = getTime();
      for (row = 0, srcPtr = srcBuf; row < ntilesh;
           row++, srcPtr += pitch * tileh) {
        for (col = 0, srcPtr2 = srcPtr; col < ntilesw;
             col++, tile++, srcPtr2 += ps * tilew) {
          int width = min(tilew, w - col * tilew);
          int height = min(tileh, h - row * tileh);

          if (doYUV) {
            double startEncode = getTime();

            if (tjEncodeYUV3(handle, srcPtr2, width, pitch, height, pf, yuvBuf,
                             yuvPad, subsamp, flags) == -1)
              THROW_TJ("executing tjEncodeYUV3()");
            if (iter >= 0) elapsedEncode += getTime() - startEncode;
            if (tjCompressFromYUV(handle, yuvBuf, width, yuvPad, height,
                                  subsamp, &jpegBuf[tile], &jpegSize[tile],
                                  jpegQual, flags) == -1)
              THROW_TJ("executing tjCompressFromYUV()");
          } else {
            if (tjCompress2(handle, srcPtr2, width, pitch, height, pf,
                            &jpegBuf[tile], &jpegSize[tile], subsamp, jpegQual,
                            flags) == -1)
              THROW_TJ("executing tjCompress2()");
          }
          totalJpegSize += jpegSize[tile];
        }
      }
      elapsed += getTime() - start;
      if (iter >= 0) {
        iter++;
        if (elapsed >= benchTime) break;
      } else if (elapsed >= warmup) {
        iter = 0;
        elapsed = elapsedEncode = 0.;
      }
    }
    if (doYUV) elapsed -= elapsedEncode;

    if (tjDestroy(handle) == -1) THROW_TJ("executing tjDestroy()");
    handle = NULL;

    if (quiet == 1) printf("%-5d  %-5d   ", tilew, tileh);
    if (quiet) {
      if (doYUV)
        printf("%-6s%s",
               sigfig((double)(w * h) / 1000000. *
                      (double)iter / elapsedEncode, 4, tempStr, 1024),
               quiet == 2 ? "\n" : "  ");
      printf("%-6s%s",
             sigfig((double)(w * h) / 1000000. * (double)iter / elapsed, 4,
                    tempStr, 1024),
             quiet == 2 ? "\n" : "  ");
      printf("%-6s%s",
             sigfig((double)(w * h * ps) / (double)totalJpegSize, 4, tempStr2,
                    80),
             quiet == 2 ? "\n" : "  ");
    } else {
      printf("\n%s size: %d x %d\n", doTile ? "Tile" : "Image", tilew, tileh);
      if (doYUV) {
        printf("Encode YUV    --> Frame rate:         %f fps\n",
               (double)iter / elapsedEncode);
        printf("                  Output image size:  %lu bytes\n", yuvSize);
        printf("                  Compression ratio:  %f:1\n",
               (double)(w * h * ps) / (double)yuvSize);
        printf("                  Throughput:         %f Megapixels/sec\n",
               (double)(w * h) / 1000000. * (double)iter / elapsedEncode);
        printf("                  Output bit stream:  %f Megabits/sec\n",
               (double)yuvSize * 8. / 1000000. * (double)iter / elapsedEncode);
      }
      printf("%s --> Frame rate:         %f fps\n",
             doYUV ? "Comp from YUV" : "Compress     ",
             (double)iter / elapsed);
      printf("                  Output image size:  %d bytes\n",
             totalJpegSize);
      printf("                  Compression ratio:  %f:1\n",
             (double)(w * h * ps) / (double)totalJpegSize);
      printf("                  Throughput:         %f Megapixels/sec\n",
             (double)(w * h) / 1000000. * (double)iter / elapsed);
      printf("                  Output bit stream:  %f Megabits/sec\n",
             (double)totalJpegSize * 8. / 1000000. * (double)iter / elapsed);
    }
    if (tilew == w && tileh == h && doWrite) {
      snprintf(tempStr, 1024, "%s_%s_Q%d.jpg", fileName, subName[subsamp],
               jpegQual);
      if ((file = fopen(tempStr, "wb")) == NULL)
        THROW_UNIX("opening reference image");
      if (fwrite(jpegBuf[0], jpegSize[0], 1, file) != 1)
        THROW_UNIX("writing reference image");
      fclose(file);  file = NULL;
      if (!quiet) printf("Reference image written to %s\n", tempStr);
    }

    /* Decompression test */
    if (!compOnly) {
      if (decomp(srcBuf, jpegBuf, jpegSize, tmpBuf, w, h, subsamp, jpegQual,
                 fileName, tilew, tileh) == -1)
        goto bailout;
    } else if (quiet == 1) printf("N/A\n");

    for (i = 0; i < ntilesw * ntilesh; i++) {
      if (jpegBuf[i]) tjFree(jpegBuf[i]);
      jpegBuf[i] = NULL;
    }
    free(jpegBuf);  jpegBuf = NULL;
    free(jpegSize);  jpegSize = NULL;
    if (doYUV) {
      free(yuvBuf);  yuvBuf = NULL;
    }

    if (tilew == w && tileh == h) break;
  }

bailout:
  if (file) { fclose(file);  file = NULL; }
  if (jpegBuf) {
    for (i = 0; i < ntilesw * ntilesh; i++) {
      if (jpegBuf[i]) tjFree(jpegBuf[i]);
      jpegBuf[i] = NULL;
    }
    free(jpegBuf);  jpegBuf = NULL;
  }
  if (yuvBuf) { free(yuvBuf);  yuvBuf = NULL; }
  if (jpegSize) { free(jpegSize);  jpegSize = NULL; }
  if (tmpBuf) { free(tmpBuf);  tmpBuf = NULL; }
  if (handle) { tjDestroy(handle);  handle = NULL; }
  return retval;
}

Project: libjpeg-turbo
File: tjbench.c

static int decomp(unsigned char *srcBuf, unsigned char **jpegBuf,
                  unsigned long *jpegSize, unsigned char *dstBuf, int w, int h,
                  int subsamp, int jpegQual, char *fileName, int tilew,
                  int tileh)
{
  char tempStr[1024], sizeStr[24] = "\0", qualStr[13] = "\0", *ptr;
  FILE *file = NULL;
  tjhandle handle = NULL;
  int row, col, iter = 0, dstBufAlloc = 0, retval = 0;
  double elapsed, elapsedDecode;
  int ps = tjPixelSize[pf];
  int scaledw = TJSCALED(w, sf);
  int scaledh = TJSCALED(h, sf);
  int pitch = scaledw * ps;
  int ntilesw = (w + tilew - 1) / tilew, ntilesh = (h + tileh - 1) / tileh;
  unsigned char *dstPtr, *dstPtr2, *yuvBuf = NULL;

  if (jpegQual > 0) {
    snprintf(qualStr, 13, "_Q%d", jpegQual);
    qualStr[12] = 0;
  }

  if ((handle = tjInitDecompress()) == NULL)
    THROW_TJ("executing tjInitDecompress()");

  if (dstBuf == NULL) {
    if ((unsigned long long)pitch * (unsigned long long)scaledh >
        (unsigned long long)((size_t)-1))
      THROW("allocating destination buffer", "Image is too large");
    if ((dstBuf = (unsigned char *)malloc((size_t)pitch * scaledh)) == NULL)
      THROW_UNIX("allocating destination buffer");
    dstBufAlloc = 1;
  }
  /* Set the destination buffer to gray so we know whether the decompressor
     attempted to write to it */
  memset(dstBuf, 127, (size_t)pitch * scaledh);

  if (doYUV) {
    int width = doTile ? tilew : scaledw;
    int height = doTile ? tileh : scaledh;
    unsigned long yuvSize = tjBufSizeYUV2(width, yuvPad, height, subsamp);

    if (yuvSize == (unsigned long)-1)
      THROW_TJ("allocating YUV buffer");
    if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL)
      THROW_UNIX("allocating YUV buffer");
    memset(yuvBuf, 127, yuvSize);
  }

  /* Benchmark */
  iter = -1;
  elapsed = elapsedDecode = 0.;
  while (1) {
    int tile = 0;
    double start = getTime();

    for (row = 0, dstPtr = dstBuf; row < ntilesh;
         row++, dstPtr += (size_t)pitch * tileh) {
      for (col = 0, dstPtr2 = dstPtr; col < ntilesw;
           col++, tile++, dstPtr2 += ps * tilew) {
        int width = doTile ? min(tilew, w - col * tilew) : scaledw;
        int height = doTile ? min(tileh, h - row * tileh) : scaledh;

        if (doYUV) {
          double startDecode;

          if (tjDecompressToYUV2(handle, jpegBuf[tile], jpegSize[tile], yuvBuf,
                                 width, yuvPad, height, flags) == -1)
            THROW_TJ("executing tjDecompressToYUV2()");
          startDecode = getTime();
          if (tjDecodeYUV(handle, yuvBuf, yuvPad, subsamp, dstPtr2, width,
                          pitch, height, pf, flags) == -1)
            THROW_TJ("executing tjDecodeYUV()");
          if (iter >= 0) elapsedDecode += getTime() - startDecode;
        } else if (tjDecompress2(handle, jpegBuf[tile], jpegSize[tile],
                                 dstPtr2, width, pitch, height, pf,
                                 flags) == -1)
          THROW_TJ("executing tjDecompress2()");
      }
    }
    elapsed += getTime() - start;
    if (iter >= 0) {
      iter++;
      if (elapsed >= benchTime) break;
    } else if (elapsed >= warmup) {
      iter = 0;
      elapsed = elapsedDecode = 0.;
    }
  }
  if (doYUV) elapsed -= elapsedDecode;

  if (tjDestroy(handle) == -1) THROW_TJ("executing tjDestroy()");
  handle = NULL;

  if (quiet) {
    printf("%-6s%s",
           sigfig((double)(w * h) / 1000000. * (double)iter / elapsed, 4,
                  tempStr, 1024),
           quiet == 2 ? "\n" : "  ");
    if (doYUV)
      printf("%s\n",
             sigfig((double)(w * h) / 1000000. * (double)iter / elapsedDecode,
                    4, tempStr, 1024));
    else if (quiet != 2) printf("\n");
  } else {
    printf("%s --> Frame rate:         %f fps\n",
           doYUV ? "Decomp to YUV" : "Decompress   ", (double)iter / elapsed);
    printf("                  Throughput:         %f Megapixels/sec\n",
           (double)(w * h) / 1000000. * (double)iter / elapsed);
    if (doYUV) {
      printf("YUV Decode    --> Frame rate:         %f fps\n",
             (double)iter / elapsedDecode);
      printf("                  Throughput:         %f Megapixels/sec\n",
             (double)(w * h) / 1000000. * (double)iter / elapsedDecode);
    }
  }

  if (!doWrite) goto bailout;

  if (sf.num != 1 || sf.denom != 1)
    snprintf(sizeStr, 24, "%d_%d", sf.num, sf.denom);
  else if (tilew != w || tileh != h)
    snprintf(sizeStr, 24, "%dx%d", tilew, tileh);
  else snprintf(sizeStr, 24, "full");
  if (decompOnly)
    snprintf(tempStr, 1024, "%s_%s.%s", fileName, sizeStr, ext);
  else
    snprintf(tempStr, 1024, "%s_%s%s_%s.%s", fileName, subName[subsamp],
             qualStr, sizeStr, ext);

  if (tjSaveImage(tempStr, dstBuf, scaledw, 0, scaledh, pf, flags) == -1)
    THROW_TJG("saving bitmap");
  ptr = strrchr(tempStr, '.');
  snprintf(ptr, 1024 - (ptr - tempStr), "-err.%s", ext);
  if (srcBuf && sf.num == 1 && sf.denom == 1) {
    if (!quiet) printf("Compression error written to %s.\n", tempStr);
    if (subsamp == TJ_GRAYSCALE) {
      unsigned long index, index2;

      for (row = 0, index = 0; row < h; row++, index += pitch) {
        for (col = 0, index2 = index; col < w; col++, index2 += ps) {
          unsigned long rindex = index2 + tjRedOffset[pf];
          unsigned long gindex = index2 + tjGreenOffset[pf];
          unsigned long bindex = index2 + tjBlueOffset[pf];
          int y = (int)((double)srcBuf[rindex] * 0.299 +
                        (double)srcBuf[gindex] * 0.587 +
                        (double)srcBuf[bindex] * 0.114 + 0.5);

          if (y > 255) y = 255;
          if (y < 0) y = 0;
          dstBuf[rindex] = abs(dstBuf[rindex] - y);
          dstBuf[gindex] = abs(dstBuf[gindex] - y);
          dstBuf[bindex] = abs(dstBuf[bindex] - y);
        }
      }
    } else {
      for (row = 0; row < h; row++)
        for (col = 0; col < w * ps; col++)
          dstBuf[pitch * row + col] =
            abs(dstBuf[pitch * row + col] - srcBuf[pitch * row + col]);
    }
    if (tjSaveImage(tempStr, dstBuf, w, 0, h, pf, flags) == -1)
      THROW_TJG("saving bitmap");
  }

bailout:
  if (file) fclose(file);
  if (handle) tjDestroy(handle);
  if (dstBuf && dstBufAlloc) free(dstBuf);
  if (yuvBuf) free(yuvBuf);
  return retval;
}