This file is indexed.

/usr/bin/lives_mpeg_encoder3 is in lives-plugins 2.4.8-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  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
#! /usr/bin/python

import locale
locale.setlocale(locale.LC_NUMERIC,"C")

"""
lives_mpeg_encoder3

Simple front-end to MJPEGtools with some image-enhancing
capabilities through the use of ImageMagick. Meant as a
companion to LiVES (to possibly call from within a plugin,
see http://www.xs4all.nl/~salsaman/lives/ ) but can also
be used as a stand-alone program.

Requires MJPEGtools, ImageMagick (GraphicsMagick might also
work), sox, and Python 2.3.0 or greater.

Copyright (C) 2004-2005 Marco De la Cruz (marco@reimeika.ca)
It's a trivial program, but might as well GPL it, so see:
http://www.gnu.org/copyleft/gpl.html for license.

See my vids at http://amv.reimeika.ca !
"""

version = '0.1.9'
convert = 'convert'
mpeg2enc = 'mpeg2enc'
mp2enc = 'mp2enc'
sox = 'sox'
png2yuv = 'png2yuv'
jpeg2yuv = 'jpeg2yuv'
yuvdenoise = 'yuvdenoise'
yuvscaler = 'yuvscaler'
mplex = 'mplex'

usage = \
      """
lives_mpeg_encoder3 -h
lives_mpeg_encoder3 -V
lives_mpeg_encoder3 -C
lives_mpeg_encoder3 [-o out] [-p pre] [-d dir] [-a aspect] [-D delay]
                [-q|-v] [-t type] [-k] [-e [[-w dir] [-c geom] [-r geom]]]
                [-s sndfile] [-b sndrate] [-f fpscode] [-L lv1file]
                [firstframe lastframe]
      """

help = \
     """
SUMMARY (ver. %s):

Encodes a series of PNG or JPG images into an MPEG-1 or MPEG-2
stream. It behaves mostly as a simplified front-end to mjpegtools,
although it is also capable of performing some simple image
enhacements using ImageMagick. The images and audio are assumed to
be in an uncompressed LiVES format, hence making this encoder
more suitable to be used within a LiVES plugin (but can also
be used directly on a LiVES temporary directory).

Note: this program currently handles only non-interlaced source.

OPTIONS:

-h          for help.

-V          shows the version number.

-C          check external program dependencies and exit.

-o out      will save the video in file "out".
            Default: "'type'_movie.mpg". See below for 'type'.

-p pre      the encoder assumes that sound and images are named using
            LiVES' conventions i.e. "audio" and "00000001.ext",
            "00000002.ext"... where "ext" is either "jpg" or "png".
            However, lives_mpeg_encoder3 will create temporary files
            which can be saved for later use (for example, after
            enhancing the images with "-e" , which may take a long
            time). These temporary files will be named
            "pre_00000001.ext", etc... where "pre" is either "eimg"
            or "rimg" and will be kept if the "-k" option is used.
            lives_mpeg_encoder3 can then be run over the enhanced images
            only by selecting the appropriate prefix ("eimg" or
            "rimg") here. See "-e" to see what each prefix means.
            Default: "" (an empty string).

-d dir      "dir" is the directory containing the source image
            files. These must be of the form "00000001.ext" or
            "pre_00000001.ext" as explained above.
            Default: "."

-a aspect   sets the aspect ratio of the resulting MPEG. This can be:

               1    1:1 display
               2    4:3 display
               3    16:9 display
               4    2.21:1 display (does not really work)

            Currently selecting "4" will fall back to "3".
            Default: "2"

-D delay    linearly delay the audio stream by "delay" ms.
            Default: "0"

-q          quiet operation, only complains on error.

-v          be verbose.

-t type     type of video created. The options here are:

               "hi":   a very high quality MPEG-1 file, suitable
                       for archiving images of 720x480.

               "mh":   medium-high quality MPEG-1, which still allows
                       to watch small videos (352x240 and below)
                       fullscreen.

               "ml":   medium-low quality MPEG-1, suitable for
                       most videos but in particular small videos
                       (352x240 and below) meant for online
                       distribution.

               "lo":   a low quality MPEG-1 format. Enlarging
                       small videos will result in very noticeable
                       artifacts. Good for distributing over slow
                       connections.

               "qlo":  a quick and dirty (but fast) low quality MPEG-1.

               "vcd":  VCD-conformant MPEG-1 stream (NTSC VIDEO).

               "svcd": SVCD-conformant MPEG-2 stream (NTSC VIDEO).

               "dvd":  DVD-conformant MPEG-2 stream (NTSC VIDEO).

               "sdvd":  Strictly DVD-conformant MPEG-2 stream (NTSC VIDEO).

               "pvcd":  VCD-conformant MPEG-1 stream (PAL VIDEO).

               "psvcd": SVCD-conformant MPEG-2 stream (PAL VIDEO).

               "pdvd":  DVD-conformant MPEG-2 stream (PAL VIDEO).

               "spdvd":  Strictly DVD-conformant MPEG-2 stream (PAL VIDEO).

            Default: "ml"

-e          perform some simple filtering/enhancement to improve image
            quality. The images created by using this option will be
            stored in the directory specified by the "-w" option (or
            "-d" if not present, see above) and each filename will be
            prefixed with "eimg" (see "-p" above). Using this option will
            take enormous amounts of disk space, and in reality does
            not do anything that cannot be done within LiVES itself.
            Using this option enables the following four:

            -w dir      "dir" is the working directory where the enhanced
                        images  will be saved. Although these can all
                        co-exist with the original LiVES files it is
                        recommended you use a different directory. Note
                        that temporary files may take a huge amount of
                        space, perhaps twice as much as the LiVES files
                        themselves. If this directory does not exist is
                        will be created.
                        Default: same as "-d".

            -k         keep the temporary files, useful to experiment
                       with different encoding types without having
                       to repeatedly enhance the images (which can be
                       very time-consuming). See "-p" above.

            -c geom    in addition to enhancing the images, crop them
                       to the specified geometry e.g. "688x448+17+11".
                       Filename prefix remains "eimg". Note that the
                       dimensions of the images should both be multiples
                       of "16", otherwise some players may show artifacts
                       (such as garbage or green bars at the borders).

            -r geom    this will create a second set of images resulting
                       from resizing the images that have already been
                       enhanced and possibly cropped (if "-c" has been
                       specified). The geometry here is simple a new
                       image size e.g. "352x240!". This second set will have
                       filenames prefixed with the string "rimg" (see "-p"
                       above). Note that the dimensions of the images
                       should both be multiples of "16", otherwise some
                       players may show artifacts (such as garbage or
                       green bars at the borders).

-s sndfile  name of the audio file. Can be either raw "audio" or
            "[/path/to/]soundfile.wav". Note that for raw audio
            the sound will always be stereo and sampled at 44100Hz.
            Default: "audio" inside "dir" as specified by "-d".

-b sndrate  sample rate of the sound file in Hertz.
            Default: "44100".

-f fpscode  frame-rate code. Acceptable values are:

              1 - 24000.0/1001.0 (NTSC 3:2 pulldown converted FILM)
              2 - 24.0 (NATIVE FILM)
              3 - 25.0 (PAL/SECAM VIDEO / converted FILM)
              4 - 30000.0/1001.0 (NTSC VIDEO)
              5 - 30.0
              6 - 50.0 (PAL FIELD RATE)
              7 - 60000.0/1001.0 (NTSC FIELD RATE)
              8 - 60.0

            Note that when type is "vcd", "svcd", or "(s)dvd" this value
            is set to "4" to make NTSC video. For "pvcd", "psvcd", or
            "(s)pdvd" the value is set to "3".

            Default: "4".

-L lv1file  use the images stored in the LiVES file "lv1file" (e.g.
            "movie.lv1"). Files will be extracted inside "dir" as
            specified by "-d". Using this option allows to encode
            a movie without having to restore it first with LiVES.
            Note that the encoder will not delete the extracted
            files after it has finished, this must be done manually
            afterwards. If frame code/rate (-f) and/or sound rate (-b)
            are not specified the defaults will be used (30000/1001 fps
            and 44100 Hz). These, however, may not be correct, in which
            case they should be specified explicitly. Furthermore, the
            .lv1 audio (if present) is always assumed to have a sample
            data size in 16-bit words with two channels, and to be signed
            linear (this is usually the case, however). If any of these
            latter parameters are incorrect the resulting file may be
            corrupted and encoding will have to be done using LiVES.

firstframe  first frame number. If less than eight digits long it will
            be padded with zeroes e.g. 234 -> 00000234. A prefix can
            be added using the "-p" option.
            Default: "00000001"

lastframe   last frame number, padded with zeroes if necessary, prefix
            set by "-p".
            Default: the last frame of its type in the "-d" directory,
                     where "type" is set by the prefix.

Note that either no frames or both first and last frames must be specified.

EXAMPLES:

Suppose you have restored a LiVES' .lv1 file (in either JPG or PNG format),
and that the images are stored in the directory "/tmp/livestmp/991319584/".
In this example the movie is assumed to be 16:9. NOTE THAT THE VIDEO MUST
BE PROGRESSIVE (NON-INTERLACED) FOR THIS TO WORK. Then, in order to
create an MPEG-1 file you can simply do the following:

   lives_mpeg_encoder3 -d /tmp/livestmp/991319584 -o /movies/default.mpg -a 3

and the clip "default.mpg" will be created in "/movies/" with the correct
aspect ratio.

Suppose we want to make a downloadable version of the clip, small in size
but of good quality. The following command activates the generic enhancement
filter and resizes the images to "352x240". Note that these operations
are performed after cropping the originals a bit (using "704x464+5+6").
This is done because we are assuming that there is a black border around
the original pictures which we want to get rid of (this might distort the
images somewhat, so be careful about cropping/resizing, and remember to
use dimensions which are multiples of 16):

   lives_mpeg_encoder3 -v -d /tmp/livestmp/991319584 -w /tmp/tmpmpg \\
   -o /movies/download.mpg -a 3 -k -e -c "704x464+5+6" -r "352x240"

Since we use the "-k" flag the enhanced images are kept (both full-size
crops and the resized ones) in "/tmp/tmpmpg". Beware that this may consume
a lot of disk space (about 10x as much as the originals). The reason we
keep them is because the above may take quite a long time and we may want
to re-use the enhanced images. So, for example, creating a high-quality
clip at full size can be accomplished now as follows:

   lives_mpeg_encoder3 -d /tmp/tmpmpg -t hi -o /movies/archive.mpg \\
   -s /tmp/livestmp/991319584/audio -a 3 -k -p eimg

Creating VCD/SVCD/DVD-compatible clips is also readily done:

   lives_mpeg_encoder3 -d /tmp/tmpmpg -t vcd -o /movies/vcd.mpg \\
   -s /tmp/livestmp/991319584/audio -a 3 -k -p eimg

   lives_mpeg_encoder3 -q -d /tmp/tmpmpg -t svcd -o /movies/svcd.mpg \\
   -s /tmp/livestmp/991319584/audio -a 3 -k -p eimg

   lives_mpeg_encoder3 -v -d /tmp/tmpmpg -t dvd -o /movies/dvd.mpg \\
   -s /tmp/livestmp/991319584/audio -a 3 -k -p eimg

If, for example, we only want to encode frames 100 to 150 we can run
the following:

   lives_mpeg_encoder3 -v -d /tmp/tmpmpg -o /movies/selection.mpg \\
   -a 3 -k -p eimg 100 150

Note that no audio has been selected ("-s"). This is because
lives_mpeg_encoder3 cannot trim the audio to the appropriate length.
You would need to use LiVES to do this.

To delete all the enhanced images you can just remove "/tmp/tmpmpg".

If you notice that the video and audio become out of sync so that
near the end of the movie the video trails the audio by, say, 0.2s,
you can use the "-D" option as follows:

   lives_mpeg_encoder3 -d /tmp/livestmp/991319584 -o test.mpg -D 200

Note that negative time values are also allowed.

Suppose that you have "movie1.lv1", "movie2.lv1" and "movie3.lv1".
Batch-encoding can be done as follows (zsh-syntax):

   for i in movie?.lv1
   do
     mkdir /tmp/$i:r
     lives_mpeg_encoder3 -d /tmp/$i:r -o /tmp/$i:r.mpg -L $i
     rm -rf /tmp/$i:r
   done

This will generate the files "movie1.mpg", "movie2.mpg" and
"movie3.mpg" in "/tmp". Note that is is not necessary to
specify whether the files are stored in JPG or PNG format,
and that potentially time-consuming options (e.g. "-e") may
be enabled. It is not necessary to have a working LiVES
installation to encode .lv1 files.
     """ % version

def run(command):
    """
    Run a shell command
    """

    if verbose:
        print('Running: \n' + command + '\n=== ... ===')
        std = ''
    else:
        std = ' > /dev/null 2>&1'

    os.system(command + std)


def do_enhance():
    """
    Image cleanup/crop/resize routine. Generic, but seems to work
    well with anime :)
    """

    if not quiet:
        print('Enhancing images... please wait, this might take long...')

    enh_opts = "-enhance -sharpen '0.0x0.5' -gamma 1.2 -contrast -depth 8"

    if cgeom:
        docrop = ' '.join(['-crop', "'%s!'" % cgeom])
    else:
        docrop = ''

    iframe = first_num
    while True:
        # File names are padded with zeroes to 8 characters
        # (not counting the .ext).
        frame = str(iframe).zfill(8)
        fname = os.path.join(img_dir, frame + ext)
        if not os.path.isfile(fname) or (iframe == last_num + 1):
            break
        eimg_fname = os.path.join(work_dir, 'eimg' + frame + '.png')
        rimg_fname = os.path.join(work_dir, 'rimg' + frame + '.png')
        command = ' '.join([convert, docrop, enh_opts, fname, eimg_fname])
        run(command)
        if rgeom:
            if os.path.exists(rimg_fname): os.remove(rimg_fname)
            shrink = ' '.join([convert, '-resize', "'%s!'" % rgeom, '-depth 8'])
            command = ' '.join([shrink, eimg_fname, rimg_fname])
            run(command)
        else:
            if os.path.exists(rimg_fname): os.remove(rimg_fname)
	    try:
            	os.symlink(eimg_fname, rimg_fname)
	    except (IOError, OSError):
		shutil.copy(eimg_fname, rimg_fname)
        iframe+=1


def do_encode():
    """
    Encode a series of images into an MPEG stream, multiplexing
    audio if necessary
    """

    if not quiet:
        print('Creating "%s"-quality MPEG' % vtype)

    if verbose:
        std = ''
    else:
        std = ' 2> /dev/null'

    # There are a lot of magic numbers here, but in a sense that's
    # the point of boiling down all the complicated parameter settings
    # to "low", "medium lo/hi", and "hi". These numbers work OK, but
    # in order to fully understand them it is necessary to read the
    # excellent MJPEGtools HOWTO:
    # https://sourceforge.net/docman/display_doc.php?docid=3456&group_id=5776

    scaler = ''
    denoise = '2'
    if vtype == 'qlo':
        common_opts = ' -f 0 -F %s -r 8 -4 4 -2 4 -P ' % fpsc
    else:
        common_opts = ' -f 0 -F %s -H -r 24 -4 1 -2 1 -P -g 6 -G 18 ' % fpsc
    if aspect in ['3','4']:
        widescreen = '-M WIDE2STD'
    else:
        widescreen = ''
    if ext == '.png':
        img2yuv = png2yuv
    else:
        img2yuv = jpeg2yuv

    # For -B: round up (vid + audio)*0.01 + audio bitrates
    # For -r: round up (vid + audio)*1.02
    # For -V: decent software decoder... push this up to 500K+
    # For -b in mplex: "at least -V". I do -V*1.1

    if vtype == 'hi':
        mpeg2enc_opts = common_opts + \
                        '-a %s -b 13000 -q 4 -B 600 -V 2000' % aspect
        mp2enc_opts = '-b 384 -r 44100'
        mplex_opts = '-f 0 -b 2200 -V -r 14000'
    elif vtype == 'mh':
        mpeg2enc_opts = common_opts + \
                        '-a %s -b 6500 -q 4 -B 350 -V 1000' % aspect
        mp2enc_opts = '-b 256 -r 44100'
        mplex_opts = '-f 0 -b 1100 -V -r 7000'
    elif vtype == 'ml':
        denoise = '1'
        mpeg2enc_opts = common_opts + \
                        '-a %s -b 6500 -q 4 -B 300 -V 1000' % aspect
        mp2enc_opts = '-b 192 -r 44100'
        mplex_opts = '-f 0 -b 1100 -V -r 7000'
    elif vtype in ['lo', 'qlo']:
        denoise = '1'
        mpeg2enc_opts = common_opts + \
                        '-a %s -b 2500 -q 6 -B 160 -V 1000' % aspect
        mp2enc_opts = '-b 128 -r 44100'
        mplex_opts = '-f 0 -b 1100 -V -r 3000'
    elif vtype in ['vcd', 'pvcd']:
        scaler = yuvscaler + ' %s -O VCD %s |' % (widescreen, std)
        mpeg2enc_opts = '-f 1 -r 16'
        mp2enc_opts = '-V'
        mplex_opts = '-f 1'
    elif vtype in ['svcd', 'psvcd']:
        scaler = yuvscaler + ' %s -O SVCD %s |' % (widescreen, std)
        mpeg2enc_opts = '-f 4 -q 7 -I 0 -V 200'
        mp2enc_opts = '-V -e'
        mplex_opts = '-f 4 -b 200 -r 2750'
    elif vtype in ['dvd', 'pdvd']:
        scaler = yuvscaler + ' %s -O DVD %s |' % (widescreen, std)
        mpeg2enc_opts = '-f 8 -q 7 -4 1 -2 1 -P -I 0'
        mp2enc_opts = '-r 48000'
        mplex_opts = '-f 8'
    elif vtype in ['sdvd', 'spdvd']:
        scaler = yuvscaler + ' %s -O DVD %s |' % (widescreen, std)
        mpeg2enc_opts = '-f 8 -q 7 -4 1 -2 1 -P -I 0'
        pcmsox_opts = '-r 48000 -x -t raw'
        mplex_opts = '-f 8 -L 48000:2:16'

    if img_dir != work_dir and not enhance:
        source_dir = img_dir
    else:
        source_dir = work_dir
    mpegv = tempfile.mkstemp('.mpv', '', work_dir)[1]
    if last_num < 99999999:
        numframes = str(last_num - first_num + 1)
        offset = str(first_num)
    else:
        numframes = '-1'
        offset = '1'

    # We set fps to 24 in png/jpeg2yuv because the converter
    # has problems with other (correct e.g. 30fps) frame
    # rates. In the end this works out OK because we force
    # the correct rate with mpeg2enc, although then it's the scaler
    # which has problems, and hence we need to use the right
    # fps in those cases (which are 25 and 30000/1001 fps, both
    # of which fortunately the converter can handle OK). BTW, these
    # same problems occur with ppmtoy4m. fps codes 6 and 7 may still
    # not work well.

    if fpsc not in ['1', '2', '3', '4']: fps = '24'

    if vtype == 'qlo':
        do_denoise = ''
    else:
        do_denoise = '%s -t %s %s | ' % (yuvdenoise, denoise, std)

    all_vars = {}
    all_vars.update(globals())
    all_vars.update(locals())

    command = """cd %(source_dir)s ; \\
%(img2yuv)s -b %(offset)s -n %(numframes)s -f %(fps)s -I p -L 0 -j %(img_pre)s%%08d%(ext)s %(std)s | \\
%(do_denoise)s %(scaler)s \\
%(mpeg2enc)s %(mpeg2enc_opts)s -o %(mpegv)s""" % all_vars
    run(command)

    if audio:
        if not quiet:
            print('Creating "%s"-quality sound file' % vtype)

        if vtype in ['sdvd', 'spdvd']:
            tmpsndf = tempfile.mkstemp('.lpcm', '', work_dir)[1]
        else:
            tmpsndf = tempfile.mkstemp('.mp2', '', work_dir)[1]

        if rawsndf:
            wav = tempfile.mkstemp('.wav', '', work_dir)[1]
            sox_opts = '-t raw -r %s -w -c 2 -s' % sndr
            command = ' '.join([sox, sox_opts, sndf, wav])
            run(command)
        else:
            wav = sndf
            
        if vtype in ['sdvd', 'spdvd']:
            command = ' '.join([sox, wav, pcmsox_opts, tmpsndf, 'rate -v'])            
        else:
            files = ' '.join(['-o', tmpsndf, '<', wav])
            command = ' '.join([mp2enc, mp2enc_opts, files])

        run(command)

        if delay != '0':
            delaysh = str(-1*int(delay))
        else:
            delaysh = delay

        all_vars.update(locals())

        if not quiet: print('Multiplexing...')
        command = """
%(mplex)s %(mplex_opts)s -O %(delaysh)sms %(tmpsndf)s %(mpegv)s -o "%(vidname)s" """ % all_vars
        run(command)

        if rawsndf and os.path.exists(wav): os.remove(wav)
        if os.path.exists(tmpsndf): os.remove(tmpsndf)
    else:
        if not quiet: print('Multiplexing...')
        command = """
%(mplex)s %(mplex_opts)s %(mpegv)s -o "%(vidname)s" """ % all_vars
        run(command)
        
    if os.path.exists(mpegv): os.remove(mpegv)


def do_clean():
    """
    Delete enhanced files
    """

    if not quiet:
        print('Deleting all enhanced images (if any)')

    eframes = os.path.join(work_dir, 'eimg')
    rframes = os.path.join(work_dir, 'rimg')
    for frame in glob.glob(eframes + '*'):
         os.remove(frame)
    for frame in glob.glob(rframes + '*'):
         os.remove(frame)


def which(command):
    """
    Finds (or not) a command a la "which"
    """

    command_found = False

    if command[0] == '/':
        if os.path.isfile(command) and \
               os.access(command, os.X_OK):
            command_found = True
            abs_command = command
    else:
        path = os.environ.get('PATH', '').split(os.pathsep)
        for dir in path:
            abs_command = os.path.join(dir, command)
            if os.path.isfile(abs_command) and \
               os.access(abs_command, os.X_OK):
                command_found = True
                break

    if not command_found:
        abs_command = ''

    return abs_command


def is_installed(prog):
    """
    See whether "prog" is installed
    """

    wprog = which(prog)

    if wprog == '':
        print(prog + ': command not found')
        raise SystemExit(1)
    else:
        if verbose:
            print(wprog + ': found')


if __name__ == '__main__':

    import os
    import sys
    import getopt
    import shutil
    import tempfile
    import glob
    import tarfile

    try:
        if sys.version_info[0:3] < (3, 0, 0):
            raise SystemExit(1)
    except:
        print('You need Python 3.0.0 or greater to run me!')
        raise SystemExit(1)

    try:
        (opts, args) = getopt.getopt(sys.argv[1:], \
                                         'ho:p:d:w:a:qvt:ekc:r:s:b:f:VCD:L:')
    except:
        print("Something's wrong. Try the '-h' flag.")
        raise SystemExit(1)

    opts = dict(opts)

    if not opts and not args:
        print(usage)
        raise SystemExit(1)

    if '-h' in opts:
        print(usage + help)
        raise SystemExit

    if '-V' in opts:
        print('lives_mpeg_encoder3 version ' + version)
        raise SystemExit

    if ('-v' in opts) or ('-C' in opts):
        verbose = True
    else:
        verbose = False

    if '-q' in opts:
        quiet = True
        verbose = False
    else:
        quiet = False

    for i in [convert, mpeg2enc, mp2enc, sox, png2yuv, jpeg2yuv, \
              yuvdenoise, yuvscaler, mplex]:
        is_installed(i)
    if '-C' in opts: raise SystemExit

    img_pre = opts.get('-p', '')

    if img_pre not in ['', 'eimg', 'rimg']:
         print('Improper image name prefix.')
         raise SystemExit(1)

    temp_dir = ''
    img_dir = opts.get('-d', '.')
    img_dir = os.path.abspath(img_dir)
    if ' ' in img_dir:
        temp_dir = tempfile.mkdtemp('', '.lives-', '/tmp/')
        try:
            os.symlink(img_dir, temp_dir + '/img_dir')
        except (IOError, OSError):
            shutil.copy(img_dir, temp_dir + '/img_dir')
        img_dir = temp_dir + '/img_dir'

    if not os.path.isdir(img_dir):
        print('The image source directory: '  + img_dir + \
              ' does not exist!')
        raise SystemExit(1)

    if len(args) not in [0, 2]:
        print('If frames are specified both first and last ' + \
              'image numbers must be chosen.')
        raise SystemExit(1)
    elif len(args) == 0:
        args = [None, None]

    frame_range = False
    if not args[0]:
        first_frame_num = '1'
    else:
        frame_range = True
        first_frame_num = args[0]
    first_frame_num = first_frame_num.zfill(8)
    first_num = int(first_frame_num)

    if not args[1]:
        last_frame_num = '99999999'
    else:
        last_frame_num = args[1]
    last_frame_num = last_frame_num.zfill(8)
    last_num = int(last_frame_num)

    aspect = opts.get('-a', '2')

    if aspect not in [str(i) for i in range(1,5)]:
        print('Invalid aspect ratio.')
        raise SystemExit(1)

    # 2.21:1 seems to be broken in mp2enc!
    if aspect == '4':
        if not quiet: print("Warning: using aspect ratio 16:9 instead of 2.21:1.")
        aspect = '3'

    vtype = opts.get('-t', 'ml')

    if vtype not in ['hi', 'mh', 'ml', 'lo', \
                     'qlo', 'vcd', 'svcd', 'dvd', \
                     'pvcd', 'psvcd', 'pdvd', \
                     'sdvd', 'spdvd']:
        print('Invalid video type.')
        raise SystemExit(1)

    out_mpg = opts.get('-o', vtype + '_movie.mpg')

    fpsc = opts.get('-f', '4')

    if fpsc not in [str(i) for i in range(1,9)]:
        print('Invalid fps code.')
        raise SystemExit(1)
    elif vtype in ['vcd', 'svcd', 'dvd', 'sdvd']:
        fps = str(30000.0/1001.0)
    elif vtype in ['pvcd', 'psvcd', 'pdvd', 'spdvd']:
        fps = str(25.0)
    else:
        if fpsc == '1': fps = str(24000.0/1001.0)
        elif fpsc == '2': fps = str(24.0)
        elif fpsc == '3': fps = str(25.0)
        elif fpsc == '4': fps = str(30000.0/1001.0)
        elif fpsc == '5': fps = str(30.0)
        elif fpsc == '6': fps = str(50.0)
        elif fpsc == '7': fps = str(60000.0/1001.0)
        elif fpsc == '8': fps = str(60.0)

    if '-e' not in opts:
        enhance = False
    else:
        enhance = True

    if enhance and img_pre:
        print('Sorry, you cannot enhance already-enhanced images')
        raise SystemExit(1)

    if '-k' not in opts:
        keep = False
    else:
        keep = True

    cgeom = opts.get('-c', '')
    rgeom = opts.get('-r', '')

    if (cgeom or rgeom) and not enhance:
        print('Missing "-e" option.')
        raise SystemExit(1)

    lv1file = opts.get('-L', None)
    if lv1file:
        if not quiet: print('Opening lv1 file...')
        try:
            lv1 = tarfile.open(os.path.abspath(lv1file))
        except:
            print('This does not appear to be a valid LiVES file!')
            raise SystemExit(1)
        if 'header.tar' not in lv1.getnames():
            print('This does not appear to be a valid LiVES file!')
            raise SystemExit(1)
        for tfile in lv1.getmembers():
            lv1.extract(tfile, img_dir)
        for tfile in glob.glob(os.path.join(img_dir, '*.tar')):
            imgtar = tarfile.open(tfile)
            for img in imgtar.getmembers():
                imgtar.extract(img, img_dir)
            os.remove(tfile)

    test_file = os.path.join(img_dir, img_pre + first_frame_num)
    if os.path.isfile(test_file + '.jpg'):
        ext = '.jpg'
    elif os.path.isfile(test_file + '.png'):
        ext = '.png'
    else:
        print('Cannot find any appropriate %s or %s files!' % ('.jpg','.png'))
        raise SystemExit(1)
    first_frame = test_file + ext
    last_frame = os.path.join(img_dir, img_pre + last_frame_num + ext)

    if not quiet: print('Found: ' + first_frame)

    work_dir = opts.get('-w', img_dir)
    work_dir = os.path.abspath(work_dir)
    if not os.path.isdir(work_dir):
        if not quiet: print('Creating ' + work_dir)
        try:
            os.makedirs(work_dir)
            os.chmod(work_dir, 0o755)
        except:
            print('Could not create the work directory ' + \
                  work_dir)
            raise SystemExit(1)
    if ' ' in work_dir:
        if temp_dir == '':
            temp_dir = tempfile.mkdtemp('', '.lives-', '/tmp/')
        try:
            os.symlink(work_dir, temp_dir + '/work_dir')
        except (IOError, OSError):
            shutil.copy(work_dir, temp_dir + '/work_dir')
        work_dir = temp_dir + '/work_dir'

    sndf = opts.get('-s', os.path.join(img_dir, 'audio'))
#    sndf = os.path.abspath(sndf)
    rawsndf = True
    if not os.path.isfile(sndf):
        audio = False
        rawsndf = False
    else:
        audio = True
        if sndf[-4:] == '.wav':
            rawsndf = False
        if not quiet: print('Found audio file: ' + sndf)

    sndr = opts.get('-b', '44100')

    delay = opts.get('-D', '0')
    if verbose and audio: print('Linear audio delay (ms): ' + delay)

    if enhance:
        do_enhance()
        # Note that do_enhance() always creates images prefixed
        # with 'rimg'. What's important to note if that if the
        # images are resized the 'rimg' are indeed resized, but
        # if not the 'rimg' are simply symlinks to (or copies of) the 'eimg'
        # (enhanced) images.
        img_pre = 'rimg'
        ext = '.png'
    vidname = os.path.join(work_dir, out_mpg)
    # do_encode() acts on images prefixed by img_pre.
    do_encode()
    if not keep:
        do_clean()
    if temp_dir != '':
        shutil.rmtree(temp_dir)
    if not quiet: print("Done!")


"""
CHANGELOG:

21 Jul 2004 : 0.0.2 : fixed frame range error in img2yuv argument.
                      added support for ".wav" files.
                      added '-C' flag.
28 Jul 2004 : 0.0.3 : added '-D' flag.
                      fixed typos.
                      eliminated some subshell calls.
                      convert dirs to absolute paths.
                      fixed work_dir permissions.
30 Jul 2004 : 0.0.4 : added '-L' flag.
                      encoder is now feature-complete.
25 Sep 2004 : 0.0.5 : make sure "rawsndf" is set correctly.
                      check if files exist before removing.
02 Oct 2004 : 0.0.6 : multiplex even if no audio.
28 Oct 2004 : 0.0.7 : added support for PAL (untested!).
                      fps fix in "common_options".
08 Nov 2004 : 0.0.8 : make sure that the enhanced
                      color depth is 8-bits/channel.
05 Dec 2004 : 0.0.9 : tweak encoding parameters.
                      mention raw audio settings in help.
02 Jan 2005 : 0.1.0 : updated docs.
                      added sound rate (-b) option.
05 Jan 2005 : 0.1.1 : bypass an fps/aspect ratio jpeg2yuv bug.
                      letterbox if 2.21:1.
29 Jan 2005 : 0.1.2 : fix fps 0.1.1 regression.
21 Mar 2005 : 0.1.3 : use env python (hopefully >= 2.3)
26 Mar 2005 : 0.1.4 : added "qlo" setting.
27 Jun 2005 : 0.1.5 : added "sdvd" and "spdvd" settings.
26 Aug 2005 : 0.1.6 : Bypass 2.21:1 brokenness.
09 Mar 2006 : 0.1.7 : added '-depth 8' to resize, as ImageMagick
                      keeps changing its damn behaviour.
28 Jun 2007 : 0.1.8 : handles paths with spaces appropriately
                      (thanks Gabriel).
"""