#!/usr/bin/env python import sys from math import sqrt MAXPIXELS = 480*360 MAXX = 480 MAXY = 360 #MAXPIXELS = 480 * 272 #MAXX = 480 #MAXY = 272 x, y = float(sys.argv[1]), float(sys.argv[2]) if len(sys.argv) >= 4: ratio = float(sys.argv[-1]) else: ratio = x / y bestpixels = min((x * y), MAXPIXELS) c = [] for ix in range(8, MAXX + 1, 8): for iy in range(8, MAXY + 1, 8): xt, yt = float(ix), float(iy) rt = xt / yt dres = abs((xt * yt - bestpixels) / bestpixels) dres = sqrt(dres) if (xt * yt) > bestpixels: dres = sqrt(dres) / 10 else: dres = dres / 3 drat = ((1 - (ratio / rt)) * 5) ** 2 if (xt * yt) <= MAXPIXELS: c.append([drat + dres, xt, yt, rt, xt * yt, dres]) c.sort(lambda x,y: cmp(x[0], y[0])) nx, ny = c[0][1], c[0][2] nratio = float(nx) / float(ny) distortion = abs(nratio - ratio) utilisation = (nx * ny) / MAXPIXELS * 100 scale = (nx * ny) / (x * y) * 100 sys.stderr.write("aspect: %.3f -> %.3f, distortion=%.3f, pixel_utilisation=%.1f%%, scale=%.1f%%\n" % (ratio, nratio, distortion, utilisation, scale)) print "%dx%d" % (nx, ny)