1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
#! /usr/bin/env python
'''
BorderPatrol all-in-one ripping/encoding driver & menu system

It needs:

- Python 2.6.x, with pythondialog module (tested on version 2.7)
- dialog (any post 2008 build)
- GNU Screen (tested on 4.0.3)
- eject (tested on 2.1.5)
- vobcopy (tested on 1.2.0)
- ddrescue (tested on 1.11)
- mplayer, with x264 support (tested on mplayer svn r31008, and x264 git
  pulled on the Fri Mar 26, 2010).
- ffmpeg (tested on SVN r22949, with multichannel vorbis patch, see issue 1325
  from ffmpeg tracker, and libvorbis support compiled in)
- sox (tested on 13.2.0)
- oggenc (tested on vorbis-tools 1.4.0, libvorbis 1.3.1, libogg 1.1.4)
- mkvtoolnix (tested on 3.3.0)
- POSIX-compliant versions of df (tested on coreutils 7.5), 
  and mount (tested on util-linux 2.14.2). 

Current user should also have ability to mount the cdroms, as well as permission
to execute /sbin/halt and /sbin/ifconfig (for info purpose only)

Sylvain Fourmanoit, 2010.
'''
#------------------------------------------------------------------------------
import os, re, pprint, shutil, copy
import subprocess, shlex, time
import logging, logging.handlers
import contextlib
import hashlib

import dialog

#------------------------------------------------------------------------------
# Hard-coded constants
basedir = '/mnt/vault/data'
cdrom_device = '/dev/cdrom'
cdrom_mountpoint = '/mnt/cdrom'

#------------------------------------------------------------------------------
@contextlib.contextmanager
def get_preferences(dirpath = '', postprocess = None, **defaults):
    '''
    Manager to load and save the global preferences
    '''
    # Load the preferences
    prefsname = os.path.join(basedir, dirpath, 'preferences.txt')
    prefs = {}
    try:
        exec file(prefsname) in prefs
    except:
        logging.warning('error loading preferences from %s' % prefsname)
    prefs = prefs.get('prefs', {})
    
    # Add some default to preferences
    for k, v in defaults.iteritems():
        if k not in prefs:
            prefs[k] = v

    # Yield back control
    try:
        yield prefs
    finally:
        # Save preferences back
        if callable(postprocess):
            postprocess(prefs)
        with file(prefsname, 'w') as out:
            out.write('# Below are ripping/encoding preferences:\n'
                      '# modify them at your own risk!\n\n'
                      'prefs = ')
            pprint.pprint(prefs, stream = out)

#------------------------------------------------------------------------------
call_output_redirect = {
    'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE}
call_output_redirect_merge = {
    'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT}

class SentinelError(Exception): 
    pass

class DummyDeadProcess(object):
    def poll(self):        
        return -1
    def communicate(self): 
        return '', ''

def is_success(p): 
    return p.poll() == 0

def call_and_check(cmdline, sentinel, interval = 2, ok_retcodes = (0, ),
                   stdin = None, stdout = None, stderr = None, verbose = True):
    '''
    Generic subprocess call driver
    '''
    def send_signal(p, signal):
        for i in xrange(5):
            if p.poll() is None:
                if signal == 'SIGTERM':
                    p.terminate()
                else:
                    p.kill()
                d = 2**i * .125
                logging.info('%s sent, waiting %.3f seconds' % (signal, d))
                time.sleep(d)
            else:
                break
        else:
            return False
        return True
            
    if verbose is True: 
        logging.info('+ %s' % cmdline)
    p = subprocess.Popen(args = shlex.split(cmdline),
                         stdin = stdin, stdout = stdout, stderr = stderr)
    try:
        while sentinel() is True:
            if p.poll() is not None:
                break
            time.sleep(interval)
    except SentinelError as e:
        logging.error(e)
    except KeyboardInterrupt:
        logging.warning(
            'command "%s" interrupted interactively by user' % cmdline)
    finally:
        if not send_signal(p, 'SIGTERM') and not send_signal(p, 'SIGKILL'):
            if verbose is True:
                logging.warning('failed to kill command "%s"' % cmdline)
            p = DummyDeadProcess()
        if verbose is True:
            ret = p.poll()
            if ret not in ok_retcodes:
                logging.error('command "%s" failed with return value %d' % 
                              (cmdline, ret))        
    return p

#------------------------------------------------------------------------------
def call(cmdline, **kw):
    '''
    Simple call, with dummy sentinel
    '''
    args = {'sentinel': lambda:True, 'interval': .1}
    args.update(kw)
    return call_and_check(cmdline, **args)

def call_output(cmdline):
    '''
    Just get stdout
    '''
    p = call(cmdline, **call_output_redirect_merge)
    return p.communicate()[0] if p.poll() == 0 else None

#------------------------------------------------------------------------------
def call_with_timeout(cmdline, timeout, **kw):
    '''
    Call with a timeout, in seconds
    '''
    class TimeoutSentinel(object):
        def __init__(self, timeout):
            self.timeout = timeout
            self.count = 0
        def __call__(self):
            self.count += 1
            if self.count > self.timeout:
                raise SentinelError(
                    'operation timed out (%d seconds)' % timeout)
            return True
    kw.update({'sentinel': TimeoutSentinel(timeout), 'interval': 1})
    p = call_and_check(cmdline, **kw)
    return p

#------------------------------------------------------------------------------
def call_with_path_monitor(cmdline, path, retries = 5, **kw):
    '''
    Call with path monitoring: it returns if a file/directory stop growing for
    too long.
    '''
    class PathSentinel(object):
        def __init__(self, path, retries = 5):
            self.path = path
            self.retries = retries
            self.size = 0
            self.count = 0
        def _du(self):
            for root, dirs, files in os.walk(self.path):
                yield sum(
                    os.path.getsize(os.path.join(root, name)) for name in files)
        def du(self):
            if os.path.isdir(self.path):
                return sum(self._du())
            elif os.path.isfile(self.path):
                return os.path.getsize(self.path)
            else:
                return 0
        def __call__(self):
            size = self.du()
            if size == self.size:
                self.count += 1
                if self.count >= self.retries:
                    raise SentinelError(
                        'process seemed hanged up, size of %s stuck to %d' % 
                        (self.path, size))
            else:
                self.size = size
                self.count = 0
            return True
    kw.update({'sentinel': PathSentinel(path, retries)})
    return call_and_check(cmdline, **kw)

#------------------------------------------------------------------------------
def vobcopy(path = 'dvdrip'):
    return call_with_path_monitor('vobcopy -t "%s" -m' % path, path)

#------------------------------------------------------------------------------
def dvdinfo(device = cdrom_device, title = 1):
    '''
    Collect and organize DVD info using mplayer
    '''
    def convert(field):
        for typ in (int, float, str):
            try:
                return typ(field)
            except ValueError:
                pass
    # Scan info from mplayer output
    logging.info('scanning DVD for info')
    output = call_output(
        'mplayer -dvd-device "%s" dvd://%d -identify -frames 0' % (
            device, title))
    if output is None:
        return
    fields = dict(
        (field.lower(), convert(value)) 
        for field, value in re.compile('^ID_(\w+)=(.*)$', re.M).findall(
            output))

    # Check for minimal characteristics
    if 'dvd_titles' not in fields:
        logging.error('Extremely incomplete disc, '
                      'deemed unusable by the system.')
        return
    
    # Organize titles characteristics
    for name in ('chapters', 'length', 'angles'): 
        fields['dvd_titles_%s' % name] = []
        for title in xrange(fields['dvd_titles']):
            field = 'dvd_title_%d_%s' % (title + 1, name)
            fields['dvd_titles_%s' % name].append(fields.get(field, 0))
            try:
                del fields[field]
            except KeyError:
                pass

    # Organize audio/subtitles tracks characteristics
    for pfx in ('aid', 'sid'):
        fields['%s_langs' % pfx] = {}
        for name in fields:
            m = re.match('%s_([0-9]+)_lang' % pfx, name)
            if m is not None:
                fields['%s_langs' % pfx][int(m.group(1))] = fields[name]
        for track in fields['%s_langs' % pfx]:
            del fields['%s_%d_lang' % (pfx, track)]

    # Isolate supplementary titbits on audio tracks
    fields['aid_formats'] = dict(
        (int(m[1]), m[0]) 
        for m in re.compile(
            '^audio stream: .* format: (.*) language: .* aid: ([0-9]+)\.$',
            re.M).findall(output))
    return fields


#------------------------------------------------------------------------------
def df(path):
    '''
    Report file system disk usage as a tuple (total, available)
    '''
    ret = call_output('df "%s"' % path)
    if ret is not None:
        return [int(c) for c in ret.split('\n')[1].split()[2:4]]
    else:
        return [0, 0]

#------------------------------------------------------------------------------
def sanitize_dvd_volume_id(volid):
    if volid is not None:
        return re.sub('[^0-9a-z]+', '_', volid.lower()).strip('_')

def rip(prefs, d):
    '''
    Implement ripping action of the main menu
    '''
    # Insert the disc
    call('eject')
    code = d.msgbox(('Insert your DVD in the tray now, then press OK '
                     '(or press escape twice to bailout).'),
                    title = 'Disk Insertion')
    if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
        call('eject -t')
        return

    try:
        # Specify default status (see finally clause below)
        status = 'No ripping took place.'

        # Mount the disc
        mount = call('mount %s' % cdrom_mountpoint)
        if mount.poll() != 0:
            d.msgbox('Could not read the disk: either no one was inserted, '
                     'or there is something wrong with it or the system '
                     '(try cleaning it).',
                     title = 'Disk Insertion Error')
            return

        # Get disk info
        logging.info('disk is properly mounted')
        info = dvdinfo()
        sugg = sanitize_dvd_volume_id(
            info.get('dvd_volume_id', info['dvd_disc_id']))
        name = sanitize_dvd_volume_id(prefs['ids'].get(info['dvd_disc_id']))

        # Define & validate disk name
        if name is not None:
            msg = ('This disk has previously been put into the system. '
                   'Originally suggested name was "%s", while '
                   'current name is (you generally should not change '
                   'this, unless you purposely want to create a dupe, or '
                   'if you already purged the system from an old rip '
                   'via management):') % sugg
        else:
            name = sugg
            msg = 'This disk is new to the system. Name it:'
        while True:
            code, answer = d.inputbox(msg, init=name, nocancel = True,
                                      help_button = True,
                                      width = 60, height = 15,
                                      title = 'Naming the DVD on disk')
            if code == d.DIALOG_OK:
                name = sanitize_dvd_volume_id(answer)
                if len(name) == 0:
                    msg = 'Cleaned up name is empty. Please correct it:'
                elif name != answer:
                    msg = ('Choosen name had to be slightly cleaned up. '
                           'It is now (you can still change it):')
                else:
                    prefs['ids'][info['dvd_disc_id']] = name
                    break
            elif code == d.DIALOG_HELP:
                d.msgbox(
                    'This name is just a human-readable way to label '
                    'the DVD on disk. It should be unique, and only '
                    'contain lower-case alphanumerical characters '
                    'as well as non-consecutives, non terminal '
                    'underscores.', 
                    width = 60, 
                    title = 'Naming Conventions')

        # Check for space
        logging.info('determining if enough space is available...')
        dvd_size  = df(cdrom_mountpoint)[0]
        hdd_space = df(basedir)[1]
        if dvd_size + 20000000 > hdd_space:
                d.msgbox('There would be less than 20 GB available on disk '
                         'once this DVD is ripped, which would not provide '
                         'enough room for encoding anyway: please cleanup the '
                         'system before performing this rip.',
                         width = 60,
                         title = 'Not Enough Space Left')
                return

        # Make sure project dir exists
        projdir = os.path.join(basedir, name)
        if not os.path.isdir(projdir):
            logging.info(
                'directory "%s" does not exist, creating it' % projdir)
            os.mkdir(projdir)
        os.chdir(projdir)

        # Acquire (or create) the project preferences:
        # - info: the dvdinfo dictionnary
        #
        with get_preferences(projdir, info = info) as proj:
            	# Check that the DVD matches the on-disk structure.
                if proj['info']['dvd_disc_id'] != info['dvd_disc_id']:
                    d.msgbox(('The disc originally scanned under the "%s" name '
                              'is different from the one currently in '
                              'the drive. You should either give '
                              'this DVD another name on disk, or purge '
                              'the disk (using the management menu).') % name,
                             width = 60,
                             title = 'non-matching disk')
                    return

                # Cleanup existing rip
                rippath = os.path.join(projdir, 'dvdrip')
                if os.path.isdir(rippath):
                    # Directory => successfull, normal rip
                    if d.yesno(
                        ('There is already a presumably working rip of this '
                         'DVD in the system. Are you sure you want '
                         'to replace it?'),
                         width = 60,
                         title = 'Full DVD Rip Available',
                         defaultno = True) == d.DIALOG_OK:
                        logging.info('recursively removing "%s"' % rippath)
                        shutil.rmtree(rippath)
                    else:
                        return
                elif os.path.isfile(rippath):
                    # File => presumably partial, incomplete rip
                    if d.yesno(
                        ('There is already a partial, presumably incomplete '
                         'rip of this DVD in the system. Do you wish to throw '
                         'it away (answer "no" to keep salvaging it)?'),
                        width = 60,
                        title = 'Partial DVD Rip Available',
                         defaultno = True) == d.DIALOG_OK:
                        logging.info('unlinking "%s"' % rippath)
                        os.unlink(rippath)
                        try:
                            os.unlink(os.path.join(projdir, 'dvd.log'))
                        except OSError:
                            pass
                
                # Allow mode selection
                if not os.path.isfile(rippath):
                    while True:
                        code, tag = d.radiolist(
                            'How bad do you want that rip?',
                            width = 60,
                            choices = [
                                ('Meh', 'Just try normally', 1),
                                ('Real Bad', 'Use aggressive recovery', 0)],
                            title = 'Choose Ripping Mode',
                            help_button = True,
                            nocancel = True)
                        if code == d.DIALOG_OK:
                            normal_mode = (tag == 'Meh')
                            break
                        elif code == d.DIALOG_HELP:
                            if tag == 'HELP Meh':
                                msg = (
                                    'This is what you should always choose '
                                    'on a first run: it\'s reasonnably fast, '
                                    'and effective on most relatively '
                                    'unscratched discs.')
                                title = 'Normal Ripping Mode'
                            else:
                                msg = (
                                    'Use this if you really have no choice: '
                                    'if for instance you tried the normal '
                                    'method on a couple of copies '
                                    'without success, or if you have one '
                                    'of those lovely ARccOS-authored '
                                    'disk from Sony Pictures. Be warned '
                                    'that it can be painfully slow. '
                                    'Finally, be aware that it\'s OK to '
                                    'interrupt it at will: unlike a normal rip '
                                    'which is a one-shot deal, you can resume '
                                    'a recovery rip at any point '
                                    'in the future: if you have multiple '
                                    'identical copies of a disk, you can '
                                    'switch between them; if you feel the DVD '
                                    'might be dirty, you can clean it up and '
                                    'put it back.')
                                title = 'Recovery Ripping Mode'
                            d.msgbox(msg, width = 60, title = title)
                else:
                    normal_mode = False

                # Finally, time to perform the rip
                if normal_mode is True:
                    if vobcopy().poll() == 0:
                        status = ('The normal rip procedure completed '
                                  'successfully.')
                    else:
                        logging.info('removing partial rip "%s" from disk' % 
                                     rippath)
                        shutil.rmtree(rippath)
                        status = ('The normal rip procedure failed, '
                                  'and the unusuable partial rip was deleted.')
                else:
                    logging.info('run the recovery rip - '
                                 'if you feel this is getting nowhere, '
                                 'feel free to manually interrupt (^C), '
                                 'you can always resume it later.')
                    p = call('ddrescue -n %s dvdrip dvd.log' % cdrom_device) 
                    status = ('A recovery rip was performed: usability '
                              'of resulting image is unknown.')

    finally:
        call('eject')
        d.msgbox('%s Don\'t forget your DVD!' % status, 
                 title = 'Disk Removal', ok_label = 'I got it back now')
        call('eject -t')
    
#------------------------------------------------------------------------------
def prepare(prefs, d):
    '''
    Implement prepare action of the main menu
    '''
    # Find the projects
    projects = [item for item in os.listdir(basedir)
                if (item not in ('final', ) and 
                    os.path.isdir(os.path.join(basedir, item)))]

    # Bailout if no projects are available
    if len(projects) == 0:
        d.msgbox('No rips to work on: please rip something first.',
                 title = 'Nothing to Prepare')
        return

    # Ask the user which project he wants to work on
    try:
        selected = projects.index(prefs['last_prep'])
    except ValueError:
        selected = 0

    code, tag = d.radiolist(
        'Which rip do you want to schedule for encoding?',
        width = 60,
        choices = [(str(i+1), project, 1 if i == selected else 0) 
                   for i, project in enumerate(projects)],
        title = 'Choose Encoding to Prepare')
    
    if code != d.DIALOG_OK:
        return
    prefs['last_prep'] = projname = projects[int(tag)-1]
    projdir = os.path.join(basedir, projname)

    # Go the the project dir, and get the preferences
    class PostProcess(object):
        '''
        Post-Process hook: validate the settings one last time,
        and remove invalid scheduled encodings.
        '''
        def __init__(self, d, prefs, projname):
            self.d = d
            self.prefs = prefs
            self.projname = projname
        def __call__(self, proj):
            err = None
            if (proj['tracks'] is None or len(proj['tracks']) == 0):
                err = 'No tracks were detected for the selected title.'
            elif max(proj['tracks']) < 128:
                err = 'No audio track were selected.'
            if err is not None:
                if self.projname in self.prefs['encodings']:
                    self.prefs['encodings'].remove(self.projname)
                    self.d.msgbox('The scheduled encoding for "%s" '
                                  'has been automatically cancelled. %s' %
                                  (self.projname, err),
                                  title = 'Encoding Cancellation')
                proj['title'] = 1
                proj['tracks'] = None
                     
    os.chdir(projdir)
    with get_preferences(
        projdir, postprocess = PostProcess(d, prefs, projname),
        title = 1, tracks = None, 
        telecine = False, nr = 0, crf = 26, preview = False) as proj:
        # Check that a rip is available
        rippath = os.path.join(projdir, 'dvdrip')
        if not os.path.exists(rippath):
            d.msgbox(
                'There is no rip available in "%s". Please add a rip '
                'under that name first.' %
                projname,
                title = 'No Rip Present')
            return
        # Give warning in case of partial rip
        elif os.path.isfile(rippath):
            d.msgbox(
                'The rip available here was produced using recovery ripping: '
                'usability is unknown.',
                title = 'Partial Rip Available')

        # Extract info from rip
        def refresh_dvdinfo(d, rippath, proj):
            '''
            Refresh dvd info & available tracks
            '''
            def refresh_tracks(proj, force = False):
                if force is True or proj['tracks'] is None:
                    proj['tracks'] =  (proj['info']['aid_langs'].keys() + 
                                       proj['info']['sid_langs'].keys())

            try:
                need_refresh = (proj['title'] != 
                                proj['info']['dvd_current_title'])
            except:
                need_refresh = True

            if need_refresh is True:
                info = dvdinfo(rippath, proj['title'])
                if info is None:
                    d.msgbox(
                        'Error getting basic disc info out of the rip '
                        'for title %d: rip seems severely incomplete '
                        'or corrupted. You should try ripping it again.' % 
                        proj['title'],
                        title = 'DVD Structural Error')
                    return False
                else:
                    proj['info'] = info
                    proj['tracks'] = None

            refresh_tracks(proj)            
            if len(proj['tracks']) == 0:
                # No track: try to find first title with a track.
                logging.info('chosen title %d has no track, '
                             'revert to first title with a track' % 
                             proj['title'])
                for title in xrange(proj['info']['dvd_titles']):
                    proj['info'] = dvdinfo(rippath, title)
                    refresh_tracks(proj, force = True)
                    if len(proj['tracks']) > 0:
                        proj['title'] = title
                        break
                else:
                    d.msgbox('No tracks were detected for title %d: '
                             'this is wrong. Your rip is broken, '
                             'at least for this title. Bailing out.' % 
                             proj['title'],
                             title = 'DVD Structural Error')
                    return False
            return True

        # Make sure the dvdinfo is up to date
        if not refresh_dvdinfo(d, rippath, proj):
            return

        # Validate/autoselect title
        def title_autoselect(d, rippath, proj):
            proj['title'] = max(enumerate(proj['info']['dvd_titles_length']), 
                                key = lambda i:i[1])[0] + 1
            # Update DVD info & Tracks
            return refresh_dvdinfo(d, rippath, proj)
        if (proj['title'] is None or
            proj['title'] <= 0 or 
            proj['title'] >= len(proj['info']['dvd_titles_length'])):
            # No title selected, ot title out of range: select the longuest
            if title_autoselect(d, rippath, proj) is False:
                return

        # Help Blurps
        helpmsgs = {
            'Title':
                ('A DVD is composed of a number of titles: '
                 'some are menus, some are clips, etc. One of them '
                 'is the movie you want. If we exclude TV series, '
                 '95% of the time, the longest title is the one you '
                 'are interested in (it\'s the one selected '
                 'by default). You can change it here.'),
            'Tracks':
                ('A DVD title generally has multiple tracks: '
                 'multiple audio scores, multiple subtitles. '
                 'You can restrict '
                 'the ones you are interested in here. There '
                 'are a few things you need to consider: DTS audio '
                 'tracks should generally be avoided. If there is '
                 'both a 5.1 and stereo version of the main score, '
                 'the stereo version will always be a superior '
                 'source for a stereo encoding. Finally, losts of '
                 'disks are poorly edited when it comes '
                 'to subtitles: it\'s not because there is a track '
                 'announced that there will be something in it: '
                 'always check after encoding this French '
                 'subtitle you selected is not empty.'),
            'Telecine':
                ('Most foreign movies coming from countries '
                 'where PAL is the TV standard (most of Europe '
                 '& the middle east), as well as many high-quality '
                 'TV series come telecined on the north american '
                 'market via some 2:3 pulldown variant. '
                 'Problem with this is that the interlaced nature '
                 'of these sources make them very nasty to watch '
                 'outside of a TV, and it needs to be corrected. '
                 'Enable this filter to take care of it. '
                 '*DO NOT* use it unless you know you need it, '
                 'as it will generally make the image fuzier, '
                 'and the encoding less space-efficient.'),
            'Noise': 
                ('If your have a low-budget film (such as Clerks), '
                 'a very dark, low-contrast zombie movie '
                 'or a VHS to DVD transfert, you could end up '
                 'with a very grainy image. Grain is OK, but it can '
                 'cost a lot to encode. Use this option to filter '
                 'some of the noise out if you get a especially big '
                 'encoding: useful values are in '
                 'the [100, 1000] interval (bigger value: '
                 'bigger noise reduction). A value of zero means '
                 'no reduction at all. Be aware than most if not '
                 'all big studio DVDs released after 2004 are '
                 'edited to avoid excessive graininess, '
                 'and will not benefit from this.'),
            'Quality': 
                ('Encoding use a constant ratefactor: what it means '
                 'is that it tries to preserve a constant "visual '
                 'quality" (yeah... so from a user perspective '
                 'it\'s a black box -- just ask the '
                 'conceptor if you want details). It\'s '
                 'modeled here as a single scalar value, defaulting '
                 'to 26. The range [18, 28] '
                 'is probably where you want to look at. The higher '
                 'the number, the lower the quality and the smaller '
                 'the size. For a DVD, a value of 16 is almost '
                 'non-distinguishable from the source, but usually '
                 'the same size too. Accepted values are integers '
                 'in the [15, 30] range. Only toy with this '
                 'if you are not satisfied with the default.'),
            'Reset':
                ('Reset all parameters to their original, '
                 'default values: use longest title on disc, '
                  'all tracks selected, no telecine, no noise reduction, '
                  'a visual quality of 26, and perform a full encode.'),
            'Preview':
                ('Only encode a 2 minutes preview, '
                 'from the start of the film with the first selected '
                 'audio track. Generated video is exactly the same '
                 'that would be generated from a full encode, but audio '
                 'is lossless. Result of a preview is called "out.avi", '
                 'while result of a full encode is "out.mkv". Needless '
                 'to say, encoding only a preview is a lot faster '
                 'than a full movie.'),
            'Fire in the hole!':
                ('Request an encoding using the set parameters, '
                 'and add it to the list of the encodings '
                 'to perform. Once it\'s done, you should start '
                 'the encoding itself via the "Encode" item in the '
                 'main menu. Until then, you can come back '
                 'as often as you like to the preparation menu '
                 'to change the parameters.'),
            'Changed my mind.':
                ('Remove current rip from the list of encoding to '
                 'perform.')
            }

        def describe_quality(crf):
            '''For quality selection feedback'''
            if crf > 28:
                return 'probably too low'
            if crf > 26:
                return 'lower than default'
            elif crf == 26:
                return 'default'
            elif crf >= 23:
                return 'higher than default'
            elif crf >= 20:
                return 'significanly higher than default'
            elif crf >= 18:
                return 'really high'
            else:
                return 'probably too high'

        # We got everything: time for the menu
        while True:
            scheduled = projname in prefs['encodings']
            code, tag = d.menu(
                'This is "%s". What do you want to do?' % projname,
                width = 60, height = 15, menu_height = 8,
                choices = [
                    ('Title', 
                     'Change title  (Title %d selected)' % proj['title']),
                    ('Tracks',
                     'Change tracks (%s track(s) selected)' % 
                     len(proj['tracks'])),
                    ('Telecine', 'Perform inverse telecine (%s)' % 
                     ('Yes' if proj['telecine'] else 'No')),
                    ('Noise', 'Setup noise reduction (%s)' %
                     ('Disabled' if proj['nr'] == 0 else proj['nr'])),
                    ('Quality', 'Setup visual quality (%s)' % 
                     ('Default' if proj['crf'] == 26 else proj['crf'])),
                    ('Preview', 'Only encode a preview (%s)' %
                     ('Yes' if proj['preview'] else 'No')),
                    ('Reset', 'Revert all settings to default'),
                    (('Fire in the hole!' 
                      if not scheduled else 'Changed my mind.'), 
                     ('Schedule an encoding' 
                      if not scheduled else 'Unschedule the encoding'))],
                title = 'Encoding Preparation Menu',
                cancel = 'Exit',
                help_button = True)
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                break
            elif str(code) == 'help':
                d.msgbox(helpmsgs[tag], width = 60, height = 15, 
                         title = 'Help on %s' % tag)

            elif code == d.DIALOG_OK:
                if tag == 'Title':
                    while True:
                        code, tag = d.radiolist(
                            'Select the title you are interested in:',
                            width = 60,
                            choices = [
                                (str(i+1), 
                                 '%d seconds, %d chapter(s)' % (length, chaps),
                                 (1 if (i == proj['title'] -1) else 0))
                                for i, (length, chaps) in 
                                enumerate(
                                    zip(proj['info']['dvd_titles_length'], 
                                        proj['info']['dvd_titles_chapters']))
                                ],
                            title = 'DVD Title Selection',
                            help_button = True)
                        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                            break
                        elif code == d.DIALOG_HELP:
                            d.msgbox(helpmsgs['Title'],
                                     width = 60, title = 'Help on Title')
                        elif code == d.DIALOG_OK:
                            proj['title'] = int(tag)
                            if not refresh_dvdinfo(d, rippath, proj):
                                return
                            break
                elif tag == 'Tracks':
                    tracks = copy.deepcopy(proj['tracks'])
                    while True:
                        code, tag = d.checklist(
                            'Select the tracks you are interested in:',
                            width = 60,
                            choices = ([(str(aid), 'audio, %s, %s' % (
                                            lang, 
                                            proj['info']['aid_formats'][aid]), 
                                         1 if aid in tracks else 0)
                                        for aid, lang in 
                                        proj['info']['aid_langs'].iteritems()] +
                                       [(str(sid), 'subtitle, %s' % lang, 
                                         1 if sid in tracks else 0)
                                        for sid, lang in
                                        proj['info']['sid_langs'].iteritems()]),
                            title = ('DVD Title %d Tracks Selection' % 
                                     proj['title']),
                            help_button = True)
                        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                            break
                        elif code == d.DIALOG_HELP:
                            d.msgbox(helpmsgs['Tracks'],
                                     width = 60, title = 'Help on Tracks')
                        elif code == d.DIALOG_OK:
                            tracks = [int(i) for i in tag]
                            if max(tracks) >= 128:
                                proj['tracks'] = tracks
                                break
                            else:
                                d.msgbox(('No audio track selected. You need '
                                          'to keep at least one audio track.'),
                                         title = 'Audio Track Missing')
                elif tag == 'Telecine':
                    while True:
                        code, tag = d.radiolist(
                            'Enable or not the inverse telecine filter:',
                            width = 60,
                            choices = [
                                ('Enabled', 'Enable inverse telecine filter', 
                                 1 if proj['telecine'] else 0),
                                ('Disabled', 'Disable inverse telecine filter',
                                 0 if proj['telecine'] else 1)],
                            title = 'Inverse Telecine Filter Selection',
                            help_button = True)
                        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                            break
                        elif code == d.DIALOG_HELP:
                            d.msgbox(helpmsgs['Telecine'],
                                     width = 60, title = 'Help on Telecine')
                        elif code == d.DIALOG_OK:
                            proj['telecine'] = (tag == 'Enabled')
                            break
                elif tag == 'Noise':
                    val = proj['nr']
                    while True:
                        code, answer = d.inputbox(
                            'Set noise reduction to:', init = str(val),
                            width = 60, title = 'Noise Reduction Setting',
                            help_button = True)
                        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                            break
                        elif code == d.DIALOG_HELP:
                            d.msgbox(helpmsgs['Noise'], 
                                     width = 60, 
                                     title = 'Help on Noise Reduction')
                        elif code == d.DIALOG_OK:
                            try:
                                val = int(answer.strip())
                            except ValueError:
                                val = -1
                                
                            if val < 0 or val > 1000:
                                val = proj['nr']
                                d.msgbox(
                                    'Value need to be an non-negative '
                                    'integer, not greater than 1000: '
                                    '"%s" is not.' % answer,
                                    title = 'Invalid Noise Reduction')
                            else:
                                proj['nr'] = val
                                break                            
                elif tag == 'Quality':
                    val = proj['crf']
                    while True:
                        code, answer = d.inputbox(
                            'Set quality to (%d is %s):' % (
                                val, describe_quality(val)), 
                            init = str(val),
                            width = 60, title = 'Visual Quality Setting',
                            help_button = True)
                        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                            break
                        elif code == d.DIALOG_HELP:
                            d.msgbox(helpmsgs['Quality'], 
                                     width = 60, 
                                     title = 'Help on Visual Quality')
                        elif code == d.DIALOG_OK:
                            try:
                                val = int(answer.strip())
                            except ValueError:
                                val = -1
                                
                            if val < 15 or val > 30:
                                val = proj['crf']
                                d.msgbox(
                                    'Value need to be an integer in the '
                                    '[15, 30] range: "%s" is not.' % answer,
                                    title = 'Invalid Quality')
                            else:
                                proj['crf'] = val
                                break
                elif tag == 'Preview':
                    while True:
                        code, tag = d.radiolist(
                            'Generate or not a preview only:',
                            width = 60,
                            choices = [
                                ('Yes', 
                                 'Only encode a short preview, "out.avi"', 
                                 1 if proj['preview'] else 0),
                                ('No', 'Encode a full length movie, "out.mkv"',
                                 0 if proj['preview'] else 1)],
                            title = 'Preview-Only Generation',
                            help_button = True)
                        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                            break
                        elif code == d.DIALOG_HELP:
                            d.msgbox(helpmsgs['Preview'],
                                     width = 60, title = 'Help on Preview')
                        elif code == d.DIALOG_OK:
                            proj['preview'] = (tag == 'Yes')
                            break
                elif tag == 'Reset':
                    proj['tracks'] = None
                    if title_autoselect(d, rippath, proj) is False:
                        return
                    proj['telecine'] = False
                    proj['nr'] = 0
                    proj['crf'] = 26
                    proj['preview'] = False
                elif tag == 'Fire in the hole!':
                    encoding = ('%s encoding of "%s" as %s, '
                                'title %d (%d seconds), '
                                'keeping %d tracks (%s), %s inverse telecine, '
                                '%s, and a visual quality of %d (%s)') % (
                        ('full' if proj['preview'] is False else 'preview'),
                        projname, 
                        ('out.mkv' if proj['preview'] is False else 'out.avi'),
                        proj['title'], 
                        proj['info']['dvd_titles_length'][proj['title']-1],
                        len(proj['tracks']), 
                        ', '.join([str(i) for i in proj['tracks']]),
                        ('with' if proj['telecine'] else 'without'),
                        ('no noise reduction' if proj['nr'] == 0 else 
                         'some noise reduction (%d)' % proj['nr']),
                        proj['crf'], describe_quality(proj['crf']))
                    if projname not in prefs['encodings']:
                        prefs['encodings'].append(projname)
                    d.msgbox('%s is now scheduled for encoding. Right now, '
                             'settings are: %s. Use the "Encode" ' 
                             'option in main menu to launch it.' % (
                            projname, encoding),
                             width = 60,
                             title = 'Encoding Now Scheduled.')
                elif tag == 'Changed my mind.':
                    prefs['encodings'].remove(projname)
                else:
                    raise NotImplementedError()
                
#------------------------------------------------------------------------------
def encode_low(projname):
    '''
    Low-level, non-interactive encoding driver.

    There is a dependency-based system to avoid unnecessary computation,
    but it us  a "Dead Man Walking" approach: in case of a problem with 
    some part of the process, it continues to the next step no matter what.
    '''
    logging.info('start encoding of "%s"' % projname)

    projdir = os.path.join(basedir, projname)
    os.chdir(projdir)

    class Preserver(object):
        '''
        Compute file preservation based on dependencies.
        such deps can either be logical (i.e. based on settings),
        file-based (i.e. based on generation time), or a combination
        of the two.
        '''
        def __init__(self, projdir, proj):
            self.projdir = projdir
            self.proj = proj

        @staticmethod
        def hash(deps):
            '''Not perfect, but good enough'''
            if deps is not None:
                return hashlib.sha1(repr(deps)).hexdigest()

        def newer_than(self, basename, pathdeps = None):
            def ctime(path):
                try:
                    return os.path.getctime(os.path.join(self.projdir, path))
                except OSError:
                    return 0
            if pathdeps is not None:
                return ctime(basename) > max(ctime(path) for path in pathdeps)
            else:
                return ctime(basename) > 0
            
        def __call__(self, basename, deps = None, pathdeps = None):
            self.current = os.path.join(self.projdir, basename)
            cur = self.hash(deps)
            old = self.proj['dependencies'].get(basename)
            if (self.newer_than(basename, pathdeps) and 
                (deps is None or cur == old)):
                logging.info('"%s" is up to date, preserving' % basename)
                return True
            else:
                self.proj['dependencies'][basename] = cur
                return False
            
    with get_preferences(projdir, dependencies = {}) as proj:
        # Welcome message on preview
        if proj['preview'] is True:
            logging.info('only perform a preview encoding')

        # Basic settings
        preserve  = Preserver(projdir, proj)
        dvd       = '-dvd-device dvdrip dvd://%d' %  proj['title']
        vf        = []
        aids      = [i for i in proj['tracks'] if i >= 128]
        sids      = [i for i in proj['tracks'] if i <  128]
        videodeps = (proj['title']   , aids[0], 
                     proj['telecine'], proj['nr'],
                     proj['crf']     , proj['preview'])
        titledeps = (proj['title']   , )

        # Extract chapters
        if not preserve('chapters.txt', deps = titledeps):
            logging.info('extracting the chapters timeline...')
            p = call_with_timeout('dvdxchap -t %s dvdrip' % proj['title'],
                                  timeout = 10,
                                  **call_output_redirect)
            if p.poll() == 0:
                logging.info('writing results to chapters.txt')
                with file(preserve.current, 'w') as out:
                    out.write(p.communicate()[0])
        
        # Time to encode the video (in six easy steps!),
        # in sync with first audio track.
        if not preserve('out.avi', deps = videodeps):
            # 1) Find out the cropping factor
            logging.info('determining cropping factor')
            crop_re = re.compile('\[CROP\][^(]*\(-vf crop=([^)]+)\)', re.M)
            stats = []
            for ss in xrange(60, 601, 60):
                # Poll it for 10 frames at different points in time
                p = call_with_timeout(
                    'mplayer %s -ss %d -frames 10 '
                    '-vf cropdetect -vo null -ao null' % (dvd, ss),
                    timeout = 10, **call_output_redirect)
                if p.poll() == 0:
                    stats.extend([[int(i) for i in crop.split(':')]
                                  for crop in crop_re.findall(
                                p.communicate()[0])])
             # Use what crops the less, horizontally then vertically
            if len(stats) > 0:
                crop_x = max(stats, key = lambda crop:crop[0])
                crop_y = max(stats, key = lambda crop:crop[1])
                vf.append(
                    'crop=%s' % ':'.join(
                        str(i) for i in (crop_x[0], crop_y[1], 
                                         crop_x[2], crop_y[3])))
                logging.info(vf[-1])
            else:
                logging.info('crop unset')

            # 2) Take care of telecine (filtration + frame rate)
            if proj['telecine'] is True:
                ofps = '30000/1001'
                vf.insert(0, 'pp=md')
            else:
                ofps = '24000/1001'

            # 3) Setup encoder option
            x264encopts = ['crf=%d' % proj['crf'], 'threads=0']
            if proj['nr'] > 0:
                x264encopts.append('nr=%d' % proj['nr'])

            # 4) Select first audio track
            aid = aids[0]

            # 5) Setup 2 minutes limits on preview
            opts = '-endpos 120' if proj['preview'] is True else ''

            # 6) Finally, build and invoke the command line
            logging.info('encoding the video track (long!)')
            call_with_path_monitor(
                ('mencoder %s -vf %s -aid %s -o out.avi '
                 '-oac pcm -ovc x264 -x264encopts %s '
                 '-ofps %s %s') % (dvd, ','.join(vf), 
                                   aid, ':'.join(x264encopts), ofps, opts),
                path = preserve.current)

        # Exit on preview
        if proj['preview'] is True:
            logging.info('end of preview encoding of %s' % projname)
            return

        # Extract(1), normalize(2), then encode(3) the audio tracks
        #
        # 1) First, extract the first audio track: it's a special case 
        # since it's synced to video in out.avi.
        if not preserve('%d.wav' % aids[0], pathdeps = ('out.avi', )):
            call_with_path_monitor(
                'mplayer -ao pcm:fast:file=%d.wav -vo null out.avi' % aids[0],
                preserve.current)
        # 1bis) Then, the rest of the audio tracks
        for aid in aids[1:]:
            if not preserve('%d.wav' % aid, deps = titledeps):
                call_with_path_monitor(
                    'mplayer %s -ao pcm:fast:file=%s -vo null -aid %d' %
                    (dvd, '%d.wav' % aid, aid),
                    preserve.current)
        # 2) Normalize them
        for aid in aids:
            if not preserve('%d_norm.wav' % aid, pathdeps = ('%d.wav' % aid, )):
                logging.info('normalizing audio track %d' % aid)
                output = call_output('sox %d.wav -n stat' % aid)
                if output is not None:
                    vol = output.split()[-1]
                else:
                    vol = 1
                logging.info('volume adjustment of %s' % vol)
                call_with_path_monitor(
                    'sox -S %d.wav %d_norm.wav vol %s' % (aid, aid, vol),
                    preserve.current)
        # 3) Encode them
        for i, aid in enumerate(aids):
            if not preserve('%d.ogg' % aid, pathdeps = ('%d_norm.wav' % aid, )):
                logging.info('encoding audio track %d' % aid)
                call_with_path_monitor(
                    'oggenc -q -1 -o %d.ogg %d_norm.wav' % (aid, aid),
                    preserve.current)

        # Extract vobsub subtites
        for sid in sids:
            if not preserve('%d.sub' % sid, deps = titledeps):
                logging.info('extracting subtitle %d' % sid)
                try:
                    os.unlink('%d.idx' % sid)
                except OSError:
                    pass
                call_with_path_monitor(
                    'mencoder %s -oac copy -ovc copy -o /dev/null '
                    '-sid %d -vobsubout %d' % (dvd, sid, sid),
                    preserve.current)

        # Finally, generate the Matroska...
        if not preserve('out.mkv', 
                        pathdeps = (['out.avi', 'chapters.txt'] + 
                                    ['%d.ogg' % aid for aid in aids] +
                                    ['%d.idx' % sid for sid in sids])):
            logging.info('merge all tracks into a matroska container (out.mkv)')
            call_with_path_monitor(
                'mkvmerge -o out.mkv --chapter-charset latin1 '
                '--chapters chapters.txt --noaudio out.avi '
                '%s %s' % (' '.join(
                    ['--language 0:%s %d.ogg' % (
                                proj['info']['aid_langs'][aid], aid)
                     for aid in aids]),
                           ' '.join(
                        ['--default-track 0:0 %d.idx' % sid
                         for sid in sids])),
                preserve.current,
                ok_retcodes = (0, 1))

    logging.info('end of full encoding of "%s"' % projname)
    time.sleep(10)

#------------------------------------------------------------------------------
def encode(prefs, d):
    '''
    Implement encoding action of the main menu
    '''
    if len(prefs['encodings']) == 0:
        d.msgbox('No encoding currently in the queue. Prepare some first '
                 '(via the "Prepare" option of the main Menu).',
                 title = 'Nothing to Encode')
        return

    # Check Space
    hdd_space = df(basedir)[1]
    if len(prefs['encodings']) * 13000000 > hdd_space:
        d.msgbox('The system does not feel confident it can perform '
                 'the %d scheduled encoding(s) in the remaining hard drive '
                 'space. All encodings have been dropped. Please clean up '
                 'the disk (via management), than resubmit your encoding '
                 'queries' % 
                 (len(prefs['encodings'])))
        prefs['encodings'] = []
        return

    # Time for an encoding menu...    
    while True:
        code, tag = d.menu(
            'There are %d encoding(s) scheduled: %s. What do you want to do?' %
            (len(prefs['encodings']), ', '.join(prefs['encodings'])),
            width = 60,
            choices = [
                ('Clear', 'Clear all scheduled encodings'),
                ('Encode', 'Perform all encodings'),
                ('Encode & Shutdown', 'Perform all encodings, then shutdown.')],
            title = 'Encoding Menu',
            cancel = 'Exit',
            help_button = True)

        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
            return
        elif str(code) == 'help':
            msg = {'Clear': ('This will clear all scheduled encodings, '
                             'so that you can start over. It will not erase '
                             'the latest individual settings you prepared '
                             'for each rip.'),
                   'Encode': ('Batch encode all of what you scheduled. This is '
                              'a very long, absolutely non-interactive '
                              'process: no intervention from you will '
                              'be required, but you will not be able '
                              'to interact with the system for a good while.'),
                   'Encode & Shutdown' : ('Same as encode, with the system '
                                          'shutting down once the encodingfest '
                                          'is over.')}[tag]
            d.msgbox(msg, width = 60, title = 'Help on Encode > %s' % tag)
        else:
            if tag == 'Clear':
                prefs['encodings'] = []
                d.msgbox('All scheduled encoding were cleared.',
                         title = 'Encodings List Now Empty')
            shutdown = (tag == 'Encode & Shutdown')
            break

    # Time to batch perform the encode
    while True:
        try:
            projname = prefs['encodings'].pop(0)
        except IndexError:
            break

        encode_low(projname)

    if shutdown is True:
        call('halt') 

#------------------------------------------------------------------------------
def manage(prefs, d):
    '''
    Implement encoding action of the main menu
    '''
    while True:
        logging.info('quick-scanning disk...')
        hdd_space = df(basedir)[1] / 1e6
        projects = dict(
            (projname, 
             {'dvdrip': os.path.exists(
                        os.path.join(basedir, projname, 'dvdrip')),
              'matroska': os.path.exists(
                        os.path.join(basedir, projname, 'out.mkv')),
              'misc': len(set(os.listdir(os.path.join(
                                    basedir, projname))).difference(
                            ('dvdrip', 'dvd.log', 
                             'out.mkv', 
                             'preferences.txt')))})
            for projname in [item for item in os.listdir(basedir)
                             if (os.path.isdir(os.path.join(basedir, item)) 
                                 and item != 'final')])

        if len(projects) == 0:
            d.msgbox('There is %.1f GB available, and nothing to clean up '
                     'right now.' % hdd_space, 
                     title = 'System is Clean')
            break
        # Time for the menu
        code, tag = d.checklist(
            ('There is approximately %.1f GB available. '
             'Select the rips and associated miscellanous files '
             'you want to remove (all final encodings '
             'in Matroska will be backed up appropriately first):') % hdd_space,
            width = 70,
            choices = ([(projname, 
                         'rip: %s, final: %s, misc: %d file(s)' %
                         ('yes' if proj['dvdrip'] else 'no',
                          'yes' if proj['matroska'] else 'no',
                          proj['misc']), 0)
                        for projname, proj in sorted(projects.iteritems(), 
                                               key = lambda i:i[0])]),
            title = 'Data Management (Cleanup)',
            cancel = 'Exit', 
            help_button = True)
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
            break
        elif code == d.DIALOG_HELP:
            d.msgbox('Here, you can select as many partial or complete rips, '
                     'as well as remaining files used, produced and stored '
                     'on the system, and remove them permanently for the disk. '
                     'just select the rips by their human-readable names '
                     'to reclaim the space. Final encodings will be preserved '
                     'by this operation.',
                     width = 60, title = 'Help on Management')
        elif code == d.DIALOG_OK:
            if len(tag) > 0:
                msg = ('If you answer "yes" to the next dialog, \n'
                       'the following is going to take place:\n')
                for projname in tag:
                    proj = projects[projname]
                    msg += '\nFor "%s": %s\n' % (
                        projname,
                        '    <= No final encoding to save!'
                        if not proj['matroska'] else '')
                    if proj['dvdrip']:
                        msg += '  - The DVD rip will be removed.\n'
                    if proj['matroska']:
                        msg += ('  - One final encoding '
                                'will be saved away. \n')
                    if proj['misc'] > 0:
                        msg += ('  - A few temporary files (%d) '
                                'will be expunged.\n' % proj['misc'])
                    
                    msg += ('  - Name and preferences will be removed.\n')
                msg += '\n\nTHESE ACTIONS ARE IRREVERSIBLE.'
                code = d.scrollbox(msg, title = 'Cleanup Recap')
                if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                    continue
                if d.yesno('Are you sure you want to proceed '
                           'with the previously described '
                           'cleanup operation?',
                           title = 'Accept Cleanup',
                           defaultno = True) == d.DIALOG_OK:
                    finaldir = os.path.join(basedir, 'final')
                    for projname in tag:
                        logging.info('cleaning up "%s"' % projname)
                        projdir = os.path.join(basedir, projname)
                        proj = projects[projname]

                        # Save out the final matroska encoding
                        if proj['matroska']:
                            logging.info('there is a matroska to save')
                            if not os.path.exists(finaldir):
                                os.mkdir(finaldir)
                            # Find out a free name
                            def gen_names(finaldir, basename):
                                yield os.path.join(
                                    finaldir, '%s.mkv' % basename)
                                for i in range(1, 100):
                                   yield os.path.join(
                                       finaldir, '%s_%.2d.mkv' % (projname, i))
                            
                            # Move out the file
                            moved = False
                            for name in gen_names(finaldir, projname):
                                if not os.path.exists(name):
                                    logging.info(
                                        'moving encoding to "%s"' % name)
                                    try:
                                        shutil.move(
                                            os.path.join(projdir, 'out.mkv'), 
                                            name)
                                        moved = True
                                    except:
                                        logging.error(
                                            'could not move final encoding '
                                            'to "%s"' % name)
                                    break
                            else:
                                logging.error(
                                    'could not find a free name to save '
                                    'final encoding for "%s"' % projname)
                            
                            if moved is False:
                                logging.info('bailing out on cleanup of '
                                             '"%s"' % projname)
                                continue
                        
                        # If it worked, remove the project directory
                        logging.info('removing the whole "%s" directory' % 
                                     projname)
                        try:
                            shutil.rmtree(projdir)
                        except:
                            logging.error('could not recursively remove "%s" '
                                          'directory' % projname)

#------------------------------------------------------------------------------
if __name__ == '__main__':
    # Setup logging
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)-15s %(levelname)s %(message)s')
    for hdlr in (logging.StreamHandler(),
                 logging.handlers.RotatingFileHandler(
            os.path.join(basedir, 'all.log'), 
            mode = 'a',
            maxBytes = 100 * 1024,	# Limit individual log files to 100 KB
            backupCount = 5)):
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)

    # Get IPv4 address of Ethernet 0
    m = re.search('(?<=addr:)[0-9\.]+', call_output('/sbin/ifconfig eth0'))
    if m is not None:
        addr = m.group(0)
    else:
        addr = 'unknown address'

    # Instantiate dialog library
    d = dialog.Dialog(dialog = 'dialog')
    d.add_persistent_args(('--backtitle', 'BorderPatrol (%s)' % addr))
    d.add_persistent_args(('--clear',))
    
    # Loop on the main menu
    while True:
        # Load/Save preferences
        with get_preferences(ids = {}, last_prep = None, 
                             encodings = []) as prefs:
            code, tag = d.menu(
                'What do you want to do?',
                width = 60, menu_height = 8,
                choices = [
                    ('Rip',      'Incorporate a new DVD to the system'),
                    ('Prepare',  'Setup encoding for an available rip'),
                    ('Encode' ,  'Perform the prepared encoding(s)'),
                    ('Get Help', 'Switch to help desk'),
                    ('Manage',   'Cleanup data'),
                    ('See Logs', 'See latest logs entries'),
                    ('Logout',   'Disconnect immediately'),
                    ('Halt',     'Halt system now'),
                    ],
                title = 'Main Menu',
                nocancel = True, help_button = True)
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
                logging.info('exiting')
                break
            elif str(code) == 'help':
                msg = {'Rip': 
                       ('If you wish working on an actual, physical DVD, '
                        'first step is to copy it onto BorderPatrol\'s '
                        'hard disk: '
                        'this is what ripping does. Once the ripping is '
                        'completed, the system no longer requires '
                        'the original optical disk.'),
                       'Prepare': 
                       ('Once you successfully ripped a DVD, '
                        'you need to specify '
                        'the type of encoding you want to perform: '
                        'the title you are interested in, '
                        'tracks you want to keep, '
                        'quality settings, etc. '
                        'If you are not satisfied with the result, '
                        'you can always come back and tweak '
                        'your settings later on as many times '
                        'as needed.'),
                       'Encode': 
                       ('Perform in batch all (or some) '
                        'of the encodings you previously prepared.'),
                       'Get Help'  : 
                       ('There is a semi-permanent help desk on '
                        'this machine: use it if you need assistance. '
                        'You can trigger the switch back and forth at any time '
                        'pressing F12.'),
                       'Manage': 
                       ('Once you are satisfied with a given encoding, '
                        'you will probably want to remove the '
                        'associated rip and all temporary files, '
                        'and keep only the result: '
                        'this is what management is for. Be warned '
                        'that this tool is blunt: '
                        'access BorderPatrol another way if you need '
                        'finer control.'),
                       'See Logs':
                       ('All significant actions happening in the system '
                        'are logged. Use this to visualize '
                        'the latest entries.'),
                       'Logout': 
                       ('Enough said: BorderPatrol will keep running, '
                        'but you will disconnect from it (if you were remotely '
                        'connected, that is). This has no use if you are '
                        'using the physical terminal, as you will relogin '
                        'almost instantly. You can trigger this pressing F11.'),
                       'Halt': 
                       ('Shutdown BorderPatrol immediately... '
                        'Didn\'t you know you could just press that big '
                        'flat power button on the front of the case? '
                        'Works exactly the same!')}[tag]
                d.msgbox(msg, width = 60, title = 'Help on %s' % tag)
            elif tag == 'Rip':
                rip(prefs, d)
            elif tag == 'Prepare':
                prepare(prefs, d)
            elif tag == 'Encode':
                encode(prefs, d)
            elif tag == 'Get Help':
                d.msgbox('Switching to help desk. Press F12 anytime '
                         'to switch back.',
                         title = 'Help Desk')
                call('screen -X select 2')
            elif tag == 'Manage':
                manage(prefs, d)
            elif tag == 'See Logs':
                d.scrollbox(file(os.path.join(basedir, 'all.log')).read(),
                            title = 'Latest Log Entries')
            elif tag == 'Logout':
                call('screen -X detach')
            elif tag == 'Halt':
                call('halt')
            else:
                raise NotImplementedError()

#------------------------------------------------------------------------------
# That's all, folks!