gonzopi

git clone https://git.tarina.org/gonzopi
Log | Files | Refs | README | LICENSE

gonzopi.py (253952B)


      1 #!/usr/bin/env python3
      2 # -*- coding: utf-8 -*-
      3 
      4 #  ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄    ▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ 
      5 # █       █       █  █  █ █       █       █       █   █
      6 # █   ▄▄▄▄█   ▄   █   █▄█ █▄▄▄▄   █   ▄   █    ▄  █   █
      7 # █  █  ▄▄█  █ █  █       █▄▄▄▄█  █  █ █  █   █▄█ █   █
      8 # █  █ █  █  █▄█  █  ▄    █ ▄▄▄▄▄▄█  █▄█  █    ▄▄▄█   █
      9 # █  █▄▄█ █       █ █ █   █ █▄▄▄▄▄█       █   █   █   █
     10 # █▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█▄█  █▄▄█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█▄▄▄█   █▄▄▄█
     11 
     12 # https://gonzopi.org
     13 cameramode=True
     14 try:
     15     import picamerax as picamera
     16 except:
     17     cameramode=False
     18 import numpy as np
     19 import string
     20 import os
     21 import time
     22 import datetime
     23 import multiprocessing as mp
     24 from subprocess import call
     25 from subprocess import Popen
     26 omxplayermode=True
     27 try:
     28     from omxplayer import OMXPlayer
     29 except:
     30     omxplayermode=False
     31 from multiprocessing import Process, Queue
     32 import subprocess
     33 import sys
     34 import pickle
     35 rpimode=True
     36 try:
     37     import RPi.GPIO as GPIO
     38 except:
     39     rpimode=False
     40 from PIL import Image
     41 import socket
     42 import configparser
     43 import shortuuid
     44 if rpimode == True:
     45     import smbus
     46 import ifaddr
     47 import web
     48 
     49 #import shlex
     50 from blessed import Terminal
     51 
     52 # bless the code!
     53 term = Terminal()
     54 
     55 #DEBIAN VERSION
     56 pipe = subprocess.check_output('lsb_release -c -s', shell=True)
     57 debianversion = pipe.decode().strip()
     58 print('running debian ' + debianversion)
     59 
     60 if rpimode:
     61     #CHECK RASPBERRY PI VERSION
     62     pipe = subprocess.check_output('cat /sys/firmware/devicetree/base/model', shell=True)
     63     raspberrypiversion = pipe.decode().strip()
     64     print('on ' + raspberrypiversion)
     65 
     66     #give permissions to GPIO
     67     os.system('sudo chown root.gpio /dev/gpiomem')
     68     os.system('sudo chmod g+rw /dev/gpiomem')
     69 
     70     #give permissions to RAM
     71     os.system('sudo chown -R pi /dev/shm')
     72 
     73     #make cpu freq performance
     74     os.system('sudo cpufreq-set -g performance')
     75 
     76     #I2CBUTTONS
     77     probei2c = 0
     78     while probei2c < 3:
     79         try:
     80             if debianversion == "stretch":
     81                 os.system('sudo modprobe i2c-dev')
     82                 bus = smbus.SMBus(3) # Rev 2 Pi uses 1
     83             else:
     84                 if 'Raspberry Pi 4 Model B' in raspberrypiversion:
     85                     os.system('sudo modprobe i2c-dev')
     86                     bus = smbus.SMBus(22) # Rev 2 Pi uses 1
     87                 else:
     88                     os.system('sudo modprobe i2c-dev')
     89                     bus = smbus.SMBus(11) # Rev 2 Pi uses 1
     90             DEVICE = 0x20 # Device address (A0-A2)
     91             IODIRB = 0x0d # Pin pullups B-side
     92             IODIRA = 0x00 # Pin pullups A-side 0x0c
     93             IODIRApullup = 0x0c # Pin pullups A-side 0x0c
     94             GPIOB  = 0x13 # Register B-side for inputs
     95             GPIOA  = 0x12 # Register A-side for inputs
     96             OLATA  = 0x14 # Register for outputs
     97             bus.write_byte_data(DEVICE,IODIRB,0xFF) # set all gpiob to input
     98             bus.write_byte_data(DEVICE,IODIRApullup,0xF3) # set two pullup inputs and two outputs 
     99             bus.write_byte_data(DEVICE,IODIRA,0xF3) # set two inputs and two outputs 
    100             bus.write_byte_data(DEVICE,OLATA,0x4)
    101             print("yes, found em i2c buttons!")
    102             i2cbuttons = True
    103             break
    104         except:
    105             print("could not find i2c buttons!! running in keyboard only mode")
    106             print("trying again...")
    107             i2cbuttons = False
    108             probei2c += 1
    109             time.sleep(1)
    110             bus=''
    111 else:
    112     i2cbuttons = False
    113 
    114 #MAIN
    115 def main():
    116     global headphoneslevel, miclevel, gonzopifolder, screen, loadfilmsettings, plughw, channels, filmfolder, scene, showmenu, rendermenu, quality, profilelevel, i2cbuttons, menudone, soundrate, soundformat, process, serverstate, que, port, recording, onlysound, camera_model, fps_selection, fps_selected, fps, db, selected, cammode, newfilmname, camera_recording, abc, showhelp, camera, overlay, overlay2, recordwithports
    117     # Get path of the current dir, then use it as working directory:
    118     rundir = os.path.dirname(__file__)
    119     if rundir != '':
    120         os.chdir(rundir)
    121     #filmfolder = "/home/pi/Videos/"
    122     #picfolder = "/home/pi/Pictures/"
    123     gonzopifolder = os.getcwd()
    124 
    125     #MENUS
    126     standardmenu = 'DSK:', 'FILM:', 'SCENE:', 'SHOT:', 'TAKE:', '', 'SHUTTER:', 'ISO:', 'RED:', 'BLUE:', 'FPS:', 'Q:', 'BRIGHT:', 'CONT:', 'SAT:', 'SFX:', 'FLIP:', 'BEEP:', 'LENGTH:', 'HW:', 'CH:', 'MIC:', 'PHONES:', 'COMP:', 'TIMELAPSE', 'MODE:', 'SHUTDOWN', 'SRV:', 'SEARCH:', 'WIFI:', 'UPDATE', 'UPLOAD', 'BACKUP', 'LOAD', 'NEW', 'TITLE', 'LIVE:'
    127     gonzopictrlmenu = 'DSK:', 'FILM:', 'SCENE:', 'SHOT:', 'TAKE:', '', 'SHUTTER:', 'ISO:', 'RED:', 'BLUE:', 'FPS:', 'Q:', 'BRIGHT:', 'CONT:', 'SAT:', 'SFX:', 'FLIP:', 'BEEP:', 'LENGTH:', 'HW:', 'CH:', 'MIC:', 'PHONES:', 'COMP:', 'TIMELAPSE', 'MODE:','SHUTDOWN', 'SRV:', 'SEARCH:', 'WIFI:', 'CAMERA:', 'Add CAMERA', 'New FILM', 'New SCENE', 'Sync SCENE'
    128     #gonzopictrlmenu = "BACK","CAMERA:", "Add CAMERA","New FILM","","New SCENE","Sync SCENE","Snapshot"
    129     emptymenu='','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''
    130     menu = standardmenu
    131     showgonzopictrl = False
    132     recordwithports = False
    133     pressagain = ''
    134     #STANDARD VALUES (some of these may not be needed, should do some clean up)
    135     abc = '_','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0'
    136     numbers_only = ' ','1','2','3','4','5','6','7','8','9','0'
    137     keydelay = 0.0555
    138     selectedaction = 0
    139     selected = 0
    140     awb = 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon'
    141     awbx = 0
    142     awb_lock = 'no'
    143     effects = 'none', 'negative', 'solarize'
    144     effectselected = 0
    145     cammode = 'film'
    146     camera_model=''
    147     fps = 25
    148     fps_selected=8
    149     fps_selection=[]
    150     quality = 25
    151     profilelevel='4.2'
    152     headphoneslevel = 40
    153     miclevel = 50
    154     soundformat = 'S16_LE'
    155     soundrate = '48000'
    156     recording = False
    157     retake = False
    158     lastmenu = ''
    159     menudone = ''
    160     rendermenu = True
    161     showmenu = 1
    162     showmenu_settings = True
    163     showhelp = False
    164     oldchecksync = ''
    165     overlay = None
    166     overlay2 = None
    167     underlay = None
    168     reclenght = 0
    169     t = 0
    170     rectime = ''
    171     scene = 1
    172     shot = 1
    173     take = 1
    174     pic = 1
    175     onlysound=False
    176     filmname = 'reel_001'
    177     newfilmname = ''
    178     beeps = 0
    179     beepcountdown = 0
    180     beeping = False
    181     backlight = True
    182     lastbeep = time.time()
    183     flip = 'no'
    184     between = 30
    185     duration = 0.2
    186     dsk = 0
    187     lenses = os.listdir('lenses/')
    188     lens = lenses[0]
    189     buttontime = time.time()
    190     pressed = ''
    191     buttonpressed = False
    192     holdbutton = ''
    193     updatethumb = False
    194     loadfilmsettings = True
    195     oldsettings = ''
    196     comp = 0
    197     yanked = ''
    198     copying = ''
    199     moving = False
    200     stream = ''
    201     live = 'no'
    202     peakshot = ''
    203     peaktake = ''
    204     plughw = 0 #default audio device
    205     channels = 1 #default mono
    206     #SAVE SETTINGS FREQUENCY IN SECS
    207     pausetime = time.time()
    208     savesettingsevery = 5
    209     #TARINA VERSION
    210     f = open(gonzopifolder + '/VERSION')
    211     gonzopiversion = f.readline()
    212     gonzopivername = f.readline()
    213     db=''
    214     synclist=[]
    215 
    216     if rpimode:
    217         #START INTERFACE
    218         startinterface()
    219         #FIRE UP CAMERA
    220         camera = startcamera(lens,fps)
    221     else:
    222         camera=None
    223 
    224     #GET FILMFOLDER AND CAMERA VERSION
    225     camera_model, camera_revision , filmfolder = getconfig(camera)
    226     if os.path.isdir(filmfolder) == False:
    227         os.makedirs(filmfolder)
    228 
    229     #SYSTEM CONFIGS (turn off hdmi)
    230     #run_command('tvservice -o')
    231     #Kernel page cache optimization for sd card
    232     if rpimode:
    233         run_command('sudo ' + gonzopifolder + '/extras/sdcardhack.sh')
    234         #Make screen shut off work and run full brightness
    235         run_command('gpio -g mode 19 pwm ')
    236         run_command('gpio -g pwm 19 1023')
    237     
    238     #STORAGE DRIVES
    239     storagedrives=[['sd',filmfolder]]
    240 
    241     #CHECK IF FILMING TO USB STORAGE
    242     #if os.path.exists('/dev/sda1') == False:
    243     #    os.system('sudo pumount /media/usb0')
    244     #    os.system('sudo umount -l /media/usb0')
    245     #if os.path.exists('/dev/sda2') == False:
    246     #    os.system('sudo pumount /media/usb1')
    247     #    os.system('sudo umount -l /media/usb1')
    248     filmfolderusb=usbfilmfolder(dsk)
    249     if filmfolderusb:
    250         filmfolder=filmfolderusb
    251         storagedrives.append(['usb0',filmfolder])
    252         dsk=1
    253         loadfilmsettings == True
    254         if os.path.isdir(filmfolder) == False:
    255             os.makedirs(filmfolder)
    256  
    257     #COUNT DISKSPACE
    258     disk = os.statvfs(filmfolder)
    259     diskleft = str(int(disk.f_bavail * disk.f_frsize / 1024 / 1024 / 1024)) + 'Gb'
    260 
    261     #LOAD FILM AND SCENE SETTINGS
    262     try:
    263         filmname = getfilms(filmfolder)[0][0]
    264     except:
    265         filmname = filmname 
    266         if os.path.isdir(filmfolder+filmname) == False:
    267             os.makedirs(filmfolder+filmname)
    268 
    269     #THUMBNAILCHECKER
    270     oldscene = scene
    271     oldshot = shot
    272     oldtake = take
    273 
    274     #TURN ON WIFI AND TARINA SERVER
    275     serverstate = 'on'
    276     wifistate = 'on'
    277     if os.path.isdir(gonzopifolder+'/srv/sessions') == False:
    278         os.makedirs(gonzopifolder+'/srv/sessions')
    279     os.system('sudo chown -R www-data '+gonzopifolder+'/srv/sessions')
    280     os.system('sudo ln -sf /dev/shm/srv/menu.html '+gonzopifolder+'/srv/static/menu.html')
    281     os.system('sudo mkdir /dev/shm/srv')
    282     os.system('sudo chown -R www-data /dev/shm/srv')
    283     os.system('sudo chown -R www-data '+gonzopifolder+'/srv/static/')
    284     #serverstate = gonzopiserver(False)
    285     #TO_BE_OR_NOT_TO_BE 
    286     foldername = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3) + '/'
    287     filename = 'take' + str(take).zfill(3)
    288     recordable = not os.path.isfile(foldername + filename + '.mp4') and not os.path.isfile(foldername + filename + '.h264')
    289 
    290     #CLEAN
    291     #clean('',filmfolder)
    292 
    293     #--------------Gonzopi Controller over socket ports --------#
    294 
    295     #TARINACTRL
    296     camerasconnected=''
    297     sleep=0.2
    298     cameras = []
    299     camerasoff =[]
    300     camselected=0
    301     newselected=0 
    302     mastersound=None
    303     camera_recording=None
    304     pingip=0
    305     searchforcameras='off'
    306     #NETWORKS
    307     networks=[]
    308     adapters = ifaddr.get_adapters()
    309     for adapter in adapters:
    310         print("IPs of network adapter " + adapter.nice_name)
    311         for ip in adapter.ips:
    312             if ':' not in ip.ip[0] and '127.0.0.1' != ip.ip:
    313                 print(ip.ip)
    314                 networks=[ip.ip]
    315     if networks != []:
    316         network=networks[0]
    317         if network not in cameras:
    318             cameras=[]
    319             cameras.append(network)
    320 
    321     port = 55555
    322     que = Queue()
    323     process = Process(target=listenforclients, args=("0.0.0.0", port, que))
    324     process.start()
    325     nextstatus = ''
    326 
    327     serverstate_old='off'
    328     wifistate_old='off'
    329 
    330 
    331     if rpimode:
    332         #--------------Rpi MAIN LOOP---------------#
    333         while True:
    334             pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
    335             if pressagain != '':
    336                 pressed = pressagain
    337                 pressagain = ''
    338             #event = screen.getch()
    339             if wifistate != wifistate_old:
    340                 if wifistate == 'on':
    341                     run_command('sudo iwconfig wlan0 txpower auto')
    342                 elif wifistate == 'off':
    343                     run_command('sudo iwconfig wlan0 txpower off')
    344                 wifistate_old = wifistate
    345             if serverstate != serverstate_old:
    346                 if serverstate == 'on':
    347                     gonzopiserver(True)
    348                 elif serverstate == 'off':
    349                     gonzopiserver(False)
    350                 serverstate_old=serverstate
    351             if recording == False:
    352                 #SHUTDOWN
    353                 if pressed == 'middle' and menu[selected] == 'SHUTDOWN':
    354                     writemessage('Hold on shutting down...')
    355                     time.sleep(1)
    356                     run_command('sudo shutdown -h now')
    357                 #MODE
    358                 elif pressed == 'changemode':
    359                     if cammode == 'film':
    360                         cammode = 'picture'
    361                         vumetermessage('changing to picture mode')
    362                     elif cammode == 'picture':
    363                         cammode = 'film'
    364                         vumetermessage('changing to film mode')
    365                     camera.stop_preview()
    366                     camera.close()
    367                     camera = startcamera(lens,fps)
    368                     loadfilmsettings = True
    369                 #PICTURE
    370                 elif pressed == 'picture':
    371                     if os.path.isdir(foldername) == False:
    372                         os.makedirs(foldername)
    373                     picture = foldername +'picture' + str(take).zfill(3) + '.jpeg'
    374                     run_command('touch ' + foldername + '.placeholder')
    375                     print('taking picture')
    376                     camera.capture(picture,format="jpeg",use_video_port=True) 
    377                 #PEAKING
    378                 elif pressed == 'peak' and recordable == True:
    379                     if shot > 1:
    380                         peakshot = shot - 1
    381                         peaktake = counttakes(filmname, filmfolder, scene, peakshot)
    382                     p_imagename = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(peakshot).zfill(3) + '/take' + str(peaktake).zfill(3) + '.jpeg'
    383                     overlay = displayimage(camera, p_imagename, overlay, 3)
    384                     while holdbutton == 'peak':
    385                         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
    386                         vumetermessage('peaking ' + str(peakshot))
    387                         time.sleep(0.03)
    388                     overlay = removeimage(camera, overlay)
    389                 #SHOWHELP
    390                 elif pressed == 'showhelp':
    391                     vumetermessage('Button layout')
    392                     if showhelp == False:
    393                         overlay2 = removeimage(camera, overlay2)
    394                         overlay2 = displayimage(camera, gonzopifolder+'/extras/buttons.png', overlay, 4)
    395                         showhelp = True
    396                     elif showhelp == True:
    397                         overlay2 = removeimage(camera, overlay2)
    398                         updatethumb =  True
    399                         showhelp = False
    400                     #while holdbutton == 'showhelp' or pressed == 'H':
    401                     #    pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
    402                     #    vumetermessage('Button layout')
    403                     #    time.sleep(0.03)
    404                 #TIMELAPSE
    405                 elif pressed == 'middle' and menu[selected] == 'TIMELAPSE':
    406                     overlay = removeimage(camera, overlay)
    407                     takes = counttakes(filmname, filmfolder, scene, shot)
    408                     if takes > 0:
    409                         shot = countshots(filmname, filmfolder, scene) + 1
    410                         take = 1
    411                     foldername = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3) + '/'
    412                     filename = 'take' + str(take).zfill(3)
    413                     renderedfilename, between, duration = timelapse(beeps,camera,filmname,foldername,filename,between,duration,backlight)
    414                     if renderedfilename != '':
    415                         #render thumbnail
    416                         #writemessage('creating thumbnail')
    417                         #run_command('avconv -i ' + foldername + filename  + '.mp4 -frames 1 -vf scale=800:460 ' + foldername + filename + '.jpeg')
    418                         updatethumb =  True
    419                 #VIEW SCENE
    420                 elif pressed == 'view' and menu[selected] == 'SCENE:':
    421                     writemessage('Loading scene...')
    422                     organize(filmfolder, filmname)
    423                     filmfiles = shotfiles(filmfolder, filmname, scene)
    424                     vumetermessage('press middlebutton to cancel')
    425                     if len(filmfiles) > 0:
    426                         #Check if rendered video exist
    427                         camera.stop_preview()
    428                         #renderfilename, newaudiomix = renderscene(filmfolder, filmname, scene)
    429                         renderfilename = renderfilm(filmfolder, filmname, comp, scene, True)
    430                         if renderfilename != '':
    431                             remove_shots = playdub(filmname,renderfilename, 'film')
    432                             #fastedit (maybe deploy sometime)
    433                             #if remove_shots != []:
    434                             #    for i in remove_shots:
    435                             #        remove(filmfolder, filmname, scene, i, take, 'shot')
    436                             #    organize(filmfolder, filmname)
    437                             #    updatethumb = True
    438                             #    #loadfilmsettings = True
    439                             #    time.sleep(0.5)
    440                             #else:
    441                             #    print('nothing to remove')
    442                             camera.start_preview()
    443                     else:
    444                         vumetermessage("There's absolutely nothing in this scene! hit rec!")
    445                     updatethumb=True
    446                     rendermenu = True
    447                 #VIEW FILM
    448                 elif pressed == 'view' and menu[selected] == 'FILM:':
    449                     writemessage('Loading film...')
    450                     organize(filmfolder, filmname)
    451                     filmfiles = viewfilm(filmfolder, filmname)
    452                     vumetermessage('press middlebutton to cancel')
    453                     if len(filmfiles) > 0:
    454                         camera.stop_preview()
    455                         #removeimage(camera, overlay)
    456                         renderfilename = renderfilm(filmfolder, filmname, comp, 0, True)
    457                         if renderfilename != '':
    458                             remove_shots = playdub(filmname,renderfilename, 'film')
    459                         #overlay = displayimage(camera, imagename, overlay, 3)
    460                         camera.start_preview()
    461                     else:
    462                         vumetermessage('wow, shoot first! there is zero, nada, zip footage to watch now... just hit rec!')
    463                     updatethumb=True
    464                     rendermenu = True
    465                 #VIEW SHOT OR TAKE
    466                 elif pressed == 'view':
    467                     writemessage('Loading clip...')
    468                     organize(filmfolder, filmname)
    469                     takes = counttakes(filmname, filmfolder, scene, shot)
    470                     vumetermessage('press middlebutton to cancel')
    471                     if takes > 0:
    472                         removeimage(camera, overlay)
    473                         camera.stop_preview()
    474                         foldername = filmfolder + filmname + '/scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3) + '/'
    475                         filename = 'take' + str(take).zfill(3)
    476                         #compileshot(foldername + filename,filmfolder,filmname)
    477                         renderfilename, newaudiomix = rendershot(filmfolder, filmname, foldername+filename, scene, shot)
    478                         if renderfilename != '':
    479                             trim = playdub(filmname,foldername + filename, 'shot')
    480                             if trim[0] == 'beginning' or trim[0] == 'end':
    481                                 writemessage('Cutting clip...')
    482                                 take = counttakes(filmname, filmfolder, scene, shot)+1
    483                                 trim_filename = foldername + 'take' + str(take).zfill(3)
    484                                 videotrim(foldername, foldername + filename, trim_filename, trim[0], trim[1])
    485                             elif trim[0] >= trim[1]:
    486                                 trim = [trim[0],0]
    487                             elif trim[0] != 0 and trim[1] != 0:
    488                                 writemessage('Cutting clip...')
    489                                 take = counttakes(filmname, filmfolder, scene, shot)+1
    490                                 trim_filename = foldername + 'take' + str(take).zfill(3)
    491                                 videotrim(foldername, foldername + filename, trim_filename, 'end', trim[1])
    492                                 take = counttakes(filmname, filmfolder, scene, shot)+1
    493                                 trim_filename2 = foldername + 'take' + str(take).zfill(3)
    494                                 videotrim(foldername, trim_filename, trim_filename2, 'beginning', trim[0])
    495                             elif trim[0] == 0 and trim[1] != 0:
    496                                 writemessage('Cutting clip...')
    497                                 take = counttakes(filmname, filmfolder, scene, shot)+1
    498                                 trim_filename = foldername + 'take' + str(take).zfill(3)
    499                                 videotrim(foldername, foldername + filename, trim_filename, 'end', trim[1])
    500                             if trim[0] != 0 and trim[1] == 0:
    501                                 writemessage('Cutting clip...')
    502                                 take = counttakes(filmname, filmfolder, scene, shot)+1
    503                                 trim_filename = foldername + 'take' + str(take).zfill(3)
    504                                 videotrim(foldername, foldername + filename, trim_filename, 'beginning', trim[0])
    505                             imagename = foldername + filename + '.jpeg'
    506                             overlay = displayimage(camera, imagename, overlay, 3)
    507                             camera.start_preview()
    508                         else:
    509                             vumetermessage('nothing here! hit rec!')
    510                         rendermenu = True
    511                         updatethumb=True
    512                 #DUB SHOT
    513                 elif pressed == 'middle' and menu[selected] == 'SHOT:' and recordable == False:
    514                     newdub = clipsettings(filmfolder, filmname, scene, shot, take, plughw)
    515                     take = counttakes(filmname, filmfolder, scene, shot)
    516                     if newdub:
    517                         camera.stop_preview()
    518                         #save original sound
    519                         dubfolder = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/dub/'
    520                         saveoriginal = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/take'+str(take).zfill(3)+'.wav'
    521                         dubfiles, dubmix, newmix = getdubs(filmfolder, filmname, scene, shot)
    522                         foldername = filmfolder + filmname + '/scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3) + '/'
    523                         filename = 'take' + str(take).zfill(3)
    524                         if dubfiles==[]:
    525                             print('no dubs, copying original sound to original')
    526                             os.system('cp '+saveoriginal+' '+dubfolder+'original.wav')
    527                             time.sleep(0.2)
    528                         renderfilename, newaudiomix = rendershot(filmfolder, filmname, foldername+filename, scene, shot)
    529                         playdub(filmname,renderfilename, 'dub')
    530                         #run_command('sox -V0 -G /dev/shm/dub.wav -c 2 ' + newdub)
    531                         #add audio/video start delay sync
    532                         run_command('sox -V0 -G /dev/shm/dub.wav -c 2 /dev/shm/temp.wav trim 0.013')
    533                         run_command('mv /dev/shm/temp.wav '+ newdub)
    534                         audiosync, videolenght, audiolenght = audiotrim(renderfilename, 'end', newdub)
    535                         vumetermessage('new shot dubbing made!')
    536                         #rerender audio
    537                         os.system('rm ' + filmfolder + filmname + '/.audiohash')
    538                         camera.start_preview()
    539                         time.sleep(1)
    540                     else:
    541                         vumetermessage('see ya around!')
    542                     rendermenu = True
    543                 #DUB SCENE
    544                 elif pressed == 'middle' and menu[selected] == 'SCENE:':
    545                     newdub = clipsettings(filmfolder, filmname, scene, 0, take, plughw)
    546                     if newdub:
    547                         camera.stop_preview()
    548                         renderfilename, newaudiomix = renderscene(filmfolder, filmname, scene)
    549                         playdub(filmname,renderfilename, 'dub')
    550                         #run_command('sox -V0 -G /dev/shm/dub.wav -c 2 ' + newdub)
    551                         #add audio/video start delay sync
    552                         run_command('sox -V0 -G /dev/shm/dub.wav -c 2 /dev/shm/temp.wav trim 0.013')
    553                         run_command('mv /dev/shm/temp.wav '+ newdub)
    554                         audiosync, videolenght, audiolenght = audiotrim(renderfilename, 'end', newdub)
    555                         vumetermessage('new scene dubbing made!')
    556                         #rerender audio
    557                         os.system('rm ' + filmfolder + filmname + '/.audiohash')
    558                         camera.start_preview()
    559                         time.sleep(1)
    560                     else:
    561                         vumetermessage('see ya around!')
    562                     rendermenu = True
    563                 #DUB FILM
    564                 elif pressed == 'middle' and menu[selected] == 'FILM:':
    565                     newdub = clipsettings(filmfolder, filmname, 0, 0, take, plughw)
    566                     if newdub:
    567                         camera.stop_preview()
    568                         renderfilename = renderfilm(filmfolder, filmname, comp, 0, False)
    569                         playdub(filmname,renderfilename, 'dub')
    570                         run_command('sox -V0 -G /dev/shm/dub.wav -c 2 ' + newdub)
    571                         vumetermessage('new film dubbing made!')
    572                         camera.start_preview()
    573                         time.sleep(1)
    574                     else:
    575                         vumetermessage('see ya around!')
    576                     rendermenu = True
    577                 #BACKUP
    578                 elif pressed == 'middle' and menu[selected] == 'BACKUP':
    579                     copytousb(filmfolder)
    580                     rendermenu = True
    581                 #UPLOAD
    582                 elif pressed == 'middle' and menu[selected] == 'UPLOAD':
    583                     if webz_on() == True:
    584                         filmfiles = viewfilm(filmfolder, filmname)
    585                         if len(filmfiles) > 0:
    586                             renderfilename = renderfilm(filmfolder, filmname, comp, 0, True)
    587                             cmd = uploadfilm(renderfilename, filmname)
    588                             if cmd != None:
    589                                 stopinterface(camera)
    590                                 try:
    591                                     run_command(cmd)
    592                                 except:
    593                                     logger.warning('uploadfilm bugging')
    594                                 startinterface()
    595                                 camera = startcamera(lens,fps)
    596                                 loadfilmsettings = True
    597                             selectedaction = 0
    598                     rendermenu = True
    599                 #LOAD FILM
    600                 elif pressed == 'middle' and menu[selected] == 'LOAD':
    601                     filmname = loadfilm(filmname, filmfolder, camera, overlay)
    602                     loadfilmsettings = True
    603                 #UPDATE
    604                 elif pressed == 'middle' and menu[selected] == 'UPDATE':
    605                     if webz_on() == True:
    606                         stopinterface(camera)
    607                         gonzopiversion, gonzopivername = update(gonzopiversion, gonzopivername)
    608                         startinterface()
    609                         camera = startcamera(lens,fps)
    610                         loadfilmsettings = True
    611                         selectedaction = 0
    612                     rendermenu = True
    613                 #WIFI
    614                 elif pressed == 'middle' and menu[selected] == 'WIFI:':
    615                     stopinterface(camera)
    616                     run_command('wicd-curses')
    617                     startinterface()
    618                     camera = startcamera(lens,fps)
    619                     loadfilmsettings = True
    620                     rendermenu = True
    621                 #NEW FILM
    622                 elif pressed == 'middle' and menu[selected] == 'NEW' or filmname == '' or pressed == 'new_film':
    623                     filmname_exist=False
    624                     if newfilmname == '':
    625                         newfilmname = nameyourfilm(filmfolder, filmname, abc, True)
    626                     allfilm = getfilms(filmfolder)
    627                     for i in allfilm:
    628                         if i[0] == newfilmname:
    629                             filmname_exist=True
    630                     if filmname != newfilmname and filmname_exist==False:
    631                         filmname = newfilmname
    632                         os.makedirs(filmfolder + filmname)
    633                         vumetermessage('Good luck with your film ' + filmname + '!')
    634                         #make a filmhash
    635                         print('making filmhash...')
    636                         filmhash = shortuuid.uuid()
    637                         with open(filmfolder + filmname + '/.filmhash', 'w') as f:
    638                             f.write(filmhash)
    639                         updatethumb = True
    640                         rendermenu = True
    641                         scene = 1
    642                         shot = 1
    643                         take = 1
    644                         #selectedaction = 0
    645                         newfilmname = ''
    646                     else:
    647                         print(term.clear)
    648                         filmname = newfilmname
    649                         newfilmname = ''
    650                         vumetermessage('film already exist!')
    651                         logger.info('film already exist!')
    652                         updatethumb = True
    653                         loadfilmsettings = True
    654                         rendermenu = True
    655                 #EDIT FILM NAME
    656                 elif pressed == 'middle' and menu[selected] == 'TITLE' or filmname == '':
    657                     newfilmname = nameyourfilm(filmfolder, filmname, abc, False)
    658                     if filmname != newfilmname:
    659                         os.system('mv ' + filmfolder + filmname + ' ' + filmfolder + newfilmname)
    660                         filmname = newfilmname
    661                         db = get_film_files(filmname,filmfolder,db)
    662                         vumetermessage('Film title changed to ' + filmname + '!')
    663                     else:
    664                         vumetermessage('')
    665                     rendermenu = True
    666                 #(YANK) COPY FILM
    667                 elif pressed == 'copy' and menu[selected] == 'FILM:' and recordable == False:
    668                     copying = 'film'
    669                     yanked = filmfolder + filmname
    670                     vumetermessage('Film ' + filmname + ' copied! (I)nsert button to place it...')
    671                 #(YANK) COPY TAKE
    672                 elif pressed == 'copy' and menu[selected] == 'TAKE:' and recordable == False:
    673                     copying = 'take'
    674                     yanked = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3)+'/take' + str(take).zfill(3)
    675                     vumetermessage('Take ' + str(take) + ' copied! (I)nsert button to place it...')
    676                 #(YANK) COPY SHOT
    677                 elif pressed == 'copy' and menu[selected] == 'SHOT:':
    678                     copying = 'shot'
    679                     yanked = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3)
    680                     vumetermessage('Shot ' + str(shot) + ' copied! (I)nsert button to place it...')
    681                 #(YANK) COPY SCENE
    682                 elif pressed == 'copy' and menu[selected] == 'SCENE:':
    683                     copying = 'scene'
    684                     yanked = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3)
    685                     vumetermessage('Scene ' + str(scene) + ' copied! (I)nsert button to place it...')
    686                 #(CUT) MOVE TAKE
    687                 elif pressed == 'move' and menu[selected] == 'TAKE:' and recordable == False:
    688                     copying = 'take'
    689                     moving = True
    690                     yanked = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3)+'/take' + str(take).zfill(3)
    691                     vumetermessage('Moving shot ' + str(shot) + ' (I)nsert button to place it...')
    692                 #(CUT) MOVE SHOT
    693                 elif pressed == 'move' and menu[selected] == 'SHOT:':
    694                     copying='shot'
    695                     moving = True
    696                     yanked = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3)
    697                     vumetermessage('Moving shot ' + str(shot) + ' (I)nsert button to place it...')
    698                 #(CUT) MOVE SCENE
    699                 elif pressed == 'move' and menu[selected] == 'SCENE:':
    700                     copying='scene'
    701                     moving = True
    702                     yanked = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3)
    703                     vumetermessage('Moving scene ' + str(scene) + ' (I)nsert button to place it...')
    704                 #PASTE SHOT and PASTE SCENE
    705                 elif pressed == 'insert' and yanked:
    706                     if copying == 'take':
    707                         take = counttakes(filmname, filmfolder, scene, shot)
    708                         take=take+1
    709                         vumetermessage('Pasting take, please wait...')
    710                         paste = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3) + '/take' + str(take).zfill(3)
    711                         #try:
    712                         #    os.makedirs(filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot'+ str(shot).zfill(3))
    713                         #except:
    714                         #    pass
    715                         os.system('cp ' + yanked + '.mp4 ' + paste + '.mp4')
    716                         os.system('cp ' + yanked + '.jpeg ' + paste + '.jpeg')
    717                         os.system('cp ' + yanked + '.h264 ' + paste + '.h264')
    718                         os.system('cp ' + yanked + '.wav ' + paste + '.wav')
    719                         paste = ''
    720                         if moving == True:
    721                             os.system('rm -r ' + yanked + '*')
    722                     elif copying == 'shot':
    723                         vumetermessage('Pasting shot, please wait...')
    724                         paste = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot-1).zfill(3) + '_yanked' 
    725                         try:
    726                             os.makedirs(filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3))
    727                         except:
    728                             pass
    729                         os.system('cp -r ' + yanked + ' ' + paste)
    730                         if moving == True:
    731                             os.system('rm -r ' + yanked+'/*')
    732                             #Remove hidden placeholder
    733                             #os.system('rm ' + yanked + '/.placeholder')
    734                     elif copying == 'scene':
    735                         vumetermessage('Pasting scene, please wait...')
    736                         paste = filmfolder + filmname + '/' + 'scene' + str(scene-1).zfill(3) + '_yanked'
    737                         os.system('cp -r ' + yanked + ' ' + paste)
    738                         if moving == True:
    739                             os.system('rm -r ' + yanked+'/*')
    740                             #Remove hidden placeholder
    741                             #os.system('rm ' + yanked + '/.placeholder')
    742                     elif copying == 'film':
    743                         vumetermessage('Pasting film, please wait...')
    744                         paste = filmfolder+filmname+'_copy'
    745                         os.system('cp -r ' + yanked + ' ' + paste)
    746                         try:
    747                             run_command('rsync -avr --update --progress --files-from='+yanked+'/.origin_videos --no-relative / ' +filmfolder+'.videos/')
    748                         except:
    749                             logger.info('no origin videos')
    750                         #if moving == True:
    751                             #os.system('rm -r ' + yanked)
    752                             #Remove hidden placeholder
    753                             #os.system('rm ' + yanked + '/.placeholder')
    754                     add_organize(filmfolder, filmname)
    755                     organize(filmfolder, filmname)
    756                     organize(filmfolder, filmname)
    757                     updatethumb = True
    758                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    759                     if scene > scenes:
    760                         scene = scenes
    761                     if shot > shots:
    762                         shot = shots
    763                     yanked = ''
    764                     copying = ''
    765                     moving = False
    766                     vumetermessage('Pasted!')
    767                     #time.sleep(3)
    768                 #INSERT SHOT
    769                 elif pressed == 'insert' and menu[selected] != 'SCENE:' and yanked == '':
    770                     insertshot = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot-1).zfill(3) + '_insert'
    771                     try:
    772                         os.makedirs(insertshot)
    773                     except:
    774                         print('is there already prob')
    775                     add_organize(filmfolder, filmname)
    776                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    777                     #vumetermessage('Shot ' + str(shot) + ' inserted')
    778                     updatethumb = True
    779                     time.sleep(1)
    780                 #INSERT SHOT TO LAST SHOT
    781                 elif pressed == 'insert_shot':
    782                     logger.info('inserting shot')
    783                     shot = countshots(filmname, filmfolder, scene)
    784                     shot=shot+1
    785                     insertshot = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot-1).zfill(3) + '_insert'
    786                     try:
    787                         os.makedirs(insertshot)
    788                     except:
    789                         print('is there already prob')
    790                     add_organize(filmfolder, filmname)
    791                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    792                     #vumetermessage('Shot ' + str(shot) + ' inserted')
    793                     updatethumb = True
    794                 #INSERT TAKE
    795                 elif pressed == 'insert_take':
    796                     logger.info('inserting take')
    797                     insertshot = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3)
    798                     try:
    799                         os.makedirs(insertshot)
    800                         run_command('touch ' + insertshot + '/.placeholder')
    801                     except:
    802                         print('is there already prob')
    803                     add_organize(filmfolder, filmname)
    804                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    805                     #vumetermessage('Take ' + str(shot) + ' inserted')
    806                     updatethumb = True
    807                     #time.sleep(1)
    808                 #INSERT SCENE
    809                 elif pressed == 'insert' and menu[selected] == 'SCENE:' and recordable == False and yanked == '':
    810                     insertscene = filmfolder + filmname + '/' + 'scene' + str(scene-1).zfill(3) + '_insert'
    811                     logger.info("inserting scene")
    812                     os.makedirs(insertscene)
    813                     add_organize(filmfolder, filmname)
    814                     take = 1
    815                     shot = 1
    816                     updatethumb = True
    817                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    818                     #vumetermessage('Scene ' + str(scene) + ' inserted')
    819                     time.sleep(1)
    820                 #NEW SCENE
    821                 elif pressed == 'new_scene':
    822                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    823                     vumetermessage('got new scene')
    824                     scene=scenes+1
    825                     shot=1
    826                     take=1
    827                 #DEVELOP
    828                 elif event == 'D':
    829                     try:
    830                         stopinterface(camera)
    831                         code.interact(local=locals())
    832                         startinterface()
    833                         camera = startcamera(lens,fps)
    834                         loadfilmsetings = True
    835                     except:
    836                         writemessage('hmm.. couldnt enter developer mode')
    837                 #TURN OFF SCREEN
    838                 elif pressed == 'screen':
    839                     if backlight == False:
    840                         # requires wiringpi installed
    841                         run_command('gpio -g pwm 19 1023')
    842                         backlight = True
    843                         camera.start_preview()
    844                     elif backlight == True:
    845                         run_command('gpio -g pwm 19 0')
    846                         backlight = False
    847                         camera.stop_preview()
    848                 elif pressed == 'showmenu':
    849                     if showmenu == 1:
    850                         # requires wiringpi installed
    851                         showmenu = 0
    852                         showmenu_settings = False
    853                     elif showmenu == 0:
    854                         showmenu = 1
    855                         showmenu_settings = True
    856                 #DSK
    857                 elif pressed == 'middle' and menu[selected] == 'DSK:':
    858                     print("usb filmfolder")
    859                     vumetermessage('checking usb mount...')
    860                     filmfolderusb=usbfilmfolder(dsk)
    861                     if filmfolderusb:
    862                         filmfolder=filmfolderusb
    863                         if dsk < 1:
    864                             storagedrives.append(['usb0',filmfolder])
    865                             dsk=1
    866                             loadfilmsettings = True
    867                         elif dsk > 0:
    868                             storagedrives.append(['usb1',filmfolder])
    869                             dsk=2
    870                             loadfilmsettings = True
    871                     else:
    872                         camera_model, camera_revision , filmfolder = getconfig(camera)
    873                         if os.path.isdir(filmfolder) == False:
    874                             os.makedirs(filmfolder)
    875                     #COUNT DISKSPACE
    876                     #sudo mkfs -t ext4 /dev/sdb1
    877                     disk = os.statvfs(filmfolder)
    878                     diskleft = str(int(disk.f_bavail * disk.f_frsize / 1024 / 1024 / 1024)) + 'Gb'
    879                     #LOAD FILM AND SCENE SETTINGS
    880                     try:
    881                         filmname = getfilms(filmfolder)[0][0]
    882                     except:
    883                         filmname = 'onthefloor' 
    884                     try:
    885                         filmname_back = getfilms(filmfolder)[0][1]
    886                     except:
    887                         filmname_back = 'onthefloor' 
    888                     if os.path.isdir(filmfolder) == False:
    889                         os.makedirs(filmfolder)
    890                     #loadfilmsettings = True
    891                     updatethumb = True
    892                     rendermenu = True
    893                     #cleanupdisk(filmname,filmfolder)
    894                     serverstate = gonzopiserver(False)
    895                     serverstate = gonzopiserver(True)
    896                 #REMOVE DELETE
    897                 #dsk
    898                 elif pressed == 'remove' and menu[selected] == 'DSK:':
    899                     if dsk != 0:
    900                         print("usb filmfolder")
    901                         os.system('sudo pumount /media/usb'+str(dsk))
    902                         os.system('sudo umount -l /media/usb'+str(dsk))
    903                         try:
    904                             del storagedrives[dsk]
    905                         except:
    906                             pass
    907                         dsk=0
    908                         time.sleep(1)
    909                 #take
    910                 elif pressed == 'remove' and menu[selected] == 'TAKE:':
    911                     remove(filmfolder, filmname, scene, shot, take, 'take')
    912                     organize(filmfolder, filmname)
    913                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    914                     take = counttakes(filmname, filmfolder, scene, shot)
    915                     updatethumb = True
    916                     rendermenu = True
    917                     #loadfilmsettings = True
    918                     time.sleep(0.2)
    919                 #shot
    920                 elif pressed == 'remove' and menu[selected] == 'SHOT:':
    921                     remove(filmfolder, filmname, scene, shot, take, 'shot')
    922                     organize(filmfolder, filmname)
    923                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    924                     take = counttakes(filmname, filmfolder, scene, shot)
    925                     updatethumb = True
    926                     rendermenu = True
    927                     #loadfilmsettings = True
    928                     time.sleep(0.2)
    929                 #scene
    930                 elif pressed == 'remove' and menu[selected] == 'SCENE:' or pressed=='remove_now':
    931                     remove(filmfolder, filmname, scene, shot, take, 'scene')
    932                     organize(filmfolder, filmname)
    933                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
    934                     shot = countshots(filmname, filmfolder, scene)
    935                     take = counttakes(filmname, filmfolder, scene, shot)
    936                     updatethumb = True
    937                     rendermenu = True
    938                     #loadfilmsettings = True
    939                     time.sleep(0.2)
    940                 #film
    941                 elif pressed == 'remove' and menu[selected] == 'FILM:':
    942                     remove(filmfolder, filmname, scene, shot, take, 'film')
    943                     try:
    944                         filmname = getfilms(filmfolder)[0][0]
    945                     except:
    946                         filmname = 'reel_001'
    947                         if os.path.isdir(filmfolder+filmname) == False:
    948                             os.makedirs(filmfolder+filmname)
    949                     else:
    950                         scene, shot, take = countlast(filmname, filmfolder)
    951                         loadfilmsettings = True
    952                         updatethumb = True
    953                         rendermenu = True
    954                     time.sleep(0.2)
    955                 elif pressed == 'remove' and menu[selected] == 'CAMERA:':
    956                     if camselected != 0:
    957                         cameras.pop(camselected)
    958                         newselected=0
    959                 elif pressed == 'middle' and menu[selected] == 'Add CAMERA':
    960                     if networks != []:
    961                         newcamera = newcamera_ip(numbers_only, network)
    962                         if newcamera != '':
    963                             if newcamera not in cameras and newcamera not in networks:
    964                                 sendtocamera(newcamera,port,'NEWFILM:'+filmname)
    965                                 time.sleep(0.2)
    966                                 sendtocamera(newcamera,port,'Q:'+str(quality))
    967                                 time.sleep(0.2)
    968                                 sendtocamera(newcamera,port,'SHOT:'+str(shot))
    969                                 time.sleep(0.2)
    970                                 sendtocamera(newcamera,port,'SCENE:'+str(scene))
    971                                 time.sleep(0.2)
    972                                 sendtocamera(newcamera,port,'MAKEPLACEHOLDERS:'+str(scenes)+'|'+str(shots))
    973                                 cameras.append(newcamera)
    974                                 rendermenu = True
    975                                 #newselected=newselected+1
    976                                 camera_recording=None
    977                                 vumetermessage("New camera! "+newcamera)
    978                     else:
    979                         vumetermessage('No network!')
    980                 elif 'SYNCIP:' in pressed:
    981                     msg = pressed.split(':')[1]
    982                     syncfolder=msg.split('|')[1]
    983                     ip = msg.split('|')[0]
    984                     synctime= ip.split(';')[1]
    985                     ip = ip.split(';')[0]
    986                     vumetermessage('SYNCING!')
    987                     time.sleep(int(synctime))
    988                     stopinterface(camera)
    989                     video_files=shotfiles(filmfolder, filmname, scene)
    990                     for i in video_files:
    991                         compileshot(i,filmfolder,filmname)
    992                         logger.info('SYNCING:'+i)
    993                     organize(filmfolder, filmname)
    994                     if not os.path.isfile('/home/pi/.ssh/id_rsa'):
    995                         run_command('ssh-keygen')
    996                     run_command('ssh-copy-id pi@'+ip)
    997                     try:
    998                         run_command('rsync -avr --update --progress --files-from='+filmfolder+filmname+'/scene'+str(scene).zfill(3)+'/.origin_videos --no-relative / pi@'+ip+':'+syncfolder+'.videos/')
    999                     except:
   1000                         logger.info('no origin videos')
   1001                     #run_command('scp -r '+filmfolder+filmname+'/'+'scene'+str(scene).zfill(3)+' pi@'+ip+':'+filmfolder+filmname+'/')
   1002                     received=False
   1003                     while received != True:
   1004                         received = sendtocamera(ip,port,'SYNCDONE:'+cameras[0]+'|'+filmfolder)
   1005                         time.sleep(1)
   1006                         logger.info('sending syncdone again...')
   1007                     startinterface()
   1008                     camera = startcamera(lens,fps)
   1009                     loadfilmsettings = True
   1010                     rendermenu = True
   1011                 elif 'SYNCDONE:' in pressed:
   1012                     msg = pressed.split(':')[1]
   1013                     syncfolder=msg.split('|')[1]
   1014                     ip = msg.split('|')[0]
   1015                     sendtocamera(ip,port,'GOTSYNC:'+cameras[0]+'|'+filmfolder)
   1016                     synclist.append(ip)
   1017                     print(synclist)
   1018                     #time.sleep(3)
   1019                     if len(synclist) == len(cameras)-1:
   1020                         for ip in synclist:
   1021                             stopinterface(camera)
   1022                             logger.info('SYNCING from ip:'+ip)
   1023                             run_command('ssh-copy-id pi@'+ip)
   1024                             try:
   1025                                 run_command('rsync -avr --update --progress pi@'+ip+':'+syncfolder+filmname+'/scene'+str(scene).zfill(3)+'/ '+filmfolder+filmname+'/scene'+str(scene).zfill(3)+'/')
   1026                             except:
   1027                                 logger.info('no files')
   1028                             try:
   1029                                 with open(filmfolder+filmname+'/scene'+str(scene).zfill(3)+'/.origin_videos', 'r') as f:
   1030                                     if f:
   1031                                         scene_origin_files = [line.rstrip() for line in f]
   1032                             except:
   1033                                 logger.info('no files')
   1034                             #a=0
   1035                             #for i in cameras:
   1036                             #    if a != 0:
   1037                             #        run_command('rsync -avr --update --progress '+filmfolder+filmname+'/scene'+str(scene).zfill(3)+'/ pi@'+i+':'+filmfolder+filmname+'/scene'+str(scene).zfill(3)+'/')
   1038                             #        time.sleep(3)
   1039                             #    a=a+1
   1040                             startinterface()
   1041                             camera = startcamera(lens,fps)
   1042                             loadfilmsettings = True
   1043                             rendermenu = True
   1044                             vumetermessage('SYNC DONE!')
   1045                 elif 'RETAKE' in pressed:
   1046                     pressed="retake_now"
   1047                 elif 'RETAKE:' in pressed:
   1048                     shot=pressed.split(':')[1]
   1049                     shot=int(shot)
   1050                     retake = True
   1051                     pressed="retake_now"
   1052                 elif 'SCENE:' in pressed:
   1053                     scene=pressed.split(':')[1]
   1054                     scene=int(scene)
   1055                     shot = countshots(filmname, filmfolder, scene)
   1056                     take = counttakes(filmname, filmfolder, scene, shot)
   1057                 elif 'SHOT:' in pressed:
   1058                     shot=pressed.split(':')[1]
   1059                     shot=int(shot)
   1060                     take = counttakes(filmname, filmfolder, scene, shot)
   1061                 elif 'REMOVE:' in pressed:
   1062                     scene=pressed.split(':')[1]
   1063                     scene=int(scene)
   1064                     shot = countshots(filmname, filmfolder, scene)
   1065                     take = counttakes(filmname, filmfolder, scene, shot)
   1066                     pressagain='remove_now'
   1067                 elif 'Q:' in pressed:
   1068                     qual=pressed.split(':')[1]
   1069                     quality=int(qual)
   1070                     vumetermessage('Quality changed to '+str(quality))
   1071                 elif 'CAMERA:' in pressed:
   1072                     newselected_maybe=int(pressed.split(':')[1])
   1073                     if len(cameras) > newselected_maybe:
   1074                         newselected=newselected_maybe
   1075                 elif 'MAKEPLACEHOLDERS:' in pressed:
   1076                     scenesshots=pressed.split(':')[1]
   1077                     pscene=int(scenesshots.split('|')[0])
   1078                     pshots=int(scenesshots.split('|')[1])
   1079                     #to not throw away empty shots, make placeholders
   1080                     for i in range(pshots):
   1081                         placeholders=filmfolder + filmname + '/scene' +  str(pscene).zfill(3) + '/shot' + str(i+1).zfill(3)
   1082                         try:
   1083                             os.makedirs(placeholders)
   1084                         except:
   1085                             logger.info('scene or shot already there!')
   1086                         run_command('touch ' + placeholders + '/.placeholder')
   1087                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take) 
   1088                     rendermenu = True
   1089                     vumetermessage('CONNECTED TO MASTER TARINA!')
   1090             #SHOWTARINACTRL
   1091             if recordwithports: 
   1092                 if pressed == 'middle' and menu[selected] == "New FILM":
   1093                     newfilmname = nameyourfilm(filmfolder, filmname, abc, True)
   1094                     a=0
   1095                     for i in cameras:
   1096                         if i not in camerasoff:
   1097                             sendtocamera(i,port,'NEWFILM:'+newfilmname)
   1098                         a=a+1
   1099                 elif pressed == "retake":
   1100                     a=0
   1101                     for i in cameras:
   1102                         if i not in camerasoff:
   1103                             if a == camselected:
   1104                                 if camera_recording == a:
   1105                                     if a==0:
   1106                                         if recording == True:
   1107                                             pressed="retake_now"
   1108                                             retake = True
   1109                                             camera_recording=None
   1110                                     else:
   1111                                         sendtocamera(i,port,'STOPRETAKE')
   1112                                     camera_recording=None
   1113                                 else:
   1114                                     if a==0:
   1115                                         if recording == False:
   1116                                             pressed="retake_now"
   1117                                             retake = True
   1118                                             camera_recording=0
   1119                                     else:
   1120                                         sendtocamera(i,port,'RETAKE:'+str(shot))
   1121                                         camera_recording=camselected
   1122                             else:
   1123                                 if a==0:
   1124                                     pressagain='insert_take'
   1125                                 else:
   1126                                     sendtocamera(i,port,'TAKEPLACEHOLDER')
   1127                             a=a+1
   1128                 elif pressed == "middle" and menu[selected]=="Sync SCENE":
   1129                     n=1
   1130                     for i in cameras:
   1131                         if i != cameras[0]:
   1132                             vumetermessage('Hold on syncing!')
   1133                             sendtocamera(i,port,'SYNCIP:'+cameras[0]+';'+str(n)+'|'+filmfolder)
   1134                             synclist=[]
   1135                             n=n+1
   1136                             #time.sleep(1)
   1137                 elif pressed == "middle" and menu[selected]=='New SCENE':
   1138                     a=0
   1139                     for i in cameras:
   1140                         if i not in camerasoff:
   1141                             if a==0:
   1142                                 pressagain="new_scene"
   1143                             else:
   1144                                 sendtocamera(i,port,'NEWSCENE')
   1145                         a=a+1
   1146                 elif pressed == "record" and camera_recording != None:
   1147                     if camera_recording == 0:
   1148                         if recording == True:
   1149                             pressed='record_now'
   1150                     else:
   1151                         sendtocamera(cameras[camera_recording],port,'STOP')
   1152                     camera_recording=None
   1153                 elif pressed == "record" and camera_recording == None:
   1154                     a=0
   1155                     for i in cameras:
   1156                         if i not in camerasoff:
   1157                             if a == camselected:
   1158                                 if camselected==0:
   1159                                     pressed='record_now'
   1160                                 else:
   1161                                     sendtocamera(i,port,'REC')
   1162                                 camera_recording=camselected
   1163                             else:
   1164                                 if a==0:
   1165                                     pressagain='insert_shot'
   1166                                 else:
   1167                                     sendtocamera(i,port,'PLACEHOLDER')
   1168                             a=a+1
   1169                 elif pressed == "remove" and menu[selected]=='SCENE:':
   1170                     a=0
   1171                     for i in cameras:
   1172                         if a!=0:
   1173                             sendtocamera(i,port,'REMOVE:'+str(scene))
   1174                         a=a+1
   1175                 elif pressed == "up" and menu[selected]=='SCENE:':
   1176                     a=0
   1177                     for i in cameras:
   1178                         if a!=0:
   1179                             sendtocamera(i,port,'SCENE:'+str(scene+1))
   1180                         a=a+1
   1181                 elif pressed == "down" and menu[selected]=='SCENE:':
   1182                     a=0
   1183                     for i in cameras:
   1184                         if a!=0:
   1185                             sendtocamera(i,port,'SCENE:'+str(scene-1))
   1186                         a=a+1
   1187                 elif pressed == "up" and menu[selected]=='SHOT:':
   1188                     a=0
   1189                     for i in cameras:
   1190                         if a!=0:
   1191                             sendtocamera(i,port,'SHOT:'+str(shot+1))
   1192                         a=a+1
   1193                 elif pressed == "down" and menu[selected]=='SHOT:':
   1194                     a=0
   1195                     for i in cameras:
   1196                         if a!=0:
   1197                             sendtocamera(i,port,'SHOT:'+str(shot-1))
   1198                         a=a+1
   1199                 elif pressed == "up" and menu[selected]=='Q:':
   1200                     a=0
   1201                     for i in cameras:
   1202                         if a!=0:
   1203                             sendtocamera(i,port,'Q:'+str(quality+1))
   1204                         a=a+1
   1205                 elif pressed == "down" and menu[selected]=='Q:':
   1206                     a=0
   1207                     for i in cameras:
   1208                         if a!=0:
   1209                             sendtocamera(i,port,'Q:'+str(quality-1))
   1210                         a=a+1
   1211                 elif event == "0":
   1212                     newselected = 0
   1213                 elif event == "1":
   1214                     if len(cameras) > 0:
   1215                         newselected = 0
   1216                 elif event == "2":
   1217                     if len(cameras) > 1:
   1218                         newselected = 1
   1219                 elif event == "3":
   1220                     if len(cameras) > 2:
   1221                         newselected = 2
   1222                 elif event == "4":
   1223                     if len(cameras) > 3:
   1224                         newselected = 3
   1225                 elif event == "5":
   1226                     if len(cameras) > 4:
   1227                         newselected = 4
   1228                 elif event == "6":
   1229                     if len(cameras) > 5:
   1230                         newselected = 5
   1231                 elif event == "7":
   1232                     if len(cameras) > 6:
   1233                         newselected = 6
   1234                 elif event == "8":
   1235                     if len(cameras) > 7:
   1236                         newselected = 7
   1237                 elif event == "9":
   1238                     if len(cameras) > 8:
   1239                         newselected = 8
   1240                 elif event == "-":
   1241                     if cameras[camselected] not in camerasoff:
   1242                         camerasoff.append(cameras[camselected])
   1243                 elif event == "+":
   1244                     if cameras[camselected] in camerasoff:
   1245                         camerasoff.remove(cameras[camselected])
   1246                 elif camselected != newselected:
   1247                     if camera_recording != None:
   1248                         #change camera
   1249                         a=0
   1250                         for c in cameras:
   1251                             if c not in camerasoff:
   1252                                 if a == camselected:
   1253                                     if a == 0:
   1254                                         #pressed='record_now'
   1255                                         #pressagain='insert_shot'
   1256                                         delayedstop=c
   1257                                     else:
   1258                                         #sendtocamera(c,port,'STOP')
   1259                                         #time.sleep(sleep)
   1260                                         #sendtocamera(c,port,'PLACEHOLDER')
   1261                                         delayedstop=c
   1262                                 elif a == newselected:
   1263                                     if a == 0:
   1264                                         if recording == False:
   1265                                             pressed='record_now'
   1266                                     else:
   1267                                         sendtocamera(c,port,'REC')
   1268                                     camera_recording=newselected
   1269                                 else:
   1270                                     if a == 0:
   1271                                         pressagain='insert_shot'
   1272                                     else:
   1273                                         sendtocamera(c,port,'PLACEHOLDER')
   1274                                     #time.sleep(2)
   1275                                 a=a+1
   1276                         if delayedstop:
   1277                             time.sleep(0.05)
   1278                             if delayedstop==cameras[0]:
   1279                                 if recording == True:
   1280                                     pressed='record_now'
   1281                                 pressagain='insert_shot'
   1282                             else:
   1283                                 sendtocamera(delayedstop,port,'STOP')
   1284                                 time.sleep(sleep)
   1285                                 sendtocamera(delayedstop,port,'PLACEHOLDER')
   1286                     camselected=newselected
   1287                     rendermenu = True
   1288                     #vumetermessage('filming with '+camera_model +' ip:'+ network + ' '+camerasconnected+' camselected:'+str(camselected))
   1289                     if len(cameras) > 0:
   1290                         if camera_recording:
   1291                             vumetermessage('filming with '+camera_model +' ip:'+ cameras[camselected] + ' '+camerasconnected+' camselected:'+str(camselected+1)+' rec:'+str(camera_recording+1))
   1292                         else:
   1293                             vumetermessage('filming with '+camera_model +' ip:'+ cameras[camselected] + ' '+camerasconnected+' camselected:'+str(camselected+1)+' rec:'+str(camera_recording))
   1294                     else:
   1295                         vumetermessage('filming with '+camera_model +' ip:'+ network)
   1296 
   1297 
   1298             #RECORD AND PAUSE
   1299             if beepcountdown > 1:
   1300                 if time.time() - lastbeep  > 1:
   1301                     beep(bus)
   1302                     beepcountdown -= 1
   1303                     lastbeep = time.time()
   1304                     logger.info('beepcountdown: ' + str(beepcountdown))
   1305                     vumetermessage('Filming in ' + str(beepcountdown) + ' seconds, press record again to cancel       ')
   1306             elif beepcountdown > 0:
   1307                 if time.time() - float(lastbeep) > 0.1:
   1308                     beep(bus)
   1309                     vumetermessage('Get ready!!')
   1310                 if time.time() - lastbeep > 1:
   1311                     longbeep(bus)
   1312                     beepcountdown = 0
   1313                     if recordwithports == True:
   1314                         if retake == True:
   1315                             pressed = 'retake_now'
   1316                             retake = False
   1317                         else:
   1318                             pressed = 'record_now'
   1319                     else:
   1320                         pressed = 'record'
   1321                     print('exhausted from all beepings')
   1322             elif 'CAMERA:' in pressed:
   1323                 newselected_maybe=int(pressed.split(':')[1])
   1324                 if len(cameras) > newselected_maybe:
   1325                     newselected=newselected_maybe
   1326             if pressed == 'record' and recordwithports==False or pressed == 'record_now' or pressed == 'retake_now' or pressed == 'retake' and recordwithports==False or reclenght != 0 and t > reclenght:
   1327                 overlay = removeimage(camera, overlay)
   1328                 if recording == False and recordable == True or recording == False and pressed == 'record_now' or recording == False and pressed == 'retake_now':
   1329                     #camera_recording=0
   1330                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take) 
   1331                     if pressed == "record":
   1332                         #shot = shots+1
   1333                         take = takes+1
   1334                     elif pressed == "retake":
   1335                         take = takes+1
   1336                     elif pressed == 'record_now':
   1337                         shot=shots+1
   1338                         take=1
   1339                     elif pressed == 'retake_now':
   1340                         takes = counttakes(filmname, filmfolder, scene, shot)
   1341                         take = takes + 1
   1342                     foldername = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3) + '/'
   1343                     filename = 'take' + str(take).zfill(3)
   1344                     if beeps > 0 and beeping == False:
   1345                         beeping = True
   1346                         beepcountdown = beeps
   1347                     elif beepcountdown == 0:
   1348                         beeping = False
   1349                         if os.path.isdir(foldername) == False:
   1350                             os.makedirs(foldername)
   1351                         if cammode == 'film':
   1352                             videos_totalt = db.query("SELECT COUNT(*) AS videos FROM videos")[0]
   1353                             tot = int(videos_totalt.videos)
   1354                             video_origins=datetime.datetime.now().strftime('%Y%d%m')+str(tot).zfill(5)+'_'+os.urandom(8).hex()
   1355                             db.insert('videos', tid=datetime.datetime.now(), filename=filmfolder+'.videos/'+video_origins+'.mp4', foldername=foldername, filmname=filmname, scene=scene, shot=shot, take=take, audiolenght=0, videolenght=0)
   1356                             os.system(gonzopifolder + '/alsa-utils-1.1.3/aplay/arecord -D hw:' + str(plughw) + ' -f '+soundformat+' -c ' + str(channels) + ' -r '+soundrate+' -vv '+ foldername + filename + '.wav &')
   1357                             sound_start = time.time()
   1358                             if onlysound != True:
   1359                                 camera.start_recording(filmfolder+ '.videos/'+video_origins+'.h264', format='h264', bitrate = 5555555, level=profilelevel, quality=quality)
   1360                                 starttime = time.time()
   1361                             os.system('ln -sfr '+filmfolder+'.videos/'+video_origins+'.h264 '+foldername+filename+'.h264')
   1362                             recording = True
   1363                             showmenu = 0
   1364                         if cammode == 'picture':
   1365                             #picdate=datetime.datetime.now().strftime('%Y%d%m')
   1366                             picture = foldername +'picture' + str(take).zfill(3) + '.jpeg'
   1367                             print('taking picture')
   1368                             camera.capture(picture,format="jpeg",use_video_port=True) 
   1369                             run_command('touch ' + foldername + 'take' + str(take).zfill(3) + '.mp4')
   1370                             basewidth = 800
   1371                             img = Image.open(picture)
   1372                             wpercent = (basewidth/float(img.size[0]))
   1373                             hsize = int((float(img.size[1])*float(wpercent)))
   1374                             img = img.resize((basewidth,hsize), Image.ANTIALIAS)
   1375                             img.save(foldername+'take'+str(take).zfill(3) + '.jpeg')
   1376                             vumetermessage('Great Pic taken!!')
   1377                             updatethumb = True
   1378                     elif beepcountdown > 0 and beeping == True:
   1379                         beeping = False
   1380                         beepcountdown = 0
   1381                         vumetermessage('Filming was canceled!!')
   1382                 elif recording == True and float(time.time() - starttime) > 0.2:
   1383                     #print(term.clear+term.home)
   1384                     disk = os.statvfs(filmfolder)
   1385                     diskleft = str(int(disk.f_bavail * disk.f_frsize / 1024 / 1024 / 1024)) + 'Gb'
   1386                     recording = False
   1387                     if showmenu_settings == True:
   1388                         showmenu = 1
   1389                     if onlysound != True:
   1390                         camera.stop_recording()
   1391                     os.system('pkill arecord')
   1392                     soundlag=starttime-sound_start
   1393                     db.update('videos', where='filename="'+filmfolder+'.videos/'+video_origins+'.mp4"', soundlag=soundlag)
   1394                     #time.sleep(0.005) #get audio at least 0.1 longer
   1395                     #camera.capture(foldername + filename + '.jpeg', resize=(800,341))
   1396                     if onlysound != True:
   1397                         try:
   1398                             #camera.capture(foldername + filename + '.jpeg', resize=(800,340), use_video_port=True)
   1399                             camera.capture(foldername + filename + '.jpeg', resize=(800,450), use_video_port=True)
   1400                         except:
   1401                             logger.warning('something wrong with camera jpeg capture')
   1402                     #delayerr = audiotrim(foldername,filename)
   1403                     onlysound = False
   1404                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
   1405                     if beeps > 0:
   1406                         if bus:
   1407                             buzz(300)
   1408                         else:
   1409                             run_command('aplay -D plughw:' + str(plughw) + ' '+ gonzopifolder + '/extras/beep.wav')
   1410                     if round(fps) != 25:
   1411                         compileshot(foldername + filename,filmfolder,filmname)
   1412                     #os.system('cp /dev/shm/' + filename + '.wav ' + foldername + filename + '.wav')
   1413                     if beeps > 0:
   1414                         if bus:
   1415                             buzz(150)
   1416                         else:
   1417                             run_command('aplay -D plughw:' + str(plughw) + ' '+ gonzopifolder + '/extras/beep.wav')
   1418                     t = 0
   1419                     rectime = ''
   1420                     vumetermessage('Gonzopi ' + gonzopiversion[:-1] + ' ' + gonzopivername[:-1])
   1421                     updatethumb = True
   1422                     #camera_recording=0
   1423                 #if not in last shot or take then go to it
   1424                 if pressed == 'record' and recordable == False:
   1425                     scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
   1426                     shot=shots+1
   1427                     take=1
   1428                     #take = takes
   1429                     #takes = counttakes(filmname, filmfolder, scene, shot)
   1430                 if pressed == 'retake' and recordable == False:
   1431                     #scenes, shots, takes = browse(filmname,filmfolder,scene,shot,take)
   1432                     takes = counttakes(filmname, filmfolder, scene, shot)
   1433                     #take = takes
   1434                     #takes = counttakes(filmname, filmfolder, scene, shot)
   1435                     take = takes + 1
   1436             #ENTER (auto shutter, iso, awb on/off)
   1437             elif pressed == 'middle' and menu[selected] == 'SHUTTER:':
   1438                 if camera.shutter_speed == 0:
   1439                     camera.shutter_speed = camera.exposure_speed
   1440                 else:
   1441                     camera.shutter_speed = 0
   1442             elif pressed == 'middle' and menu[selected] == 'ISO:':
   1443                 if camera.iso == 0:
   1444                     camera.iso = 100
   1445                 else:
   1446                     camera.iso = 0
   1447             elif pressed == 'middle' and menu[selected] == 'RED:':
   1448                 if camera.awb_mode == 'auto':
   1449                     camera.awb_gains = (float(camera.awb_gains[0]), float(camera.awb_gains[1]))
   1450                     camera.awb_mode = 'off'
   1451                 else:
   1452                     camera.awb_mode = 'auto'
   1453             elif pressed == 'middle' and menu[selected] == 'BLUE:':
   1454                 if camera.awb_mode == 'auto':
   1455                     camera.awb_gains = (float(camera.awb_gains[0]), float(camera.awb_gains[1]))
   1456                     camera.awb_mode = 'off'
   1457                 else:
   1458                     camera.awb_mode = 'auto'
   1459             elif pressed == 'middle' and menu[selected] == 'BEEP:':
   1460                 beeps = 0
   1461             elif pressed == 'middle' and menu[selected] == 'LENGTH:':
   1462                 reclenght = 0
   1463             elif pressed == 'middle' and menu[selected] == 'LIVE:':
   1464                 if stream == '':
   1465                     stream = startstream(camera, stream, plughw, channels,network)
   1466                     if stream == '':
   1467                         vumetermessage('something wrong with streaming')
   1468                     else:
   1469                         live = 'yes'
   1470                 else:
   1471                     stream = stopstream(camera, stream)
   1472                     live = 'no'
   1473             elif pressed == 'middle' and menu[selected] == 'BRIGHT:':
   1474                 camera.brightness = 50
   1475             elif pressed == 'middle' and menu[selected] == 'CONT:':
   1476                 camera.contrast = 0
   1477             elif pressed == 'middle' and menu[selected] == 'SAT:':
   1478                 camera.saturation = 0
   1479             elif pressed == 'middle' and menu[selected] == 'MIC:':
   1480                 miclevel  = 70
   1481             elif pressed == 'middle' and menu[selected] == 'PHONES:':
   1482                 headphoneslevel = 70
   1483             elif pressed == 'middle' and menu[selected] == 'SRV:':
   1484                 if showgonzopictrl == False:
   1485                     menu=gonzopictrlmenu
   1486                     #selected=0
   1487                     showgonzopictrl = True
   1488                 else:
   1489                     menu=standardmenu
   1490                     showgonzopictrl=False
   1491 
   1492             #UP
   1493             elif pressed == 'up':
   1494                 if menu[selected] == 'FILM:':
   1495                     filmname = loadfilm(filmname, filmfolder, camera, overlay)
   1496                     loadfilmsettings = True
   1497                 if menu[selected] == 'BRIGHT:':
   1498                     camera.brightness = min(camera.brightness + 1, 99)
   1499                 elif menu[selected] == 'CONT:':
   1500                     camera.contrast = min(camera.contrast + 1, 99)
   1501                 elif menu[selected] == 'SAT:':
   1502                     camera.saturation = min(camera.saturation + 1, 99)
   1503                 elif menu[selected] == 'SFX:':
   1504                     if effectselected < len(effects) - 1:
   1505                         effectselected += 1
   1506                         camera.image_effect = effects[effectselected]
   1507                 elif menu[selected] == 'SHUTTER:':
   1508                     if camera.shutter_speed == 0:
   1509                         camera.shutter_speed = camera.exposure_speed
   1510                     if camera.shutter_speed < 5000:
   1511                         camera.shutter_speed = min(camera.shutter_speed + 50, 50000)
   1512                     else:
   1513                         camera.shutter_speed = min(camera.shutter_speed + 200, 50000)
   1514                 elif menu[selected] == 'ISO:':
   1515                     camera.iso = min(camera.iso + 100, 1600)
   1516                 elif menu[selected] == 'BEEP:':
   1517                     beeps = beeps + 1
   1518                 elif menu[selected] == 'FLIP:':
   1519                     if flip == 'yes':
   1520                         camera.hflip = False
   1521                         camera.vflip = False
   1522                         flip = 'no'
   1523                         time.sleep(0.2)
   1524                     else:
   1525                         camera.hflip = True
   1526                         camera.vflip = True
   1527                         flip = 'yes'
   1528                         time.sleep(0.2)
   1529                 elif menu[selected] == 'LENGTH:':
   1530                     if reclenght < 1:
   1531                         reclenght = reclenght + 0.2
   1532                     else:
   1533                         reclenght = int(reclenght + 1)
   1534                     time.sleep(0.1)
   1535                 elif menu[selected] == 'MIC:':
   1536                     if miclevel < 100:
   1537                         miclevel = miclevel + 2
   1538                         run_command('amixer -c 0 sset Mic ' + str(miclevel) + '% unmute')
   1539                 elif menu[selected] == 'PHONES:':
   1540                     if headphoneslevel < 100:
   1541                         headphoneslevel = headphoneslevel + 2
   1542                         run_command('amixer -c 0 sset Speaker ' + str(headphoneslevel) + '%')
   1543                 elif menu[selected] == 'SCENE:' and recording == False:
   1544                     if scene <= scenes:
   1545                         scene += 1
   1546                         #shot = countshots(filmname, filmfolder, scene)
   1547                         shot = 1
   1548                         take = counttakes(filmname, filmfolder, scene, shot)
   1549                     #scene, shots, takes = browse2(filmname, filmfolder, scene, shot, take, 0, 1)
   1550                     #shot = 1
   1551                 elif menu[selected] == 'SHOT:' and recording == False:
   1552                     if shot <= shots:
   1553                         shot += 1
   1554                         take = counttakes(filmname, filmfolder, scene, shot)
   1555                     #scene, shot, take = browse2(filmname, filmfolder, scene, shot, take, 1, 1)
   1556                     #takes = take
   1557                 elif menu[selected] == 'TAKE:' and recording == False:
   1558                     if take <= takes:
   1559                         take += 1
   1560                     #scene, shot, take = browse2(filmname, filmfolder, scene, shot, take, 2, 1)
   1561                 elif menu[selected] == 'RED:':
   1562                     camera.awb_mode = 'off'
   1563                     if float(camera.awb_gains[0]) < 7.98:
   1564                         camera.awb_gains = (round(camera.awb_gains[0],2) + 0.02, round(camera.awb_gains[1],2))
   1565                 elif menu[selected] == 'BLUE:':
   1566                     camera.awb_mode = 'off'
   1567                     if float(camera.awb_gains[1]) < 7.98:
   1568                         camera.awb_gains = (round(camera.awb_gains[0],2), round(camera.awb_gains[1],2) + 0.02)
   1569                 elif menu[selected] == 'SRV:':
   1570                     if serverstate == 'on':
   1571                         try:
   1572                             os.makedirs(gonzopifolder+'/srv/sessions')
   1573                             os.system('chown www-data '+gonzopifolder+'/srv/sessions')
   1574                         except:
   1575                             print('srv folder exist')
   1576                         serverstate = 'false'
   1577                         serverstate = gonzopiserver(False)
   1578                     elif serverstate == 'off':
   1579                         serverstate = 'on'
   1580                         serverstate = gonzopiserver(True)
   1581                 elif menu[selected] == 'WIFI:':
   1582                     if wifistate == 'on':
   1583                         run_command('sudo iwconfig wlan0 txpower off')
   1584                         wifistate = 'off'
   1585                     elif wifistate == 'off':
   1586                         run_command('sudo iwconfig wlan0 txpower auto')
   1587                         wifistate = 'on'
   1588                 elif menu[selected] == 'SEARCH:':
   1589                     if searchforcameras == 'on':
   1590                         searchforcameras = 'off'
   1591                     elif searchforcameras == 'off':
   1592                         searchforcameras = 'on'
   1593                 elif menu[selected] == 'MODE:':
   1594                     if cammode == 'film':
   1595                         cammode = 'picture'
   1596                         vumetermessage('changing to picture mode')
   1597                     elif cammode == 'picture':
   1598                         cammode = 'film'
   1599                         vumetermessage('changing to film mode')
   1600                     camera.stop_preview()
   1601                     camera.close()
   1602                     camera = startcamera(lens,fps)
   1603                     loadfilmsettings = True
   1604                     flushbutton()
   1605                 elif menu[selected] == 'LENS:':
   1606                     s = 0
   1607                     for a in lenses:
   1608                         if a == lens:
   1609                             selectlens = s
   1610                         s += 1
   1611                     if selectlens < len(lenses) - 1:
   1612                         selectlens += 1
   1613                     lens = os.listdir('lenses/')[selectlens]
   1614                     #npzfile = np.load('lenses/' + lens)
   1615                     #lensshade = npzfile['lens_shading_table']
   1616                     table = read_table('lenses/' + lens)
   1617                     camera.lens_shading_table = table
   1618                 elif menu[selected] == 'COMP:':
   1619                     if comp < 1:
   1620                         comp += 1
   1621                 elif menu[selected] == 'HW:':
   1622                     if plughw < len(getaudiocards())-1:
   1623                         plughw += 1
   1624                     vumetermessage(getaudiocards()[plughw])
   1625                 elif menu[selected] == 'CH:':
   1626                     if channels == 1:
   1627                         channels = 2
   1628                 elif menu[selected] == 'FPS:':
   1629                     if fps_selected < len(fps_selection)-1:
   1630                         fps_selected+=1
   1631                         fps=fps_selection[fps_selected]
   1632                         camera.framerate = fps
   1633                 elif menu[selected] == 'Q:':
   1634                     if scenes == 0:
   1635                         if quality < 39:
   1636                             quality += 1
   1637                 elif menu[selected] == 'CAMERA:':
   1638                     if camselected < len(cameras)-1:
   1639                         newselected = camselected+1
   1640                         logger.info('camera selected:'+str(camselected))
   1641                 elif menu[selected] == 'DSK:':
   1642                     if dsk+1 < len(storagedrives):
   1643                         dsk += 1
   1644                         filmfolder = storagedrives[dsk][1]
   1645                         loadfilmsettings = True
   1646                         #COUNT DISKSPACE
   1647                         disk = os.statvfs(filmfolder)
   1648                         diskleft = str(int(disk.f_bavail * disk.f_frsize / 1024 / 1024 / 1024)) + 'Gb'
   1649                         #LOAD FILM AND SCENE SETTINGS
   1650                         try:
   1651                             filmname = getfilms(filmfolder)[0][0]
   1652                         except:
   1653                             filmname = filmname 
   1654                         try:
   1655                             filmname_back = getfilms(filmfolder)[0][1]
   1656                         except:
   1657                             filmname_back = filmname
   1658                         if serverstate == 'on':
   1659                             gonzopiserver(False)
   1660                             gonzopiserver(True)
   1661 
   1662             #LEFT
   1663             elif pressed == 'left':
   1664                 if selected > 0:
   1665                     selected = selected - 1
   1666                 else:
   1667                     selected = len(menu) - 1
   1668                 if selected == 5:
   1669                     selected = 4
   1670             #DOWN
   1671             elif pressed == 'down':
   1672                 if menu[selected] == 'FILM:':
   1673                     filmname = loadfilm(filmname, filmfolder, camera, overlay)
   1674                     loadfilmsettings = True
   1675                 elif menu[selected] == 'BRIGHT:':
   1676                     camera.brightness = max(camera.brightness - 1, 0)
   1677                 elif menu[selected] == 'CONT:':
   1678                     camera.contrast = max(camera.contrast - 1, -100)
   1679                 elif menu[selected] == 'SAT:':
   1680                     camera.saturation = max(camera.saturation - 1, -100)
   1681                 elif menu[selected] == 'SFX:':
   1682                     if effectselected > 0:
   1683                         effectselected -= 1
   1684                         camera.image_effect = effects[effectselected]
   1685                 elif menu[selected] == 'SHUTTER:':
   1686                     if camera.shutter_speed == 0:
   1687                         camera.shutter_speed = camera.exposure_speed
   1688                     if camera.shutter_speed < 5000:
   1689                         camera.shutter_speed = max(camera.shutter_speed - 50, 20)
   1690                     else:
   1691                         camera.shutter_speed = max(camera.shutter_speed - 200, 200)
   1692                 elif menu[selected] == 'ISO:':
   1693                     camera.iso = max(camera.iso - 100, 100)
   1694                 elif menu[selected] == 'BEEP:':
   1695                     if beeps > 0:
   1696                         beeps = beeps - 1
   1697                 elif menu[selected] == 'FLIP:':
   1698                     if flip == 'yes':
   1699                         camera.hflip = False
   1700                         camera.vflip = False
   1701                         flip = 'no'
   1702                         time.sleep(0.2)
   1703                     else:
   1704                         camera.hflip = True
   1705                         camera.vflip = True
   1706                         flip = 'yes'
   1707                         time.sleep(0.2)
   1708                 elif menu[selected] == 'LENGTH:':
   1709                     if reclenght > 1:
   1710                         reclenght = int(reclenght - 1)
   1711                         time.sleep(0.1)
   1712                     elif reclenght > 0.3:
   1713                         reclenght = reclenght - 0.2
   1714                         time.sleep(0.1)
   1715                     else:
   1716                         reclenght = 0
   1717                 elif menu[selected] == 'MIC:':
   1718                     if miclevel > 0:
   1719                         miclevel = miclevel - 2
   1720                         run_command('amixer -c 0 sset Mic ' + str(miclevel) + '% unmute')
   1721                 elif menu[selected] == 'PHONES:':
   1722                     if headphoneslevel > 0:
   1723                         headphoneslevel = headphoneslevel - 2
   1724                         run_command('amixer -c 0 sset Speaker ' + str(headphoneslevel) + '%')
   1725                 elif menu[selected] == 'SCENE:' and recording == False:
   1726                     if scene > 1:
   1727                         scene -= 1
   1728                         #shot = countshots(filmname, filmfolder, scene)
   1729                         shot=1
   1730                         take = counttakes(filmname, filmfolder, scene, shot)
   1731                     #scene, shots, take = browse2(filmname, filmfolder, scene, shot, take, 0, -1)
   1732                     #takes = take
   1733                     #shot = 1
   1734                 elif menu[selected] == 'SHOT:' and recording == False:
   1735                     if shot > 1:
   1736                         shot -= 1
   1737                         take = counttakes(filmname, filmfolder, scene, shot)
   1738                     #scene, shot, take = browse2(filmname, filmfolder, scene, shot, take, 1, -1)
   1739                     #takes = take
   1740                 elif menu[selected] == 'TAKE:' and recording == False:
   1741                     if take > 1:
   1742                         take -= 1
   1743                     #scene, shot, take = browse2(filmname, filmfolder, scene, shot, take, 2, -1)
   1744                 elif menu[selected] == 'RED:':
   1745                     camera.awb_mode = 'off'
   1746                     if float(camera.awb_gains[0]) > 0.02:
   1747                         camera.awb_gains = (round(camera.awb_gains[0],2) - 0.02, round(camera.awb_gains[1],2))
   1748                 elif menu[selected] == 'BLUE:':
   1749                     camera.awb_mode = 'off'
   1750                     if float(camera.awb_gains[1]) > 0.02:
   1751                         camera.awb_gains = (round(camera.awb_gains[0],2), round(camera.awb_gains[1],2) - 0.02)
   1752                 elif menu[selected] == 'SRV:':
   1753                     if serverstate == 'on':
   1754                         try:
   1755                             os.makedirs(gonzopifolder+'/srv/sessions')
   1756                             os.system('chown www-data '+gonzopifolder+'/srv/sessions')
   1757                         except:
   1758                             print('srv folder exist')
   1759                         serverstate = gonzopiserver(False)
   1760                     elif serverstate == 'off':
   1761                         serverstate = gonzopiserver(True)
   1762                 elif menu[selected] == 'WIFI:':
   1763                     if wifistate == 'on':
   1764                         run_command('sudo iwconfig wlan0 txpower off')
   1765                         wifistate = 'off'
   1766                     elif wifistate == 'off':
   1767                         run_command('sudo iwconfig wlan0 txpower auto')
   1768                         wifistate = 'on'
   1769                 elif menu[selected] == 'SEARCH:':
   1770                     if searchforcameras == 'on':
   1771                         searchforcameras = 'off'
   1772                     elif searchforcameras == 'off':
   1773                         seaarchforcameras = 'on'
   1774                 elif menu[selected] == 'MODE:':
   1775                     if cammode == 'film':
   1776                         cammode = 'picture'
   1777                         vumetermessage('changing to picture mode')
   1778                     elif cammode == 'picture':
   1779                         cammode = 'film'
   1780                         vumetermessage('changing to film mode')
   1781                     camera.stop_preview()
   1782                     camera.close()
   1783                     camera = startcamera(lens,fps)
   1784                     loadfilmsettings = True
   1785                     flushbutton()
   1786                 elif menu[selected] == 'LENS:':
   1787                     s = 0
   1788                     for a in lenses:
   1789                         if a == lens:
   1790                             selectlens = s
   1791                         s += 1
   1792                     if selectlens > 0:
   1793                         selectlens -= 1
   1794                     lens = os.listdir('lenses/')[selectlens]
   1795                     #npzfile = np.load('lenses/' + lens)
   1796                     #lensshade = npzfile['lens_shading_table']
   1797                     table = read_table('lenses/' + lens)
   1798                     camera.lens_shading_table = table
   1799                 elif menu[selected] == 'DUB:':
   1800                     if round(dub[0],1) == 1.0 and round(dub[1],1) > 0.0:
   1801                         dub[1] -= 0.1
   1802                     if round(dub[1],1) == 1.0 and round(dub[0],1) < 1.0:
   1803                         dub[0] += 0.1
   1804                 elif menu[selected] == 'COMP:':
   1805                     if comp > 0:
   1806                         comp -= 1
   1807                 elif menu[selected] == 'HW:':
   1808                     if plughw > 0:
   1809                         plughw -= 1
   1810                     vumetermessage(getaudiocards()[plughw])
   1811                 elif menu[selected] == 'CH:':
   1812                     if channels == 2:
   1813                         channels = 1
   1814                 elif menu[selected] == 'FPS:':
   1815                     if fps_selected > 0:
   1816                         fps_selected-=1
   1817                         fps=fps_selection[fps_selected]
   1818                         camera.framerate = fps
   1819                 elif menu[selected] == 'Q:':
   1820                     if scenes == 0:
   1821                         if quality > 10:
   1822                             quality -= 1
   1823                 elif menu[selected] == 'CAMERA:':
   1824                     if camselected > 0:
   1825                         newselected = camselected-1
   1826                         logger.info('camera selected:'+str(camselected))
   1827                 elif menu[selected] == 'DSK:':
   1828                     if dsk > 0:
   1829                         dsk -= 1
   1830                         filmfolder = storagedrives[dsk][1]
   1831                         loadfilmsettings = True
   1832                         #COUNT DISKSPACE
   1833                         disk = os.statvfs(filmfolder)
   1834                         diskleft = str(int(disk.f_bavail * disk.f_frsize / 1024 / 1024 / 1024)) + 'Gb'
   1835                         #LOAD FILM AND SCENE SETTINGS
   1836                         try:
   1837                             filmname = getfilms(filmfolder)[0][0]
   1838                         except:
   1839                             filmname = filmname 
   1840                         try:
   1841                             filmname_back = getfilms(filmfolder)[0][1]
   1842                         except:
   1843                             filmname_back = filmname 
   1844                         if serverstate == 'on':
   1845                             gonzopiserver(False)
   1846                             gonzopiserver(True)
   1847 
   1848             #RIGHT
   1849             elif pressed == 'right':
   1850                 if selected < len(menu) - 1:
   1851                     selected = selected + 1
   1852                 else:
   1853                     selected = 0
   1854                 if selected == 5: #jump over recording time
   1855                     selected = 6
   1856             #Start Recording Time
   1857             if recording == True:
   1858                 t = time.time() - starttime
   1859                 rectime = time.strftime("%H:%M:%S", time.gmtime(t))
   1860             #Load settings
   1861             if loadfilmsettings == True:
   1862                 db = get_film_files(filmname,filmfolder,db)
   1863                 try:
   1864                     filmsettings = loadsettings(filmfolder, filmname)
   1865                     camera.brightness = filmsettings[2]
   1866                     camera.contrast = filmsettings[3]
   1867                     camera.saturation = filmsettings[4]
   1868                     camera.shutter_speed = filmsettings[5]
   1869                     camera.iso = filmsettings[6]
   1870                     camera.awb_mode = filmsettings[7]
   1871                     camera.awb_gains = filmsettings[8]
   1872                     awb_lock = filmsettings[9]
   1873                     miclevel = filmsettings[10]
   1874                     headphoneslevel = filmsettings[11]
   1875                     beeps = filmsettings[12]
   1876                     flip = filmsettings[13]
   1877                     comp = filmsettings[14]
   1878                     between = filmsettings[15]
   1879                     duration = filmsettings[16]
   1880                     showmenu_settings = filmsettings[17]
   1881                     quality = filmsettings[18]
   1882                     #wifistate = filmsettings[19]
   1883                     #serverstate=filmsettings[20]
   1884                     plughw=filmsettings[21]
   1885                     channels=filmsettings[22]
   1886                     #cammode=filmsettings[23]
   1887                     scene=filmsettings[24]
   1888                     shot=filmsettings[25]
   1889                     take=filmsettings[26]
   1890                     cameras=filmsettings[27]
   1891                     logger.info('film settings loaded & applied')
   1892                     time.sleep(0.2)
   1893                 except:
   1894                     logger.warning('could not load film settings')
   1895                 if flip == "yes":
   1896                     camera.vflip = True
   1897                     camera.hflip = True
   1898                 run_command('amixer -c 0 sset Mic ' + str(miclevel) + '% unmute')
   1899                 run_command('amixer -c 0 sset Speaker ' + str(headphoneslevel) + '%')
   1900                 print(filmfolder)
   1901                 print(filmname)
   1902                 origin_videos=organize(filmfolder, filmname)
   1903                 print('ORIGIN')
   1904                 print(origin_videos)
   1905                 print('total of videos: '+str(len(origin_videos)))
   1906                 with open(filmfolder+filmname+'/.origin_videos', 'w') as outfile:
   1907                     outfile.write('\n'.join(str(i) for i in origin_videos))
   1908                 if not os.path.isdir(filmfolder+'.videos/'):
   1909                     os.makedirs(filmfolder+'.videos/')
   1910                 allfiles = os.listdir(filmfolder+'.videos/')
   1911                 print(allfiles)
   1912                 print('alll')
   1913                 for origin in origin_videos:
   1914                     if origin in allfiles:
   1915                         try:
   1916                             #os.remove(origin)
   1917                             print('ORIGIN VIDEO FOLDER NOT IN SYNC' + origin)
   1918                             time.sleep(5)
   1919                         except:
   1920                             print('not exist')
   1921                 #organize(filmfolder,'onthefloor')
   1922                 scenes, shots, takes = countlast(filmname, filmfolder)
   1923                 loadfilmsettings = False
   1924                 rendermenu = True
   1925                 updatethumb =  True
   1926             if scene == 0:
   1927                 scene = 1
   1928             if take == 0:
   1929                 take = 1
   1930             if shot == 0:
   1931                 shot = 1
   1932             # If menu at SCENE show first shot thumbnail off that scene
   1933             if menu[selected] == 'FILM:' and lastmenu != menu[selected] and recordable == False:
   1934                 updatethumb = True
   1935             if menu[selected] == 'SCENE:' and lastmenu != menu[selected] and recordable == False:
   1936                 updatethumb = True
   1937             if menu[selected] == 'SHOT:' and lastmenu != menu[selected] and recordable == False:
   1938                 updatethumb = True
   1939             if menu[selected] == 'TAKE:' and lastmenu != menu[selected] and recordable == False:
   1940                 updatethumb = True
   1941             #Check if scene, shot, or take changed and update thumbnail
   1942             if oldscene != scene or oldshot != shot or oldtake != take or updatethumb == True:
   1943                 if recording == False:
   1944                     #logger.info('film:' + filmname + ' scene:' + str(scene) + '/' + str(scenes) + ' shot:' + str(shot) + '/' + str(shots) + ' take:' + str(take) + '/' + str(takes))
   1945                     foldername = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) +'/shot' + str(shot).zfill(3) + '/'
   1946                     filename = 'take' + str(take).zfill(3)
   1947                     recordable = not os.path.isfile(foldername + filename + '.mp4') and not os.path.isfile(foldername + filename + '.h264')
   1948                     overlay = removeimage(camera, overlay)
   1949                     if menu[selected] == 'SCENE:' and recordable == False: # display first shot of scene if browsing scenes
   1950                         p = counttakes(filmname, filmfolder, scene, 1)
   1951                         imagename = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(1).zfill(3) + '/take' + str(p).zfill(3) + '.jpeg'
   1952                         try:
   1953                             videosize=countsize(filmfolder + filmname + '/scene' + str(scene).zfill(3)+'/scene.mp4')
   1954                             vumetermessage('videosize: '+str(round(videosize/1000,2))+' Mb')
   1955                         except:
   1956                             vumetermessage('not rendered')
   1957                     #elif menu[selected] == 'FILM:' and recordable == True:
   1958                     #    scene, shot, take = countlast(filmname,filmfolder)
   1959                     #    shot += 1
   1960                     elif menu[selected] == 'FILM:' and recordable == False: # display first shot of film
   1961                         p = counttakes(filmname, filmfolder, 1, 1)
   1962                         imagename = filmfolder + filmname + '/scene' + str(1).zfill(3) + '/shot' + str(1).zfill(3) + '/take' + str(p).zfill(3) + '.jpeg'
   1963                         try:
   1964                             videosize=countsize(filmfolder + filmname + '/' + filmname+'.mp4')
   1965                             vumetermessage('videosize: '+str(round(videosize/1000,2))+' Mb')
   1966                         except:
   1967                             vumetermessage('not rendered')
   1968                     imagename = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/take' + str(take).zfill(3) + '.jpeg'
   1969                     if menu[selected]=='SHOT:' and recordable == False or menu[selected]=='TAKE:' and recordable==False:
   1970                         try:
   1971                             videosize=countsize(foldername + filename + '.mp4')
   1972                             vumetermessage('videosize: '+str(round(videosize/1000,2))+' Mb')
   1973                         except:
   1974                             videosize=countsize(foldername + filename + '.h264')
   1975                             vumetermessage('not rendered, videosize: '+str(round(videosize/1000,2))+' Mb')
   1976                     overlay = displayimage(camera, imagename, overlay, 3)
   1977                     oldscene = scene
   1978                     oldshot = shot
   1979                     oldtake = take
   1980                     updatethumb = False
   1981                     scenes = countscenes(filmfolder, filmname)
   1982                     shots = countshots(filmname, filmfolder, scene)
   1983                     takes = counttakes(filmname, filmfolder, scene, shot)
   1984             #If auto dont show value show auto (impovement here to show different colors in gui, yes!!?)
   1985             if camera.iso == 0:
   1986                 cameraiso = 'auto'
   1987             else:
   1988                 cameraiso = str(camera.iso)
   1989             if camera.shutter_speed == 0:
   1990                 camerashutter = 'auto'
   1991             else:
   1992                 camerashutter = str(camera.exposure_speed).zfill(5)
   1993             if camera.awb_mode == 'auto':
   1994                 camerared = 'auto'
   1995                 camerablue = 'auto'
   1996             else:
   1997                 camerared = str(float(camera.awb_gains[0]))[:4]
   1998                 camerablue = str(float(camera.awb_gains[1]))[:4]
   1999 
   2000             #Check if menu is changed and save settings / sec
   2001             if buttonpressed == True or recording == True or rendermenu == True:
   2002                 lastmenu = menu[selected]
   2003                 if showgonzopictrl == False:
   2004                     menu = standardmenu
   2005                     settings = storagedrives[dsk][0]+' '+diskleft, filmname, str(scene) + '/' + str(scenes), str(shot) + '/' + str(shots), str(take) + '/' + str(takes), rectime, camerashutter, cameraiso, camerared, camerablue, str(round(camera.framerate)), str(quality), str(camera.brightness), str(camera.contrast), str(camera.saturation), effects[effectselected], str(flip), str(beeps), str(round(reclenght,2)), str(plughw), str(channels), str(miclevel), str(headphoneslevel), str(comp), '', cammode, '', serverstate, searchforcameras, wifistate, '', '', '', '', '', '', live
   2006                 else:
   2007                     #gonzopictrlmenu = 'FILM:', 'SCENE:', 'SHOT:', 'TAKE:', '', 'SHUTTER:', 'ISO:', 'RED:', 'BLUE:', 'FPS:', 'Q:', 'BRIGHT:', 'CONT:', 'SAT:', 'FLIP:', 'BEEP:', 'LENGTH:', 'HW:', 'CH:', 'MIC:', 'PHONES:', 'COMP:', 'TIMELAPSE', 'MODE:', 'DSK:', 'SHUTDOWN', 'SRV:', 'SEARCH:', 'WIFI:', 'CAMERA:', 'Add CAMERA', 'New FILM', 'Sync FILM', 'Sync SCENE'
   2008                     menu = gonzopictrlmenu
   2009                     #settings = '',str(camselected),'','',rectime,'','','','','','','','','',''
   2010                     settings = storagedrives[dsk][0]+' '+diskleft, filmname, str(scene) + '/' + str(scenes), str(shot) + '/' + str(shots), str(take) + '/' + str(takes), rectime, camerashutter, cameraiso, camerared, camerablue, str(round(camera.framerate)), str(quality), str(camera.brightness), str(camera.contrast), str(camera.saturation), effects[effectselected], str(flip), str(beeps), str(reclenght), str(plughw), str(channels), str(miclevel), str(headphoneslevel), str(comp), '', cammode, '', serverstate, searchforcameras, wifistate, str(camselected+1), '', '', '', '', '', ''
   2011                 #Rerender menu if picamera settings change
   2012                 #if settings != oldsettings or selected != oldselected:
   2013                 writemenu(menu,settings,selected,'',showmenu)
   2014                 rendermenu = False
   2015                 #save settings if menu has been updated and x seconds passed
   2016                 if recording == False:
   2017                     #if time.time() - pausetime > savesettingsevery: 
   2018                     if oldsettings != settings:
   2019                         settings_to_save = [filmfolder, filmname, camera.brightness, camera.contrast, camera.saturation, camera.shutter_speed, camera.iso, camera.awb_mode, camera.awb_gains, awb_lock, miclevel, headphoneslevel, beeps, flip, comp, between, duration, showmenu_settings, quality,wifistate,serverstate,plughw,channels,cammode,scene,shot,take,cameras]
   2020                         #print('saving settings')
   2021                         savesettings(settings_to_save, filmname, filmfolder)
   2022                     if time.time() - pausetime > savesettingsevery: 
   2023                         pausetime = time.time()
   2024                         #NETWORKS
   2025                         networks=[]
   2026                         adapters = ifaddr.get_adapters()
   2027                         for adapter in adapters:
   2028                             print("IPs of network adapter " + adapter.nice_name)
   2029                             for ip in adapter.ips:
   2030                                 if ':' not in ip.ip[0] and '127.0.0.1' != ip.ip:
   2031                                     print(ip.ip)
   2032                                     networks=[ip.ip]
   2033                         if networks != []:
   2034                             network=networks[0]
   2035                             if network not in cameras:
   2036                                 cameras=[]
   2037                                 cameras.append(network)
   2038                         else:
   2039                             network='not connected'
   2040                         if len(cameras) > 1:
   2041                             camerasconnected='connected '+str(len(cameras)-1)
   2042                             recordwithports=True
   2043                             if camera_recording:
   2044                                 vumetermessage('filming with '+camera_model +' ip:'+ cameras[camselected] + ' '+camerasconnected+' camselected:'+str(camselected+1)+' rec:'+str(camera_recording+1))
   2045                             else:
   2046                                 vumetermessage('filming with '+camera_model +' ip:'+ cameras[camselected] + ' '+camerasconnected+' camselected:'+str(camselected+1)+' rec:'+str(camera_recording))
   2047                         else:
   2048                             camerasconnected=''
   2049                             recordwithports=False
   2050                             if searchforcameras == 'on':
   2051                                 camerasconnected='searching '+str(pingip)
   2052                             if menu[selected] != 'SHOT:' and menu[selected] != 'SCENE:' and menu[selected] != 'FILM:' and menu[selected] != 'TAKE:':
   2053                                 vumetermessage('filming with '+camera_model +' ip:'+ network + ' '+camerasconnected)
   2054                         disk = os.statvfs(filmfolder)
   2055                         diskleft = str(int(disk.f_bavail * disk.f_frsize / 1024 / 1024 / 1024)) + 'Gb'
   2056                         checksync = str(int(disk.f_bavail * disk.f_frsize / 1024 / 1024 )) + 'Mb'
   2057                         if checksync == oldchecksync:
   2058                             rectime = ''
   2059                         else:
   2060                             rectime = 'SYNCING.. '
   2061                             oldchecksync = checksync
   2062                         #print(term.yellow+'filming with '+camera_model +' ip:'+ network
   2063                         print(camselected,camera_recording,cameras)
   2064                 #writemessage(pressed)
   2065                 oldsettings = settings
   2066                 oldselected = selected
   2067             #PING TARINAS
   2068             if searchforcameras == 'on':
   2069                 if camera_recording == None:
   2070                     if pingip < 256:
   2071                         pingip+=1
   2072                     else:
   2073                         pingip=0
   2074                         #searchforcameras='off'
   2075                     newcamera=pingtocamera(network[:-3]+str(pingip),port,'PING')
   2076                     if newcamera != '':
   2077                         if newcamera not in cameras and newcamera not in networks:
   2078                             cameras.append(newcamera)
   2079                             vumetermessage("Found camera! "+newcamera)
   2080                     print('-~-')
   2081                     print('pinging ip: '+network[:-3]+str(pingip))
   2082                 else:
   2083                     searchforcameras = 'off'
   2084             time.sleep(keydelay)
   2085 
   2086 #--------------Logger-----------------------
   2087 
   2088 class logger():
   2089     def info(info):
   2090         print(term.yellow(info))
   2091     def warning(warning):
   2092         print('Warning: ' + warning)
   2093 
   2094 #-------------get film db files---
   2095 
   2096 def get_film_files(filmname,filmfolder,db):
   2097     if not os.path.isdir(filmfolder+'.videos/'):
   2098         os.makedirs(filmfolder+'.videos/')
   2099     filmdb = filmfolder+'.videos/gonzopi.db'
   2100     db = web.database(dbn='sqlite', db=filmdb)
   2101     try:
   2102         videodb=db.select('videos')
   2103         return db
   2104     except:
   2105         db.query("CREATE TABLE videos (id integer PRIMARY KEY, tid DATETIME, filename TEXT, foldername TEXT, filmname TEXT, scene INT, shot INT, take INT, audiolenght FLOAT, videolenght FLOAT,soundlag FLOAT, audiosync FLOAT);")
   2106     videodb=db.select('videos')
   2107     return db
   2108 
   2109 #--------------Save settings-----------------
   2110 
   2111 def savesettings(settings, filmname, filmfolder):
   2112     #db.insert('videos', tid=datetime.datetime.now())
   2113     try:
   2114         with open(filmfolder + filmname + "/settings.p", "wb") as f:
   2115             pickle.dump(settings, f)
   2116             #logger.info("settings saved")
   2117     except:
   2118         logger.warning("could not save settings")
   2119         #logger.warning(e)
   2120     return
   2121 
   2122 #--------------Load film settings--------------
   2123 
   2124 def loadsettings(filmfolder, filmname):
   2125     try:
   2126         settings = pickle.load(open(filmfolder + filmname + "/settings.p", "rb"))
   2127         logger.info("settings loaded")
   2128         return settings
   2129     except:
   2130         logger.info("couldnt load settings")
   2131         return ''
   2132 
   2133 
   2134 ##---------------Connection----------------------------------------------
   2135 def pingtocamera(host, port, data):
   2136     print("Sending to "+host+" on port "+str(port)+" DATA:"+data)
   2137     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   2138     s.settimeout(0.05)
   2139     newcamera=''
   2140     try:
   2141         while True:
   2142             s.connect((host, port))
   2143             s.send(str.encode(data))
   2144             newcamera=host
   2145             print("Sent to server..")
   2146             break
   2147     except:
   2148         print('did not connect')
   2149     s.close()
   2150     return newcamera
   2151 
   2152 ##---------------Send to server----------------------------------------------
   2153 
   2154 def sendtocamera(host, port, data):
   2155     print("Sending to "+host+" on port "+str(port)+" DATA:"+data)
   2156     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   2157     s.settimeout(5)
   2158     try:
   2159         while True:
   2160             s.connect((host, port))
   2161             s.send(str.encode(data))
   2162             print("Sent to server..")
   2163             break
   2164         return True
   2165     except:
   2166         print('did not connect')
   2167         return False
   2168     s.close()
   2169 
   2170 ##---------------Send to server----------------------------------------------
   2171 
   2172 def sendtoserver(host, port, data):
   2173     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   2174     try:
   2175         while True:
   2176             print('sending data to '+host+':'+str(port))
   2177             s.connect((host, port))
   2178             s.send(str.encode(data))
   2179             s.close()
   2180             break
   2181     except:
   2182         print('sometin rong')
   2183 
   2184 ##--------------Listen for Clients-----------------------
   2185 
   2186 def listenforclients(host, port, q):
   2187     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   2188     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
   2189     s.bind((host,port))
   2190     #s.settimeout(0.1)
   2191     try:
   2192         print("listening on port "+str(port))
   2193         s.listen(5)
   2194         c, addr = s.accept()
   2195         while True:
   2196                 data = c.recv(1024).decode()
   2197                 if not data:
   2198                     print("no data")
   2199                     break
   2200                 else:
   2201                     if addr:
   2202                         #print(addr[0],' sending back')
   2203                         #sendtoserver(addr[0],port,'rebounce'+data)
   2204                         nextstatus = data
   2205                         print("got data:"+nextstatus)
   2206                         c.close()
   2207                         q.put(nextstatus+'*'+addr[0])
   2208                         break
   2209     except:
   2210         print("somthin wrong")
   2211         q.put('')
   2212 
   2213 #--------------Write the menu layer to dispmanx--------------
   2214 
   2215 def writemenu(menu,settings,selected,header,showmenu):
   2216     global menudone, rendermenu
   2217     oldmenu=menudone
   2218     menudone = ''
   2219     menudoneprint = ''
   2220     menudone += str(selected) + '\n'
   2221     menudone += str(showmenu) + '\n'
   2222     menudone += header + '\n'
   2223     n = 0
   2224     for i, s in zip(menu, settings):
   2225         menudone += i + s + '\n'
   2226         if n == selected:
   2227             menudoneprint += term.black_on_darkkhaki(i+s) + ' | ' 
   2228         else:
   2229             menudoneprint += i + ' ' + s + ' | '
   2230         n += 1
   2231     spaces = len(menudone) - 500
   2232     menudone += spaces * ' '
   2233     if oldmenu != menudone or rendermenu == True:
   2234         print(term.clear+term.home)
   2235         if showmenu == 0:
   2236             print(term.red+menudoneprint)
   2237         else:
   2238             print(menudoneprint)
   2239         #menudone += 'EOF'
   2240         f = open('/dev/shm/interface', 'w')
   2241         f.write(menudone)
   2242         f.close()
   2243         return menudone
   2244 
   2245 #------------Write to screen----------------
   2246 
   2247 def writemessage(message):
   2248     menudone = ""
   2249     menudone += '420' + '\n'
   2250     menudone += message + '\n'
   2251     #menudone += 'EOF'
   2252     #clear = 500
   2253     #clear = clear - len(message)
   2254     f = open('/dev/shm/interface', 'w')
   2255     f.write(menudone)
   2256     f.close()
   2257 
   2258 #------------Write to vumeter (last line)-----
   2259 
   2260 def vumetermessage(message):
   2261     clear = 72
   2262     clear = clear - len(message)
   2263     f = open('/dev/shm/vumeter', 'w')
   2264     f.write(message + clear * ' ')
   2265     f.close()
   2266     logger.info(message)
   2267 
   2268 #------------Count file size-----
   2269 
   2270 def countvideosize(filename):
   2271     size = 0
   2272     if type(filename) is list:
   2273         size = 0
   2274         for i in filename[:]:
   2275             size = size + os.stat(i + '.mp4').st_size
   2276     if type(filename) is str:
   2277         size = os.stat(filename + '.mp4').st_size
   2278     return size/1024
   2279 
   2280 def countsize(filename):
   2281     size = 0
   2282     if type(filename) is str:
   2283         size = os.stat(filename).st_size
   2284     else:
   2285         return 0
   2286     return size/1024
   2287 
   2288 #------------Count scenes, takes and shots-----
   2289 
   2290 def countlast(filmname, filmfolder): 
   2291     scenes = 0
   2292     shots = 0
   2293     takes = 0
   2294     try:
   2295         allfiles = os.listdir(filmfolder + filmname)
   2296     except:
   2297         allfiles = []
   2298         scenes = 0
   2299     for a in allfiles:
   2300         if 'scene' in a:
   2301             scenes = scenes + 1
   2302     try:
   2303         allfiles = os.listdir(filmfolder + filmname + '/scene' + str(scenes).zfill(3))
   2304     except:
   2305         allfiles = []
   2306         shots = 0
   2307     for a in allfiles:
   2308         if 'shot' in a:
   2309             shots = shots + 1
   2310     try:
   2311         allfiles = os.listdir(filmfolder + filmname + '/scene' + str(scenes).zfill(3) + '/shot' + str(shots).zfill(3))
   2312     except:
   2313         allfiles = []
   2314         takes = 0
   2315     for a in allfiles:
   2316         if '.mp4' in a or '.h264' in a:
   2317             takes = takes + 1
   2318     return scenes, shots, takes
   2319 
   2320 #------------Count scenes--------
   2321 
   2322 def countscenes(filmfolder, filmname):
   2323     scenes = 0
   2324     try:
   2325         allfiles = os.listdir(filmfolder + filmname)
   2326     except:
   2327         allfiles = []
   2328         scenes = 0
   2329     for a in allfiles:
   2330         if 'scene' in a:
   2331             scenes = scenes + 1
   2332     return scenes
   2333 
   2334 #------------Count shots--------
   2335 
   2336 def countshots(filmname, filmfolder, scene):
   2337     shots = 0
   2338     try:
   2339         allfiles = os.listdir(filmfolder + filmname + '/scene' + str(scene).zfill(3))
   2340     except:
   2341         allfiles = []
   2342         shots = 0
   2343     for a in allfiles:
   2344         if 'shot' in a:
   2345             shots = shots + 1
   2346     return shots
   2347 
   2348 #------------Count takes--------
   2349 
   2350 def counttakes(filmname, filmfolder, scene, shot):
   2351     takes = 0
   2352     doubles = ''
   2353     try:
   2354         allfiles = os.listdir(filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3))
   2355     except:
   2356         allfiles = []
   2357         return takes
   2358     for a in allfiles:
   2359         if '.mp4' in a or '.h264' in a:
   2360             if not doubles.replace('.h264', '.mp4') == a:
   2361                 takes = takes + 1
   2362             doubles = a
   2363     return takes
   2364 
   2365 #-----------Count videos on floor-----
   2366 
   2367 def countonfloor(filmname, filmfolder):
   2368     print('dsad')
   2369 
   2370 
   2371 #------------Run Command-------------
   2372 
   2373 def run_command(command_line):
   2374     #command_line_args = shlex.split(command_line)
   2375     logger.info('Running: "' + command_line + '"')
   2376     try:
   2377         p = subprocess.Popen(command_line, shell=True).wait()
   2378         # process_output is now a string, not a file,
   2379         # you may want to do:
   2380     except (OSError, CalledProcessError) as exception:
   2381         logger.warning('Exception occured: ' + str(exception))
   2382         logger.warning('Process failed')
   2383         return False
   2384     else:
   2385         # no exception was raised
   2386         logger.info('Process finished')
   2387     return True
   2388 
   2389 #-------------Display bakg-------------------
   2390 
   2391 def displaybakg(camera, filename, underlay, layer):
   2392     # Load the arbitrarily sized image
   2393     img = Image.open(filename)
   2394     # Create an image padded to the required size with
   2395     # mode 'RGB'
   2396     pad = Image.new('RGB', (
   2397         ((img.size[0] + 31) // 32) * 32,
   2398         ((img.size[1] + 15) // 16) * 16,
   2399         ))
   2400     # Paste the original image into the padded one
   2401     pad.paste(img, (0, 0))
   2402 
   2403     # Add the overlay with the padded image as the source,
   2404     # but the original image's dimensions
   2405     underlay = camera.add_overlay(pad.tobytes(), size=img.size)
   2406     # By default, the overlay is in layer 0, beneath the
   2407     # preview (which defaults to layer 2). Here we make
   2408     # the new overlay semi-transparent, then move it above
   2409     # the preview
   2410     underlay.alpha = 255
   2411     underlay.layer = layer
   2412 
   2413 #-------------Display jpeg-------------------
   2414 
   2415 def displayimage(camera, filename, overlay, layer):
   2416     # Load the arbitrarily sized image
   2417     try:
   2418         img = Image.open(filename)
   2419     except:
   2420         #writemessage('Seems like an empty shot. Hit record!')
   2421         overlay = removeimage(camera, overlay)
   2422         return overlay
   2423     camera.stop_preview()
   2424     # Create an image padded to the required size with
   2425     # mode 'RGB'
   2426     pad = Image.new('RGB', (
   2427         ((img.size[0] + 31) // 32) * 32,
   2428         ((img.size[1] + 15) // 16) * 16,
   2429         ))
   2430     # Paste the original image into the padded one
   2431     pad.paste(img, (0, 0))
   2432 
   2433     # Add the overlay with the padded image as the source,
   2434     # but the original image's dimensions
   2435     overlay = camera.add_overlay(pad.tobytes(), size=img.size)
   2436     # By default, the overlay is in layer 0, beneath the
   2437     # preview (which defaults to layer 2). Here we make
   2438     # the new overlay semi-transparent, then move it above
   2439     # the preview
   2440     overlay.alpha = 255
   2441     overlay.layer = layer
   2442     return overlay
   2443 
   2444 def removeimage(camera, overlay):
   2445     if overlay:
   2446         try:
   2447             camera.remove_overlay(overlay)
   2448             overlay = None
   2449             camera.start_preview()
   2450         except:
   2451             pass
   2452         return overlay
   2453 
   2454 
   2455 #-------------Browse------------------
   2456 
   2457 def browse(filmname, filmfolder, scene, shot, take):
   2458     scenes = countscenes(filmfolder, filmname)
   2459     shots = countshots(filmname, filmfolder, scene)
   2460     takes = counttakes(filmname, filmfolder, scene, shot)
   2461     return scenes, shots, takes
   2462 
   2463 #-------------Browse2.0------------------
   2464 
   2465 def browse2(filmname, filmfolder, scene, shot, take, n, b):
   2466     scenes = countscenes(filmfolder, filmname)
   2467     shots = countshots(filmname, filmfolder, scene)
   2468     takes = counttakes(filmname, filmfolder, scene, shot)
   2469     #writemessage(str(scene) + ' < ' + str(scenes))
   2470     #time.sleep(4)
   2471     selected = n
   2472     if selected == 0 and b == 1:
   2473         if scene < scenes + 1: #remove this if u want to select any scene
   2474             scene = scene + 1
   2475             shot = countshots(filmname, filmfolder, scene)
   2476             take = counttakes(filmname, filmfolder, scene, shot)
   2477             #if take == 0:
   2478                 #shot = shot - 1
   2479                 #take = counttakes(filmname, filmfolder, scene, shot - 1)
   2480     elif selected == 1 and b == 1:
   2481         if shot < shots + 1: #remove this if u want to select any shot
   2482             shot = shot + 1 
   2483             take = counttakes(filmname, filmfolder, scene, shot)
   2484     elif selected == 2 and b == 1:
   2485         if take < takes + 1:
   2486             take = take + 1 
   2487     elif selected == 0 and b == -1:
   2488         if scene > 1:
   2489             scene = scene - 1
   2490             shot = countshots(filmname, filmfolder, scene)
   2491             take = counttakes(filmname, filmfolder, scene, shot)
   2492             #if take == 0:
   2493             #    shot = shot - 1
   2494             #    take = counttakes(filmname, filmfolder, scene, shot - 1)
   2495     elif selected == 1 and b == -1:
   2496         if shot > 1:
   2497             shot = shot - 1
   2498             take = counttakes(filmname, filmfolder, scene, shot)
   2499     elif selected == 2 and b == -1:
   2500         if take > 1:
   2501             take = take - 1 
   2502     return scene, shot, take
   2503 
   2504 #-------------Update------------------
   2505 
   2506 def update(gonzopiversion, gonzopivername):
   2507     logger.info('Current version ' + gonzopiversion[:-1] + ' ' + gonzopivername[:-1])
   2508     time.sleep(2)
   2509     logger.info('Checking for updates...')
   2510     try:
   2511         run_command('wget -N https://raw.githubusercontent.com/rbckman/gonzopi/master/VERSION -P /tmp/')
   2512     except:
   2513         logger.info('Sorry buddy, no internet connection')
   2514         time.sleep(2)
   2515         return gonzopiversion, gonzopivername
   2516     try:
   2517         f = open('/tmp/VERSION')
   2518         versionnumber = f.readline()
   2519         versionname = f.readline()
   2520     except:
   2521         logger.info('hmm.. something wrong with the update')
   2522     if round(float(gonzopiversion),3) < round(float(versionnumber),3):
   2523         logger.info('New version found ' + versionnumber[:-1] + ' ' + versionname[:-1])
   2524         time.sleep(4)
   2525         logger.info('Updating...')
   2526         run_command('git -C ' + gonzopifolder + ' pull')
   2527         #run_command('sudo ' + gonzopifolder + '/install.sh')
   2528         logger.info('Update done, will now reboot Gonzopi')
   2529         waitforanykey()
   2530         logger.info('Hold on rebooting Gonzopi...')
   2531         run_command('sudo reboot')
   2532     logger.info('Version is up-to-date!')
   2533     return gonzopiversion, gonzopivername
   2534 
   2535 #-------------Get films---------------
   2536 
   2537 def getfilms(filmfolder):
   2538     #get a list of films, in order of settings.p file last modified
   2539     films_sorted = []
   2540     films = next(os.walk(filmfolder))[1]
   2541     if films == []:
   2542         return
   2543     for i in films:
   2544         if not '.videos' in i:
   2545             if os.path.isfile(filmfolder + i + '/' + 'settings.p') == True:
   2546                 lastupdate = os.path.getmtime(filmfolder + i + '/' + 'settings.p')
   2547                 films_sorted.append((i,lastupdate))
   2548             else:
   2549                 films_sorted.append((i,0))
   2550     films_sorted = sorted(films_sorted, key=lambda tup: tup[1], reverse=True)
   2551     logger.info('*-- Films --*')
   2552     for p in films_sorted:
   2553         logger.info(p[0])
   2554     return films_sorted
   2555 
   2556 #-------------Load gonzopi config---------------
   2557 
   2558 def getconfig(camera):
   2559     filmfolder=''
   2560     if camera != None:
   2561         version = camera.revision
   2562     else:
   2563         version = 'none'
   2564     home = os.path.expanduser('~')
   2565     configfile = home + '/.gonzopi/config.ini'
   2566     configdir = os.path.dirname(configfile)
   2567     if not os.path.isdir(configdir):
   2568         os.makedirs(configdir)
   2569     config = configparser.ConfigParser()
   2570     if config.read(configfile):
   2571         try:
   2572             camera_model = config['SENSOR']['model']
   2573         except:
   2574             logger.info("couldnt read config")
   2575         try:
   2576             camera_revision = config['SENSOR']['revision']
   2577         except:
   2578             logger.info("couldnt read config")
   2579         try:
   2580             filmfolder = config['USER']['filmfolder']
   2581             return camera_model, camera_revision, filmfolder+'/'
   2582         except:
   2583             logger.info("couldnt read config")
   2584     if version == 'none':
   2585         config['SENSOR'] = {}
   2586         config['SENSOR']['model'] = version
   2587         config['SENSOR']['revision'] = 'none'
   2588         with open(configfile, 'w') as f:
   2589             config.write(f)
   2590         camera_model = version
   2591         camera_revision = 'none'
   2592     elif version == 'imx219':
   2593         config['SENSOR'] = {}
   2594         config['SENSOR']['model'] = version
   2595         config['SENSOR']['revision'] = 'standard'
   2596         with open(configfile, 'w') as f:
   2597             config.write(f)
   2598         camera_model = version
   2599         camera_revision = 'standard'
   2600     elif version == 'imx477':
   2601         config['SENSOR'] = {}
   2602         config['SENSOR']['model'] = version
   2603         config['SENSOR']['revision'] = 'hq-camera'
   2604         camera_model = version
   2605         camera_revision = 'hq-camera'
   2606         with open(configfile, 'w') as f:
   2607             config.write(f)
   2608     else:
   2609         pressed = ''
   2610         buttonpressed = ''
   2611         buttontime = time.time()
   2612         holdbutton = ''
   2613         selected = 0
   2614         header = 'What revision of ' + version + ' sensor are you using?'
   2615         menu = 'rev.C', 'rev.D', 'hq-camera'
   2616         while True:
   2617             settings = '', '', ''
   2618             writemenu(menu,settings,selected,header,showmenu)
   2619             pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   2620             if pressed == 'right':
   2621                 if selected < (len(settings) - 1):
   2622                     selected = selected + 1
   2623             elif pressed == 'left':
   2624                 if selected > 0:
   2625                     selected = selected - 1
   2626             elif pressed == 'middle':
   2627                 camera_model = version
   2628                 camera_revision = menu[selected]
   2629                 config['SENSOR'] = {}
   2630                 config['SENSOR']['model'] = camera_model
   2631                 config['SENSOR']['revision'] = camera_revision
   2632                 with open(configfile, 'w') as f:
   2633                     config.write(f)
   2634             time.sleep(0.02)
   2635 
   2636     return version, camera_revision, home+'/gonzopifilms/'
   2637     #if filmfolder != '':
   2638     #    return version, camera_revision, filmfolder+'/'
   2639     #else:
   2640     #    filmfolder = namesomething('Your film folder: ', home+'/Videos')
   2641     #    config['USER'] = {}
   2642     #    config['USER']['filmfolder'] = filmfolder
   2643     #    with open(configfile, 'w') as f:
   2644     #        config.write(f)
   2645     #    return camera_model, camera_revision, filmfolder+'/'
   2646 
   2647 #-------------Calc folder size with du-----------
   2648 
   2649 def du(path):
   2650     """disk usage in human readable format (e.g. '2,1GB')"""
   2651     return subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8')
   2652 
   2653 
   2654 #------------Clean up----------------
   2655 
   2656 def cleanupdisk(filmname, filmfolder):
   2657     alloriginfiles=[]
   2658     films = getfilms(filmfolder)
   2659     for f in films:
   2660         alloriginfiles.extend(organize(filmfolder,f[0]))
   2661     print(alloriginfiles)
   2662     filesinfolder = next(os.walk(filmfolder+'.videos/'))[2]
   2663     filesfolder=[]
   2664     for i in filesinfolder:
   2665         filesfolder.append(filmfolder+'.videos/'+i)
   2666     print(filesfolder)
   2667     for i in alloriginfiles:
   2668         if i in filesfolder:
   2669             print("YES, found link to origin")
   2670         else:
   2671             print("NOPE, no link to origin")
   2672             print(i)
   2673             time.sleep(2)
   2674             #os.system('rm ' + i)
   2675     #for i in filesfolder:
   2676     #    if i in alloriginfiles:
   2677     #        print("YES, found link to origin")
   2678     #    else:
   2679     #        print("NOPE, no link to origin")
   2680     #        print(i)
   2681     #        os.system('rm ' + i)
   2682 
   2683 #-------------Load film---------------
   2684 
   2685 def loadfilm(filmname, filmfolder, camera, overlay):
   2686     pressed = ''
   2687     buttonpressed = ''
   2688     buttontime = time.time()
   2689     holdbutton = ''
   2690     films = getfilms(filmfolder)
   2691     filmsize=[]
   2692     for f in films:
   2693         filmsize.append(du(filmfolder+f[0]))
   2694     filmstotal = len(films[1:])
   2695     selectedfilm = 0
   2696     selected = 0
   2697     header = 'Up and down to select and load film'
   2698     menu = 'FILM:', 'BACK'
   2699     while True:
   2700         settings = films[selectedfilm][0], ''
   2701         writemenu(menu,settings,selected,header,showmenu)
   2702         vumetermessage('filmsize: '+filmsize[selectedfilm]+' date: '+time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(films[selectedfilm][1])))
   2703         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   2704         if pressed == 'down':
   2705             if selectedfilm < filmstotal:
   2706                 selectedfilm = selectedfilm + 1
   2707                 p = counttakes(films[selectedfilm][0], filmfolder, 1, 1)
   2708                 overlay = removeimage(camera, overlay)
   2709                 imagename = filmfolder + films[selectedfilm][0] + '/scene' + str(1).zfill(3) + '/shot' + str(1).zfill(3) + '/take' + str(p).zfill(3) + '.jpeg'
   2710                 overlay = displayimage(camera, imagename, overlay, 3)
   2711         elif pressed == 'up':
   2712             if selectedfilm > 0:
   2713                 selectedfilm = selectedfilm - 1
   2714                 p = counttakes(films[selectedfilm][0], filmfolder, 1, 1)
   2715                 overlay = removeimage(camera, overlay)
   2716                 imagename = filmfolder + films[selectedfilm][0] + '/scene' + str(1).zfill(3) + '/shot' + str(1).zfill(3) + '/take' + str(p).zfill(3) + '.jpeg'
   2717                 overlay = displayimage(camera, imagename, overlay, 3)
   2718         elif pressed == 'right':
   2719             if selected < (len(settings) - 1):
   2720                 selected = selected + 1
   2721         elif pressed == 'left':
   2722             if selected > 0:
   2723                 selected = selected - 1
   2724         elif pressed == 'middle' and menu[selected] == 'FILM:':
   2725             overlay = removeimage(camera, overlay)
   2726             filmname = films[selectedfilm][0]
   2727             return filmname
   2728         elif pressed == 'middle' and menu[selected] == 'BACK':
   2729             overlay = removeimage(camera, overlay)
   2730             writemessage('Returning')
   2731             return filmname
   2732         time.sleep(0.02)
   2733 
   2734 
   2735 #---------Name anything really-----------
   2736 
   2737 def namesomething(what, readymadeinput):
   2738     global abc
   2739     anything = readymadeinput
   2740     pressed = ''
   2741     buttonpressed = ''
   2742     buttontime = time.time()
   2743     holdbutton = ''
   2744     abcx = 0
   2745     helpmessage = 'Up, Down (select characters) Right (next). Middle (done)'
   2746     cursor = '_'
   2747     blinking = True
   2748     pausetime = time.time()
   2749     while True:
   2750         message = what + anything
   2751         print(term.clear+term.home)
   2752         print(message+cursor)
   2753         writemessage(message + cursor)
   2754         vumetermessage(helpmessage)
   2755         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   2756         if event == ' ':
   2757             event = '_'
   2758         if pressed == 'down':
   2759             pausetime = time.time()
   2760             if abcx < (len(abc) - 1):
   2761                 abcx = abcx + 1
   2762                 cursor = abc[abcx]
   2763         elif pressed == 'up':
   2764             pausetime = time.time()
   2765             if abcx > 0:
   2766                 abcx = abcx - 1
   2767                 cursor = abc[abcx]
   2768         elif pressed == 'right':
   2769             pausetime = time.time()
   2770             if len(anything) < 30:
   2771                 anything = anything + abc[abcx]
   2772                 cursor = abc[abcx]
   2773             else:
   2774                 helpmessage = 'Yo, maximum characters reached bro!'
   2775         elif pressed == 'left' or pressed == 'remove':
   2776             pausetime = time.time()
   2777             if len(anything) > 0:
   2778                 anything = anything[:-1]
   2779                 cursor = abc[abcx]
   2780         elif pressed == 'middle' or event == 10:
   2781             if len(anything) > 0:
   2782                 if abc[abcx] != '_':
   2783                     anything = anything + abc[abcx]
   2784                 return anything
   2785         elif event in abc:
   2786             pausetime = time.time()
   2787             anything = anything + event
   2788         if time.time() - pausetime > 0.5:
   2789             if blinking == True:
   2790                 cursor = abc[abcx]
   2791             if blinking == False:
   2792                 cursor = ' '
   2793             blinking = not blinking
   2794             pausetime = time.time()
   2795         time.sleep(keydelay)
   2796 
   2797 
   2798 #-------------New film----------------
   2799 
   2800 def nameyourfilm(filmfolder, filmname, abc, newfilm):
   2801     filmcount=len(getfilms(filmfolder))
   2802     oldfilmname = filmname
   2803     filmname = 'reel_'+str(filmcount+1).zfill(3)
   2804     #if newfilm == True:
   2805     #    filmname = ''
   2806     pressed = ''
   2807     buttonpressed = ''
   2808     buttontime = time.time()
   2809     holdbutton = ''
   2810     abcx = 0
   2811     helpmessage = 'Left (remove), Up, Down (select characters) Right (next). Middle (done), Retake (Cancel)'
   2812     vumetermessage('Press enter if you want to leave it untitled')
   2813     cursor = '_'
   2814     blinking = True
   2815     pausetime = time.time()
   2816     while True:
   2817         if newfilm == True:
   2818             message = 'New film name: ' + filmname
   2819         else:
   2820             message = 'Edit film name: ' + filmname
   2821         print(term.clear+term.home)
   2822         print(message+cursor)
   2823         print(helpmessage)
   2824         writemessage(message + cursor)
   2825         vumetermessage(helpmessage)
   2826         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   2827         if event == ' ':
   2828             event = '_'
   2829         if pressed == 'down':
   2830             pausetime = time.time()
   2831             if abcx < (len(abc) - 1):
   2832                 abcx = abcx + 1
   2833                 cursor = abc[abcx]
   2834         elif pressed == 'up':
   2835             pausetime = time.time()
   2836             if abcx > 0:
   2837                 abcx = abcx - 1
   2838                 cursor = abc[abcx]
   2839         elif pressed == 'right':
   2840             pausetime = time.time()
   2841             if len(filmname) < 30:
   2842                 filmname = filmname + abc[abcx]
   2843                 cursor = abc[abcx]
   2844             else:
   2845                 helpmessage = 'Yo, maximum characters reached bro!'
   2846         elif pressed == 'left' or pressed == 'remove':
   2847             pausetime = time.time()
   2848             if len(filmname) > 0:
   2849                 filmname = filmname[:-1]
   2850                 cursor = abc[abcx]
   2851         elif pressed == 'middle' or event == 10:
   2852             if filmname == '':
   2853                 filmname='untitledfilm'
   2854             if len(filmname) > 0:
   2855                 if abc[abcx] != '_':
   2856                     filmname = filmname + abc[abcx]
   2857                 try:
   2858                     if filmname == oldfilmname:
   2859                         return oldfilmname
   2860                     elif filmname in getfilms(filmfolder)[0]:
   2861                         helpmessage = 'this filmname is already taken! make a sequel!'
   2862                         filmname = filmname+'2'
   2863                     elif filmname not in getfilms(filmfolder)[0]:
   2864                         logger.info("New film " + filmname)
   2865                         return(filmname)
   2866                 except:
   2867                     logger.info("New film " + filmname)
   2868                     return(filmname)
   2869         elif pressed == 'retake':
   2870             return oldfilmname
   2871         elif event in abc:
   2872             pausetime = time.time()
   2873             filmname = filmname + event
   2874         if time.time() - pausetime > 0.5:
   2875             if blinking == True:
   2876                 cursor = abc[abcx]
   2877             if blinking == False:
   2878                 cursor = ' '
   2879             blinking = not blinking
   2880             pausetime = time.time()
   2881         time.sleep(keydelay)
   2882 
   2883 
   2884 #-------------New udp Stream host----------------
   2885 
   2886 def newudp_ip(abc, network):
   2887     pressed = ''
   2888     buttonpressed = ''
   2889     buttontime = time.time()
   2890     holdbutton = ''
   2891     abcx = 0
   2892     helpmessage = 'Up, Down (select characters) Right (next). Middle (done), Retake (Cancel)'
   2893     cursor = '_'
   2894     blinking = True
   2895     pausetime = time.time()
   2896     ip_network = network.split('.')[:-1]
   2897     ip_network = '.'.join(ip_network)+'.'
   2898     ip = ''
   2899     port=8000
   2900     while True:
   2901         message = 'Host ip and port: ' + ip_network + ip
   2902         print(term.clear+term.home)
   2903         print(message+cursor)
   2904         writemessage(message + cursor)
   2905         vumetermessage(helpmessage)
   2906         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   2907         if event == ' ':
   2908             event = '_'
   2909         if pressed == 'down':
   2910             pausetime = time.time()
   2911             if abcx < (len(abc) - 1):
   2912                 abcx = abcx + 1
   2913                 cursor = abc[abcx]
   2914         elif pressed == 'up':
   2915             pausetime = time.time()
   2916             if abcx > 0:
   2917                 abcx = abcx - 1
   2918                 cursor = abc[abcx]
   2919         elif pressed == 'right':
   2920             pausetime = time.time()
   2921             if len(ip) < 2:
   2922                 ip = ip + abc[abcx]
   2923                 cursor = abc[abcx]
   2924             else:
   2925                 helpmessage = 'Yo, maximum ip reached bro!'
   2926         elif pressed == 'left' or pressed == 'remove':
   2927             pausetime = time.time()
   2928             if len(ip) > 0:
   2929                 ip = ip[:-1]
   2930                 cursor = abc[abcx]
   2931         elif pressed == 'middle' or event == 10:
   2932             if abc[abcx] != ' ' or ip != '':
   2933                 ip = ip + abc[abcx]
   2934                 if int(ip) < 256:
   2935                     logger.info("New host " + ip_network+ip)
   2936                     newhost = (ip_network+ip).strip()
   2937                     break
   2938                 else:
   2939                     helpmessage = 'in the range of ips 1-256'
   2940         elif pressed == 'retake':
   2941             return '' 
   2942         elif event in abc:
   2943             pausetime = time.time()
   2944             ip = ip + event
   2945         if time.time() - pausetime > 0.5:
   2946             if blinking == True:
   2947                 cursor = abc[abcx]
   2948             if blinking == False:
   2949                 cursor = ' '
   2950             blinking = not blinking
   2951             pausetime = time.time()
   2952         time.sleep(keydelay)
   2953     ip='800'
   2954     abcx=1
   2955     while True:
   2956         message = 'Host ip and port: ' + newhost + ': ' + ip
   2957         print(term.clear+term.home)
   2958         print(message+cursor)
   2959         writemessage(message + cursor)
   2960         vumetermessage(helpmessage)
   2961         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   2962         if event == ' ':
   2963             event = '_'
   2964         if pressed == 'down':
   2965             pausetime = time.time()
   2966             if abcx < (len(abc) - 1):
   2967                 abcx = abcx + 1
   2968                 cursor = abc[abcx]
   2969         elif pressed == 'up':
   2970             pausetime = time.time()
   2971             if abcx > 0:
   2972                 abcx = abcx - 1
   2973                 cursor = abc[abcx]
   2974         elif pressed == 'right':
   2975             pausetime = time.time()
   2976             if len(ip) < 2:
   2977                 ip = ip + abc[abcx]
   2978                 cursor = abc[abcx]
   2979             else:
   2980                 helpmessage = 'Yo, maximum ip reached bro!'
   2981         elif pressed == 'left' or pressed == 'remove':
   2982             pausetime = time.time()
   2983             if len(ip) > 0:
   2984                 ip = ip[:-1]
   2985                 cursor = abc[abcx]
   2986         elif pressed == 'middle' or event == 10:
   2987             if abc[abcx] != ' ' or ip != '':
   2988                 ip = ip + abc[abcx]
   2989                 if int(ip) < 8256:
   2990                     logger.info("New port " +ip)
   2991                     return newhost, (ip).strip()
   2992                 else:
   2993                     helpmessage = 'in the range of ips 1-256'
   2994         elif pressed == 'retake':
   2995             return '' 
   2996         elif event in abc:
   2997             pausetime = time.time()
   2998             ip = ip + event
   2999         if time.time() - pausetime > 0.5:
   3000             if blinking == True:
   3001                 cursor = abc[abcx]
   3002             if blinking == False:
   3003                 cursor = ' '
   3004             blinking = not blinking
   3005             pausetime = time.time()
   3006         time.sleep(keydelay)
   3007 
   3008 #-------------New camera----------------
   3009 
   3010 def newcamera_ip(abc, network):
   3011     pressed = ''
   3012     buttonpressed = ''
   3013     buttontime = time.time()
   3014     holdbutton = ''
   3015     abcx = 0
   3016     helpmessage = 'Up, Down (select characters) Right (next). Middle (done), Retake (Cancel)'
   3017     cursor = '_'
   3018     blinking = True
   3019     pausetime = time.time()
   3020     ip_network = network.split('.')[:-1]
   3021     ip_network = '.'.join(ip_network)+'.'
   3022     ip = ''
   3023     while True:
   3024         message = 'Camera ip: ' + ip_network + ip
   3025         print(term.clear+term.home)
   3026         print(message+cursor)
   3027         writemessage(message + cursor)
   3028         vumetermessage(helpmessage)
   3029         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   3030         if event == ' ':
   3031             event = '_'
   3032         if pressed == 'down':
   3033             pausetime = time.time()
   3034             if abcx < (len(abc) - 1):
   3035                 abcx = abcx + 1
   3036                 cursor = abc[abcx]
   3037         elif pressed == 'up':
   3038             pausetime = time.time()
   3039             if abcx > 0:
   3040                 abcx = abcx - 1
   3041                 cursor = abc[abcx]
   3042         elif pressed == 'right':
   3043             pausetime = time.time()
   3044             if len(ip) < 2:
   3045                 ip = ip + abc[abcx]
   3046                 cursor = abc[abcx]
   3047             else:
   3048                 helpmessage = 'Yo, maximum ip reached bro!'
   3049         elif pressed == 'left' or pressed == 'remove':
   3050             pausetime = time.time()
   3051             if len(ip) > 0:
   3052                 ip = ip[:-1]
   3053                 cursor = abc[abcx]
   3054         elif pressed == 'middle' or event == 10:
   3055             if abc[abcx] != ' ' or ip != '':
   3056                 ip = ip + abc[abcx]
   3057                 if int(ip) < 256:
   3058                     logger.info("New camera " + ip_network+ip)
   3059                     return (ip_network+ip).strip()
   3060                 else:
   3061                     helpmessage = 'in the range of ips 1-256'
   3062         elif pressed == 'retake':
   3063             return '' 
   3064         elif event in abc:
   3065             pausetime = time.time()
   3066             ip = ip + event
   3067         if time.time() - pausetime > 0.5:
   3068             if blinking == True:
   3069                 cursor = abc[abcx]
   3070             if blinking == False:
   3071                 cursor = ' '
   3072             blinking = not blinking
   3073             pausetime = time.time()
   3074         time.sleep(keydelay)
   3075 
   3076 #------------Timelapse--------------------------
   3077 
   3078 def timelapse(beeps,camera,filmname,foldername,filename,between,duration,backlight):
   3079     pressed = ''
   3080     buttonpressed = ''
   3081     buttontime = time.time()
   3082     holdbutton = ''
   3083     sound = False
   3084     selected = 0
   3085     header = 'Adjust delay in seconds between videos'
   3086     menu = 'DELAY:', 'DURATION:', 'SOUND:', 'START', 'BACK'
   3087     while True:
   3088         settings = str(round(between,2)), str(round(duration,2)), str(sound), '', ''
   3089         writemenu(menu,settings,selected,header,showmenu)
   3090         seconds = (3600 / between) * duration
   3091         vumetermessage('1 h timelapse filming equals ' + str(round(seconds,2)) + ' second clip   ')
   3092         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   3093         if pressed == 'up' and menu[selected] == 'DELAY:':
   3094             between = between + 1
   3095         elif pressed == 'down' and menu[selected] == 'DELAY:':
   3096             if between > 1:
   3097                 between = between - 1
   3098         if pressed == 'up' and menu[selected] == 'SOUND:':
   3099             sound = True
   3100         elif pressed == 'down' and menu[selected] == 'SOUND:':
   3101             sound = False
   3102         elif pressed == 'up' and menu[selected] == 'DURATION:':
   3103             duration = duration + 0.1
   3104         elif pressed == 'down' and menu[selected] == 'DURATION:':
   3105             if duration > 0.3:
   3106                 duration = duration - 0.1
   3107         elif pressed == 'up' or pressed == 'down' and menu[selected] == 'SOUND:':
   3108             if sound == False:
   3109                 sound == True
   3110             if sound == True:
   3111                 sound == False
   3112         elif pressed == 'right':
   3113             if selected < (len(settings) - 1):
   3114                 selected = selected + 1
   3115         elif pressed == 'left':
   3116             if selected > 0:
   3117                 selected = selected - 1
   3118         elif pressed == 'middle':
   3119             if menu[selected] == 'START':
   3120                 if os.path.isdir(foldername+'timelapse') == False:
   3121                     os.makedirs(foldername + 'timelapse')
   3122                 time.sleep(0.02)
   3123                 writemessage('Recording timelapse, middlebutton to stop')
   3124                 n = 1
   3125                 recording = False
   3126                 starttime = time.time()
   3127                 t = 0
   3128                 files = []
   3129                 while True:
   3130                     t = time.time() - starttime
   3131                     pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   3132                     vumetermessage('Timelapse lenght is now ' + str(round(n * duration,2)) + ' second clip   ')
   3133                     if recording == False and t > between:
   3134                         if beeps > 0:
   3135                             if bus:
   3136                                 buzz(150)
   3137                             else:
   3138                                 run_command('aplay -D plughw:' + str(plughw) + ' '+ gonzopifolder + '/extras/beep.wav')
   3139                         #camera.start_recording(foldername + 'timelapse/' + filename + '_' + str(n).zfill(3) + '.h264', format='h264', quality=26, bitrate=5000000)
   3140                         camera.start_recording(foldername + 'timelapse/' + filename + '_' + str(n).zfill(3) + '.h264', format='h264', bitrate=5555555, level=profilelevel, quality=quality)
   3141                         if sound == True:
   3142                             os.system(gonzopifolder+'/alsa-utils-1.1.3/aplay/arecord -D hw:'+str(plughw)+' -f '+soundformat+' -c '+str(channels)+' -r '+soundrate+' -vv '+foldername+'timelapse/'+filename+'_'+str(n).zfill(3)+'.wav &')
   3143                         files.append(foldername + 'timelapse/' + filename + '_' + str(n).zfill(3))
   3144                         starttime = time.time()
   3145                         recording = True
   3146                         n = n + 1
   3147                         t = 0
   3148                     if recording == True:
   3149                         writemessage('Recording timelapse ' + str(n) + ' ' + 'time:' + str(round(t,2)))
   3150                     if recording == False:
   3151                         writemessage('Between timelapse ' + str(n) + ' ' + 'time:' + str(round(t,2)))
   3152                     if t > duration and recording == True:
   3153                         if sound == True:
   3154                             os.system('pkill arecord')
   3155                         camera.stop_recording()
   3156                         recording = False
   3157                         starttime = time.time()
   3158                         t = 0
   3159                     if pressed == 'screen':
   3160                         if backlight == False:
   3161                             # requires wiringpi installed
   3162                             run_command('gpio -g pwm 19 1023')
   3163                             backlight = True
   3164                         elif backlight == True:
   3165                             run_command('gpio -g pwm 19 0')
   3166                             backlight = False
   3167                     elif pressed == 'middle' and n > 1:
   3168                         if recording == True:
   3169                             os.system('pkill arecord')
   3170                             camera.stop_recording()
   3171                         #create thumbnail
   3172                         try:
   3173                             camera.capture(foldername + filename + '.jpeg', resize=(800,450), use_video_port=True)
   3174                         except:
   3175                             logger.warning('something wrong with camera jpeg capture')
   3176                         writemessage('Compiling timelapse')
   3177                         logger.info('Hold on, rendering ' + str(len(files)) + ' scenes')
   3178                         #RENDER VIDEO
   3179                         renderfilename = foldername + filename
   3180                         n = 1
   3181                         videomerge = ['MP4Box']
   3182                         videomerge.append('-force-cat')
   3183                         for f in files:
   3184                             if sound == True:
   3185                                 compileshot(f,filmfolder,filmname)
   3186                                 #audiotrim(foldername + 'timelapse/' + filename + '_' + str(n).zfill(3), 'end', '')
   3187                                 videomerge.append('-cat')
   3188                                 videomerge.append(f + '.mp4#video')
   3189                             else:
   3190                                 videomerge.append('-cat')
   3191                                 videomerge.append(f + '.h264')
   3192                             n = n + 1                            
   3193                         videomerge.append('-new')
   3194                         videomerge.append(renderfilename + '.mp4')
   3195                         call(videomerge, shell=False) #how to insert somekind of estimated time while it does this?
   3196                         ##RENDER AUDIO
   3197                         if sound == True:
   3198                             writemessage('Rendering sound')
   3199                             audiomerge = ['sox']
   3200                             #if render > 2:
   3201                             #    audiomerge.append(filename + '.wav')
   3202                             for f in files:
   3203                                 audiomerge.append(f + '.wav')
   3204                             audiomerge.append(renderfilename + '.wav')
   3205                             call(audiomerge, shell=False)
   3206                         ##MAKE AUDIO SILENCE
   3207                         if sound == False:
   3208                             audiosilence(foldername,filename)
   3209                         #cleanup
   3210                         #os.system('rm -r ' + foldername + 'timelapse')
   3211                         vumetermessage('timelapse done! ;)')
   3212                         return renderfilename, between, duration
   3213                     time.sleep(keydelay)
   3214             if menu[selected] == 'BACK':
   3215                 vumetermessage('ok!')
   3216                 return '', between, duration
   3217         time.sleep(keydelay)
   3218 
   3219 #------------Remove-----------------------
   3220 
   3221 def remove(filmfolder, filmname, scene, shot, take, sceneshotortake):
   3222     foldername = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/'
   3223     filename = 'take' + str(take).zfill(3)
   3224     pressed = ''
   3225     buttonpressed = ''
   3226     buttontime = time.time()
   3227     holdbutton = ''
   3228     time.sleep(0.1)
   3229     header = 'Are you sure you want to remove ' + sceneshotortake + '?'
   3230     menu = '', ''
   3231     settings = 'NO', 'YES'
   3232     selected = 0
   3233     otf_scene = countscenes(filmfolder, filmname)
   3234     otf_scene += 1
   3235     otf_shot = countshots(filmname, filmfolder, otf_scene)
   3236     otf_shot += 1
   3237     otf_take = counttakes(filmname, filmfolder, otf_scene, otf_shot)
   3238     otf_take += 1
   3239     while True:
   3240         writemenu(menu,settings,selected,header,showmenu)
   3241         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   3242         if pressed == 'right':
   3243             if selected < (len(settings) - 1):
   3244                 selected = selected + 1
   3245         elif pressed == 'left':
   3246             if selected > 0:
   3247                 selected = selected - 1
   3248         elif pressed == 'middle':
   3249             if selected == 1:
   3250                 if '_onthefloor' in filmname:
   3251                     if sceneshotortake == 'take':
   3252                         os.system('rm ' + foldername + filename + '.h264')
   3253                         os.system('rm ' + foldername + filename + '.mp4')
   3254                         os.system('rm ' + foldername + filename + '.wav')
   3255                         os.system('rm ' + foldername + filename + '.jpeg')
   3256                     elif sceneshotortake == 'shot' and shot > 0:
   3257                         os.system('rm -r ' + foldername)
   3258                     elif sceneshotortake == 'scene':
   3259                         foldername = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3)
   3260                         os.system('rm -r ' + foldername)
   3261                         scene = countscenes(filmfolder, filmname)
   3262                         shot=1
   3263                         take=1
   3264                     elif sceneshotortake == 'film':
   3265                         origin_videos=[]
   3266                         v=organize(filmfolder, filmname)
   3267                         if v == '':
   3268                             return
   3269                         origin_videos.extend(v)
   3270                         for i in origin_videos:
   3271                             print('remove video: '+i)
   3272                             try:
   3273                                 os.remove(i)
   3274                             except:
   3275                                 pass
   3276                             #time.sleep(3)
   3277                         foldername = filmfolder + filmname
   3278                         os.system('rm -r ' + foldername)
   3279                         return
   3280                 else:
   3281                     if sceneshotortake == 'take':
   3282                         writemessage('Throwing take on the floor' + str(take))
   3283                         #onthefloor = filmfolder + filmname + '_onthefloor/' + 'scene' + str(otf_scene).zfill(3) + '/shot' + str(otf_shot).zfill(3) + '/take' + str(otf_take).zfill(3) 
   3284                         onthefloor = filmfolder + filmname + '_onthefloor/' + 'scene' + str(otf_scene).zfill(3) + '/shot' + str(otf_shot).zfill(3) + '/'
   3285                         if os.path.isdir(onthefloor) == False:
   3286                             os.makedirs(onthefloor)
   3287                         os.system('mv ' + foldername + filename + '.h264 ' + onthefloor + '.h264')
   3288                         os.system('mv ' + foldername + filename + '.mp4 ' + onthefloor + '.mp4')
   3289                         os.system('mv ' + foldername + filename + '.wav ' + onthefloor + '.wav')
   3290                         os.system('mv ' + foldername + filename + '.jpeg ' + onthefloor + '.jpeg')
   3291                         os.system('cp -r '+filmfolder + filmname + "/settings.p "+filmfolder + filmname + '_onthefloor/settings.p')
   3292                         take = take - 1
   3293                         if take == 0:
   3294                             take = 1
   3295                     elif sceneshotortake == 'shot' and shot > 0:
   3296                         writemessage('Throwing shot on the floor' + str(shot))
   3297                         onthefloor = filmfolder + filmname + '_onthefloor/' + 'scene' + str(otf_scene).zfill(3) + '/shot' + str(otf_shot).zfill(3)+'/'
   3298                         os.makedirs(onthefloor)
   3299                         os.system('cp -r '+foldername+'* '+onthefloor)
   3300                         os.system('cp -r '+filmfolder + filmname + "/settings.p "+filmfolder + filmname + '_onthefloor/settings.p')
   3301                         os.system('rm -r '+foldername)
   3302                         take = counttakes(filmname, filmfolder, scene, shot)
   3303                     elif sceneshotortake == 'scene':
   3304                         onthefloor = filmfolder + filmname + '_onthefloor/' + 'scene' + str(otf_scene).zfill(3)
   3305                         os.makedirs(onthefloor)
   3306                         writemessage('Throwing clips on the floor ' + str(scene))
   3307                         foldername = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3)
   3308                         os.system('mv ' + foldername + '/* ' + onthefloor+'/' )
   3309                         os.system('cp -r '+filmfolder + filmname + "/settings.p "+filmfolder + filmname + '_onthefloor/settings.p')
   3310                         scene = countscenes(filmfolder, filmname)
   3311                         shot = 1
   3312                         take = 1
   3313                     elif sceneshotortake == 'film':
   3314                         origin_videos=[]
   3315                         v=organize(filmfolder, filmname)
   3316                         if v == '':
   3317                             return
   3318                         origin_videos.extend(v)
   3319                         for i in origin_videos:
   3320                             print('remove video: '+i)
   3321                             try:
   3322                                 os.remove(i)
   3323                             except:
   3324                                 pass
   3325                             #time.sleep(3)
   3326                         foldername = filmfolder + filmname
   3327                         os.system('rm -r ' + foldername)
   3328                         return
   3329                     organize(filmfolder, filmname + '_onthefloor')
   3330                 return
   3331             elif selected == 0:
   3332                 return
   3333         time.sleep(0.02)
   3334 
   3335 #--------CLEAN---------
   3336 
   3337 def clean(filmname, filmfolder):
   3338     if filmname == '':
   3339         films = getfilms(filmfolder)
   3340     else:
   3341         films.append(filmname)
   3342     videos_to_remove=[]
   3343     origin_videos=[]
   3344     for f in films:
   3345         v=organize(filmfolder, f[0])
   3346         origin_videos.extend(v)
   3347         print(filmfolder)
   3348         print(f[0])
   3349         print(origin_videos)
   3350         #time.sleep(5)
   3351     print('ORIGIN')
   3352     print(origin_videos)
   3353     print('alll')
   3354     allfiles = os.listdir(filmfolder+'.videos/')
   3355     print(allfiles)
   3356     print('all videos: '+ str(len(allfiles)))
   3357     remove_videos=[]
   3358     for video in allfiles:
   3359         if any(filmfolder+'.videos/'+video in x for x in origin_videos):
   3360             #os.remove(origin)
   3361             print('REMOVE ORIGIN VIDEO NOT IN SYNC ' + video)
   3362         else:
   3363             #os.remove(origin)
   3364             if video != 'gonzopi.db':
   3365                 remove_videos.append(filmfolder+'.videos/'+video)
   3366             print('ORIGIN VIDEO IN SYNC' + video)
   3367     #print(remove_videos)
   3368     print('all videos: '+ str(len(allfiles)))
   3369     print('origin videos: '+ str(len(origin_videos)))
   3370     print('to be removed: '+ str(len(remove_videos)))
   3371     for i in remove_videos:
   3372         os.remove(i)
   3373     #with open(filmfolder+'.videos/.remove_videos', 'w') as outfile:
   3374     #    outfile.write('\n'.join(str(i) for i in remove_videos))
   3375     #time.sleep(10)
   3376 
   3377 #------------Remove and Organize----------------
   3378 
   3379 def organize(filmfolder, filmname):
   3380     global fps, db
   3381     origin_files=[]
   3382     scenes = next(os.walk(filmfolder + filmname))[1]
   3383     for i in scenes:
   3384         if 'scene' not in i:
   3385             scenes.remove(i)
   3386     # Takes
   3387     for i in sorted(scenes):
   3388         origin_scene_files=[]
   3389         shots = next(os.walk(filmfolder + filmname + '/' + i))[1]
   3390         for p in sorted(shots):
   3391             takes = next(os.walk(filmfolder + filmname + '/' + i + '/' + p))[2]
   3392             if len(takes) == 0:
   3393                 logger.info('no takes in this shot, removing shot if no placeholder')
   3394                 if not os.path.isfile(filmfolder + filmname + '/' + i + '/' + p + '/.placeholder'):
   3395                     os.system('rm -r ' + filmfolder + filmname + '/' + i + '/' + p)
   3396             organized_nr = 1
   3397             print(i)
   3398             print(p)
   3399             print(sorted(takes))
   3400             #time.sleep(2)
   3401             for s in sorted(takes):
   3402                 if '.mp4' in s or '.h264' in s:
   3403                     unorganized_nr = int(s[4:7])
   3404                     takename = filmfolder + filmname + '/' + i + '/' + p + '/take' + str(unorganized_nr).zfill(3)
   3405                     if '.mp4' in s:
   3406                         origin=os.path.realpath(takename+'.mp4')
   3407                         if origin != os.path.abspath(takename+'.mp4'):
   3408                             print('appending: '+origin)
   3409                             origin_files.append(origin)
   3410                             origin_scene_files.append(origin)
   3411                             if os.path.isfile(takename+'.h264'):
   3412                                 print('oh no boubles found!')
   3413                     if '.h264' in s:
   3414                         origin=os.path.realpath(takename+'.h264')
   3415                         if origin != os.path.abspath(takename+'.h264'):
   3416                             origin_files.append(origin)
   3417                             origin_scene_files.append(origin)
   3418                     if organized_nr == unorganized_nr:
   3419                         #print('correct')
   3420                         pass
   3421                     if organized_nr != unorganized_nr:
   3422                         print('false, correcting from ' + str(unorganized_nr) + ' to ' + str(organized_nr))
   3423                         print(s)
   3424                         #time.sleep(3)
   3425                         mv = 'mv ' + filmfolder + filmname + '/' + i + '/' + p + '/take' + str(unorganized_nr).zfill(3)
   3426                         run_command(mv + '.mp4 ' + filmfolder + filmname + '/' + i + '/' + p + '/take' + str(organized_nr).zfill(3) + '.mp4')
   3427                         run_command(mv + '.h264 ' + filmfolder + filmname + '/' + i + '/' + p + '/take' + str(organized_nr).zfill(3) + '.h264')
   3428                         run_command(mv + '.wav ' + filmfolder + filmname + '/' + i + '/' + p + '/take' + str(organized_nr).zfill(3) + '.wav')
   3429                         run_command(mv + '.jpeg ' + filmfolder + filmname + '/' + i + '/' + p + '/take' + str(organized_nr).zfill(3) + '.jpeg')
   3430                     #check if same video has both h246 and mp4 and render and remove h264
   3431                     for t in sorted(takes):
   3432                         if t.replace('.mp4','') == s.replace('.h264','') or s.replace('.mp4','') == t.replace('.h264',''):
   3433                             logger.info('Found both mp4 and h264 of same video!')
   3434                             logger.info(t)
   3435                             logger.info(s)
   3436                             #time.sleep(5)
   3437                             compileshot(takename,filmfolder,filmname)
   3438                             organized_nr -= 1
   3439                     organized_nr += 1
   3440         origin_files.extend(origin_scene_files)
   3441         with open(filmfolder+filmname+'/'+i+'/.origin_videos', 'w') as outfile:
   3442             outfile.write('\n'.join(str(i) for i in origin_scene_files))
   3443 
   3444     # Shots
   3445     for i in sorted(scenes):
   3446         shots = next(os.walk(filmfolder + filmname + '/' + i))[1]
   3447         if len(shots) == 0:
   3448             logger.info('no shots in this scene, removing scene..')
   3449             os.system('rm -r ' + filmfolder + filmname + '/' + i)
   3450         organized_nr = 1
   3451         for p in sorted(shots):
   3452             if 'insert' in p:
   3453                 #add_organize(filmfolder, filmname)
   3454                 pass
   3455             elif 'shot' in p:
   3456                 #print(p)
   3457                 unorganized_nr = int(p[-3:])
   3458                 if organized_nr == unorganized_nr:
   3459                     #print('correct')
   3460                     pass
   3461                 if organized_nr != unorganized_nr:
   3462                     #print('false, correcting from ' + str(unorganized_nr) + ' to ' + str(organized_nr))
   3463                     os.system('mv ' + filmfolder + filmname + '/' + i + '/shot' + str(unorganized_nr).zfill(3) + ' ' + filmfolder + filmname + '/' + i + '/shot' + str(organized_nr).zfill(3))
   3464                 organized_nr += 1
   3465 
   3466     # Scenes
   3467     organized_nr = 1
   3468     for i in sorted(scenes):
   3469         if 'insert' in i:
   3470             #add_organize(filmfolder, filmname)
   3471             pass
   3472         elif 'scene' in i:
   3473             #print(i)
   3474             unorganized_nr = int(i[-3:])
   3475             if organized_nr == unorganized_nr:
   3476                 #print('correct')
   3477                 pass
   3478             if organized_nr != unorganized_nr:
   3479                 #print('false, correcting from ' + str(unorganized_nr) + ' to ' + str(organized_nr))
   3480                 os.system('mv ' + filmfolder + filmname + '/scene' + str(unorganized_nr).zfill(3) + ' ' + filmfolder + filmname + '/scene' + str(organized_nr).zfill(3))
   3481             organized_nr += 1
   3482 
   3483     logger.info('Organizer done! Everything is tidy')
   3484     return origin_files
   3485 
   3486 
   3487 #------------Add and Organize----------------
   3488 
   3489 def add_organize(filmfolder, filmname):
   3490     scenes = next(os.walk(filmfolder + filmname))[1]
   3491     for i in scenes:
   3492         if 'scene' not in i:
   3493             scenes.remove(i)
   3494     # Shots
   3495     for i in sorted(scenes):
   3496         shots = next(os.walk(filmfolder + filmname + '/' + i))[1]
   3497         for c in shots:
   3498             if 'shot' not in c:
   3499                 shots.remove(c)
   3500         organized_nr = len(shots)
   3501         for p in sorted(shots, reverse=True):
   3502             if 'yanked' in p:
   3503                 #print(p)
   3504                 os.system('mv -n ' + filmfolder + filmname + '/' + i + '/shot' + str(organized_nr - 1).zfill(3) + '_yanked ' + filmfolder + filmname + '/' + i + '/shot' + str(organized_nr).zfill(3))
   3505             elif 'insert' in p:
   3506                 os.system('mv -n ' + filmfolder + filmname + '/' + i + '/shot' + str(organized_nr - 1).zfill(3) + '_insert ' + filmfolder + filmname + '/' + i + '/shot' + str(organized_nr).zfill(3))
   3507                 run_command('touch ' + filmfolder + filmname + '/' + i + '/shot' + str(organized_nr).zfill(3) + '/.placeholder')
   3508             elif 'shot' in p:
   3509                 #print(p)
   3510                 unorganized_nr = int(p[-3:])
   3511                 if organized_nr == unorganized_nr:
   3512                     #print('correct')
   3513                     pass
   3514                 if organized_nr != unorganized_nr:
   3515                     #print('false, correcting from ' + str(unorganized_nr) + ' to ' + str(organized_nr))
   3516                     os.system('mv -n ' + filmfolder + filmname + '/' + i + '/shot' + str(unorganized_nr).zfill(3) + ' ' + filmfolder + filmname + '/' + i + '/shot' + str(organized_nr).zfill(3)) 
   3517             organized_nr -= 1
   3518 
   3519     # Scenes
   3520     organized_nr = len(scenes)
   3521     for i in sorted(scenes, reverse=True):
   3522         #print(i)
   3523         if 'yanked' in i:
   3524             os.system('mv -n ' + filmfolder + filmname + '/scene' + str(organized_nr - 1).zfill(3) + '_yanked ' + filmfolder + filmname + '/scene' + str(organized_nr).zfill(3))
   3525         elif 'insert' in i:
   3526             #print(p)
   3527             os.system('mv -n ' + filmfolder + filmname + '/scene' + str(organized_nr - 1).zfill(3) + '_insert ' + filmfolder + filmname + '/scene' + str(organized_nr).zfill(3))
   3528             run_command('touch ' + filmfolder + filmname + '/scene' + str(organized_nr).zfill(3) + '/.placeholder')
   3529         elif 'scene' in i:
   3530             #print(i)
   3531             unorganized_nr = int(i[-3:])
   3532             if organized_nr == unorganized_nr:
   3533                 #print('correct')
   3534                 pass
   3535             if organized_nr != unorganized_nr:
   3536                 #print('false, correcting from ' + str(unorganized_nr) + ' to ' + str(organized_nr))
   3537                 os.system('mv -n ' + filmfolder + filmname + '/scene' + str(unorganized_nr).zfill(3) + ' ' + filmfolder + filmname + '/scene' + str(organized_nr).zfill(3))
   3538         organized_nr -= 1
   3539     return
   3540 
   3541 
   3542 #-------------Stretch Audio--------------
   3543 
   3544 def stretchaudio(filename,fps):
   3545     fps_rounded=round(fps)
   3546     if int(fps_rounded) != 25:
   3547         pipe = subprocess.check_output('mediainfo --Inform="Video;%Duration%" ' + filename + '.mp4', shell=True)
   3548         videolenght = pipe.decode().strip()
   3549         try:
   3550             pipe = subprocess.check_output('mediainfo --Inform="Audio;%Duration%" ' + filename + '.wav', shell=True)
   3551             audiolenght = pipe.decode().strip()
   3552         except:
   3553             audiosilence('',filename)
   3554             audiolenght=videolenght
   3555         #if there is no audio lenght
   3556         logger.info('audio is:' + audiolenght)
   3557         if not audiolenght.strip():
   3558             audiolenght = 0
   3559         ratio = int(audiolenght)/int(videolenght)
   3560         print(str(ratio))
   3561         run_command('cp '+filename+'.wav '+filename+'_temp.wav')
   3562         run_command('ffmpeg -y -i ' + filename + '_temp.wav -filter:a atempo="'+str(ratio) + '" ' + filename + '.wav')
   3563         os.remove(filename + '_temp.wav')
   3564     #time.sleep(5)
   3565     return
   3566 
   3567 #-------------Compile Shot--------------
   3568 
   3569 def compileshot(filename,filmfolder,filmname):
   3570     global fps, soundrate, channels
   3571     videolenght=0
   3572     audiolenght=0
   3573     #Check if file already converted
   3574     if '.h264' in filename:
   3575         filename=filename.replace('.h264','')
   3576     if '.mp4' in filename:
   3577         filename=filename.replace('.mp4','')
   3578     if os.path.isfile(filename + '.h264'):
   3579         logger.info('Video not converted!')
   3580         writemessage('Converting to playable video')
   3581         #remove old mp4 if corrupted like if an unpredicted shutdown in middle of converting
   3582         video_origins = (os.path.realpath(filename+'.h264'))[:-5]
   3583         os.system('rm ' + filename + '.mp4')
   3584         os.system('rm ' + video_origins + '.mp4')
   3585         print(filename+'.mp4 removed!')
   3586         run_command('MP4Box -fps 25 -add ' + video_origins + '.h264 ' + video_origins + '.mp4')
   3587         os.system('ln -sfr '+video_origins+'.mp4 '+filename+'.mp4')
   3588         if not os.path.isfile(filename + '.wav'):
   3589             audiosilence('',filename)
   3590         #add audio/video start delay sync
   3591         run_command('sox -V0 '+filename+'.wav -c 2 /dev/shm/temp.wav trim 0.013')
   3592         run_command('mv /dev/shm/temp.wav '+ filename + '.wav')
   3593         stretchaudio(filename,fps)
   3594         audiosync, videolenght, audiolenght = audiotrim(filename, 'end','')
   3595         muxing = True
   3596         if muxing == True:
   3597             #muxing mp3 layer to mp4 file
   3598             #count estimated audio filesize with a bitrate of 320 kb/s
   3599             audiosize = countsize(filename + '.wav') * 0.453
   3600             p = Popen(['ffmpeg', '-y', '-i', filename + '.wav', '-acodec', 'libmp3lame', '-ac', '2', '-b:a', '320k', filename + '.mp3'])
   3601             while p.poll() is None:
   3602                 time.sleep(0.2)
   3603                 try:
   3604                     rendersize = countsize(filename + '.mp3')
   3605                 except:
   3606                     continue
   3607                 writemessage('audio rendering ' + str(int(rendersize)) + ' of ' + str(int(audiosize)) + ' kb done')
   3608             ##MERGE AUDIO & VIDEO
   3609             writemessage('Merging audio & video')
   3610             #os.remove(renderfilename + '.mp4') 
   3611             call(['MP4Box', '-rem', '2',  video_origins + '.mp4'], shell=False)
   3612             call(['MP4Box', '-fps', '25', '-add', video_origins + '.mp4', '-add', filename + '.mp3', '-new', video_origins + '_tmp.mp4'], shell=False)
   3613             os.system('cp -f ' + video_origins + '_tmp.mp4 ' + video_origins + '.mp4')
   3614             os.remove(video_origins + '_tmp.mp4')
   3615             os.remove(filename + '.mp3')
   3616         origin=os.path.realpath(filename+'.mp4')
   3617         db.update('videos', where='filename="'+origin+'"', videolenght=videolenght/1000, audiolenght=audiolenght/1000, audiosync=audiosync)
   3618         os.system('rm ' + video_origins + '.h264')
   3619         os.system('rm ' + filename + '.h264')
   3620         os.system('rm /dev/shm/temp.wav')
   3621         os.system('ln -sfr '+video_origins+'.mp4 '+filename+'.mp4')
   3622         logger.info('compile done!')
   3623         #run_command('omxplayer --layer 3 ' + filmfolder + '/.rendered/' + filename + '.mp4 &')
   3624         #time.sleep(0.8)
   3625         #run_command('aplay ' + foldername + filename + '.wav')
   3626     return
   3627 
   3628 #-------------Get shot files--------------
   3629 
   3630 def shotfiles(filmfolder, filmname, scene):
   3631     files = []
   3632     shots = countshots(filmname,filmfolder,scene)
   3633     print("shots"+str(shots))
   3634     shot = 1
   3635     for i in range(shots):
   3636         takes = counttakes(filmname,filmfolder,scene,shot)
   3637         if takes > 0:
   3638             folder = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/'
   3639             filename = 'take' + str(takes).zfill(3)
   3640             files.append(folder + filename)
   3641             print(folder+filename)
   3642         shot = shot + 1
   3643     #writemessage(str(len(shotfiles)))
   3644     #time.sleep(2)
   3645     return files
   3646 
   3647 #--------Show JPEG as progress when rendering
   3648 
   3649 #---------------Render Video------------------
   3650 
   3651 def rendervideo(filmfiles, filename, renderinfo):
   3652     if len(filmfiles) < 1:
   3653         writemessage('Nothing here!')
   3654         time.sleep(2)
   3655         return None
   3656     print('Rendering videofiles')
   3657     writemessage('Hold on, rendering ' + renderinfo + ' with ' + str(len(filmfiles)) + ' files')
   3658     videosize = 0
   3659     rendersize = 0
   3660     videomerge = ['MP4Box']
   3661     videomerge.append('-force-cat')
   3662     for f in filmfiles[:]:
   3663         videosize = videosize + countsize(f + '.mp4')
   3664         videomerge.append('-cat')
   3665         videomerge.append(f + '.mp4#video')
   3666     videomerge.append('-new')
   3667     videomerge.append(filename + '.mp4')
   3668     #videomerge.append(filename + '.h264')
   3669     #call(videomerge, shell=True) #how to insert somekind of estimated time while it does this?
   3670     p = Popen(videomerge)
   3671     #show progress
   3672     while p.poll() is None:
   3673         time.sleep(0.1)
   3674         try:
   3675             rendersize = countsize(filename + '.mp4')
   3676         except:
   3677             continue
   3678         writemessage('video rendering ' + str(int(rendersize)) + ' of ' + str(int(videosize)) + ' kb done')
   3679     print('Video rendered!')
   3680     return
   3681 
   3682 #---------------Render Audio----------------
   3683 
   3684 def renderaudio(audiofiles, filename, dubfiles, dubmix):
   3685     #if len(audiofiles) < 1:
   3686     #    writemessage('Nothing here!')
   3687     #    time.sleep(2)
   3688     #    return None
   3689     print('Rendering audiofiles')
   3690     ##PASTE AUDIO TOGETHER
   3691     writemessage('Hold on, rendering audio...')
   3692     audiomerge = ['sox']
   3693     #if render > 2:
   3694     #    audiomerge.append(filename + '.wav')
   3695     if isinstance(audiofiles, list):
   3696         for f in audiofiles:
   3697             audiomerge.append(f + '.wav')
   3698         audiomerge.append(filename + '.wav')
   3699         call(audiomerge, shell=False)
   3700     else:
   3701         #if rendering scene with one shot
   3702         if audiofiles[0] != filename:
   3703             os.system('cp '+audiofiles[0]+'.wav '+filename+'.wav')
   3704     #DUBBING
   3705     p = 1
   3706     pipe = subprocess.check_output('mediainfo --Inform="Video;%Duration%" ' + filename + '.mp4', shell=True)
   3707     videolenght = pipe.decode().strip()
   3708     audiolenght=videolenght
   3709     for i, d in zip(dubmix, dubfiles):
   3710         writemessage('Dub ' + str(p) + ' audio found lets mix...')
   3711         #first trimit!
   3712         audiotrim(filename, 'end', d)
   3713         try:
   3714             pipe = subprocess.check_output('soxi -D ' + d, shell=True)
   3715             dubaudiolenght = pipe.decode()
   3716             if dubaudiolengt != videolenght:
   3717                 print('dub wrong lenght!')
   3718                 time.sleep(5)
   3719         except:
   3720             pass
   3721         os.system('cp ' + filename + '.wav ' + filename + '_tmp.wav')
   3722         #Fade and make stereo
   3723         run_command('sox -V0 -G ' + d + ' /dev/shm/fade.wav fade ' + str(round(i[2],1)) + ' 0 ' + str(round(i[3],1)))
   3724         run_command('sox -V0 -G -m -v ' + str(round(i[0],1)) + ' /dev/shm/fade.wav -v ' + str(round(i[1],1)) + ' ' + filename + '_tmp.wav ' + filename + '.wav trim 0 ' + audiolenght)
   3725         try:
   3726             os.remove(filename + '_tmp.wav')
   3727             os.remove('/dev/shm/fade.wav')
   3728         except:
   3729             pass
   3730         print('Dub mix ' + str(p) + ' done!')
   3731         p += 1
   3732     return
   3733 
   3734 #-------------Fast Edit-----------------
   3735 def fastedit(filmfolder, filmname, filmfiles, scene):
   3736     scenedir = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/'
   3737     totlenght = 0
   3738     try:
   3739         os.remove(scenedir + '.fastedit')
   3740     except:
   3741         print('no fastedit file')
   3742     #for f in filmfiles:
   3743         #pipe = subprocess.check_output('mediainfo --Inform="Video;%Duration%" ' + f + '.mp4', shell=True)
   3744         #videolenght = pipe.decode().strip()
   3745         #totlenght = int(videolenght) + totlenght
   3746         #print('writing shot lenghts for fastedit mode')
   3747         #with open(scenedir + '.fastedit', 'a') as f:
   3748         #    f.write(str(totlenght)+'\n')
   3749     
   3750 
   3751 #-------------Get scene files--------------
   3752 
   3753 def scenefiles(filmfolder, filmname):
   3754     files = []
   3755     scenes = countscenes(filmfolder,filmname)
   3756     scene = 1
   3757     while scene <= scenes:
   3758         folder = filmfolder + filmname + '/' + 'scene' + str(scene).zfill(3) + '/'
   3759         filename = 'scene'
   3760         files.append(folder + filename)
   3761         scene = scene + 1
   3762     #writemessage(str(len(shotfiles)))
   3763     #time.sleep(2)
   3764     return files
   3765 
   3766 #-------------Render Shot-------------
   3767 
   3768 def rendershot(filmfolder, filmname, renderfilename, scene, shot):
   3769     global fps
   3770     #This function checks and calls rendervideo & renderaudio if something has changed in the film
   3771     #Video
   3772     def render(q, filmfolder, filmname, renderfilename, scene, shot):
   3773         videohash = ''
   3774         oldvideohash = ''
   3775         scenedir = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/'
   3776         #return if no file
   3777         # Video Hash
   3778         if os.path.isfile(renderfilename + '.h264') == True:
   3779             compileshot(renderfilename,filmfolder,filmname)
   3780             audiohash = str(int(countsize(renderfilename + '.wav')))
   3781             with open(scenedir + '.audiohash', 'w') as f:
   3782                 f.write(audiohash)
   3783         #if something shutdown in middle of process
   3784         elif os.path.isfile(renderfilename + '_tmp.mp4') == True:
   3785             os.system('cp ' + renderfilename + '_tmp.mp4 ' + renderfilename + '.mp4')
   3786         elif os.path.isfile(renderfilename + '.mp4') == True:
   3787             videohash = videohash + str(int(countsize(renderfilename + '.mp4')))
   3788             video_origins = (os.path.realpath(renderfilename+'.mp4'))[:-4]
   3789             print('Videohash of shot is: ' + videohash)
   3790             #time.sleep(3)
   3791         else:
   3792             vumetermessage('Nothing here to play hit record')
   3793             status='',''
   3794             q.put(status)
   3795         #if os.path.isfile(renderfilename + '.h264') and os.path.isfile(renderfilename + '.mp4'):
   3796         #    os.system('rm ' + renderfilename + '.h264 ')
   3797         # Check if video corrupt
   3798         renderfix = False
   3799         if os.path.isfile(renderfilename + '.jpeg') == False: 
   3800             run_command('ffmpeg -sseof -1 -i ' + renderfilename + '.mp4 -update 1 -q:v 1 -vf scale=800:450 ' + renderfilename + '.jpeg')
   3801         #try:
   3802         #    pipe = subprocess.check_output('mediainfo --Inform="Video;%Duration%" ' + renderfilename + '.mp4', shell=True)
   3803         #    videolenght = pipe.decode().strip()
   3804         #except:
   3805         #    videolenght = ''
   3806         #print('Shot lenght ' + videolenght)
   3807         #if videolenght == '':
   3808         #    print('Okey, shot file not found or is corrupted')
   3809         #    # For backwards compatibility remove old rendered scene files
   3810         #    # run_command('rm ' + renderfilename + '*')
   3811         #    status='',''
   3812         #    q.put(status)
   3813         try:
   3814             with open(scenedir + '.videohash', 'r') as f:
   3815                 oldvideohash = f.readline().strip()
   3816             print('oldvideohash is: ' + oldvideohash)
   3817         except:
   3818             print('no videohash found, making one...')
   3819             with open(scenedir + '.videohash', 'w') as f:
   3820                 f.write(videohash)
   3821         #Audio
   3822         lasttake = counttakes(filmname, filmfolder, scene, shot)
   3823         lasttakefilename = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/take' + str(lasttake).zfill(3) 
   3824         audiohash = ''
   3825         oldaudiohash = ''
   3826         newaudiomix = False
   3827         if lasttakefilename == renderfilename:
   3828             audiohash += str(int(countsize(renderfilename + '.wav')))
   3829             dubfiles, dubmix, newmix = getdubs(filmfolder, filmname, scene, shot)
   3830             for p in dubfiles:
   3831                 audiohash += str(int(countsize(p)))
   3832             print('Audiohash of shot is: ' + audiohash)
   3833             try:
   3834                 with open(scenedir + '.audiohash', 'r') as f:
   3835                     oldaudiohash = f.readline().strip()
   3836                 print('oldaudiohash is: ' + oldaudiohash)
   3837             except:
   3838                 print('no audiohash found, making one...')
   3839                 with open(scenedir + '.audiohash', 'w') as f:
   3840                     f.write(audiohash)
   3841             if audiohash != oldaudiohash or newmix == True or renderfix == True:
   3842                 print('rerendering')
   3843                 #time.sleep(3)
   3844                 #make scene rerender
   3845                 os.system('touch '+filmfolder + filmname + '/scene' + str(scene).zfill(3)+'/.rerender')
   3846                 #copy original sound
   3847                 if os.path.exists(scenedir+'dub') == True:
   3848                     os.system('cp '+scenedir+'dub/original.wav '+renderfilename+'.wav')
   3849                 #os.system('cp '+dubfolder+'original.wav '+renderfilename+'.wav')
   3850                 renderaudio(renderfilename, renderfilename, dubfiles, dubmix)
   3851                 print('updating audiohash...')
   3852                 with open(scenedir + '.audiohash', 'w') as f:
   3853                     f.write(audiohash)
   3854                 for i in range(len(dubfiles)):
   3855                     os.system('cp ' + scenedir + '/dub/.settings' + str(i + 1).zfill(3) + ' ' + scenedir + '/dub/.rendered' + str(i + 1).zfill(3))
   3856                 print('Audio rendered!')
   3857                 newaudiomix = True
   3858                 muxing = True
   3859                 if muxing == True:
   3860                     #muxing mp3 layer to mp4 file
   3861                     #count estimated audio filesize with a bitrate of 320 kb/s
   3862                     audiosize = countsize(renderfilename + '.wav') * 0.453
   3863                     p = Popen(['ffmpeg', '-y', '-i', renderfilename + '.wav', '-acodec', 'libmp3lame', '-ac', '2', '-b:a', '320k', renderfilename + '.mp3'])
   3864                     while p.poll() is None:
   3865                         time.sleep(0.2)
   3866                         try:
   3867                             rendersize = countsize(renderfilename + '.mp3')
   3868                         except:
   3869                             continue
   3870                         writemessage('audio rendering ' + str(int(rendersize)) + ' of ' + str(int(audiosize)) + ' kb done')
   3871                     ##MERGE AUDIO & VIDEO
   3872                     writemessage('Merging audio & video')
   3873                     #os.remove(renderfilename + '.mp4') 
   3874                     call(['MP4Box', '-rem', '2',  video_origins + '.mp4'], shell=False)
   3875                     call(['MP4Box', '-fps', '25', '-add', video_origins + '.mp4', '-add', renderfilename + '.mp3', '-new', video_origins + '_tmp.mp4'], shell=False)
   3876                     os.system('cp -f ' + video_origins + '_tmp.mp4 ' + video_origins + '.mp4')
   3877                     try:
   3878                         os.remove(video_origins + '_tmp.mp4')
   3879                         os.remove(renderfilename + '.mp3')
   3880                     except:
   3881                         print('nothing to remove')
   3882                 #origin=os.path.realpath(renderfilename+'.mp4')
   3883                 #os.system('rm ' + filename + '.h264')
   3884                 #os.system('rm /dev/shm/temp.wav')
   3885                 #os.system('ln -sfr '+video_origins+'.mp4 '+filename+'.mp4')
   3886                 logger.info('compile done!')
   3887             else:
   3888                 print('Already rendered!')
   3889         status=renderfilename,newaudiomix
   3890         q.put(status)
   3891     q = mp.Queue()
   3892     proc = mp.Process(target=render, args=(q, filmfolder, filmname, renderfilename, scene, shot))
   3893     proc.start()
   3894     procdone = False
   3895     status = ''
   3896     while True:
   3897         if proc.is_alive() == False and procdone == False:
   3898             status = q.get()
   3899             print(status)
   3900             procdone = True
   3901             proc.join()
   3902             renderfilename,newaudiomix = status
   3903             vumetermessage(renderfilename+'.mp4')
   3904             break
   3905         if middlebutton() == True:
   3906             proc.terminate()
   3907             proc.join()
   3908             procdone = True
   3909             q=''
   3910             os.system('pkill MP4Box')
   3911             vumetermessage('canceled for now, maybe u want to render later ;)')
   3912             writemessage('press any button to continue')
   3913             print('canceling videorender')
   3914             renderfilename = ''
   3915             newaudiomix=''
   3916             break
   3917     return renderfilename, newaudiomix
   3918 
   3919 #-------------Render Scene-------------
   3920 
   3921 def renderscene(filmfolder, filmname, scene):
   3922     global fps
   3923     #This function checks and calls rendervideo & renderaudio if something has changed in the film
   3924     #Video
   3925     videohash = ''
   3926     oldvideohash = ''
   3927     filmfiles = shotfiles(filmfolder, filmname, scene)
   3928     renderfilename = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/scene'
   3929     scenedir = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/'
   3930     # Check if video corrupt
   3931     renderfixscene = False
   3932     #try:
   3933     #    pipe = subprocess.check_output('mediainfo --Inform="Video;%Duration%" ' + renderfilename + '.mp4', shell=True)
   3934     #    videolenght = pipe.decode().strip()
   3935     #except:
   3936     #    videolenght = ''
   3937     #    renderfixscene = True
   3938     #print('Scene lenght ' + videolenght)
   3939     #if videolenght == '':
   3940     #    print('Okey, hold your horses, rendering!')
   3941     #    # For backwards compatibility remove old rendered scene files
   3942     #    #run_command('rm ' + renderfilename + '.mp4')
   3943     #    #run_command('rm ' + renderfilename + '.wav')
   3944     #    #vumetermessage('corrupted scene file! removing, please render again')
   3945     #    renderfixscene = True
   3946     #    #return '', ''
   3947     # Video Hash
   3948     for p in filmfiles:
   3949         #compileshot(p,filmfolder,filmname)
   3950         #print(p)
   3951         #time.sleep(5)
   3952         scene = int(p.rsplit('scene',1)[1][:3])
   3953         shot = int(p.rsplit('shot',1)[1][:3])
   3954         rendershotname, renderfix = rendershot(filmfolder, filmname, p, scene, shot)
   3955         if renderfix == True:
   3956             renderfixscene = True
   3957         if rendershotname:
   3958             try: 
   3959                 videohash = videohash + str(int(countsize(p + '.mp4')))
   3960             except:
   3961                 print('no file? ')
   3962     print('Videohash of scene is: ' + videohash)
   3963     try:
   3964         with open(scenedir + '.videohash', 'r') as f:
   3965             oldvideohash = f.readline().strip()
   3966         print('oldvideohash is: ' + oldvideohash)
   3967     except:
   3968         print('no videohash found, making one...')
   3969         with open(scenedir + '.videohash', 'w') as f:
   3970             f.write(videohash)
   3971 
   3972     print('renderfix is:'+str(renderfixscene))
   3973     # Render if needed
   3974     if videohash != oldvideohash or renderfixscene == True:
   3975         rendervideo(filmfiles, renderfilename, 'scene ' + str(scene))
   3976         fastedit(filmfolder, filmname, filmfiles, scene)
   3977         print('updating videohash...')
   3978         with open(scenedir + '.videohash', 'w') as f:
   3979             f.write(videohash)
   3980     #time.sleep(3)
   3981 
   3982     #Audio
   3983     audiohash = ''
   3984     oldaudiohash = ''
   3985     newaudiomix = False
   3986     for p in filmfiles:
   3987         try:
   3988             audiohash += str(int(countsize(p + '.wav')))
   3989         except:
   3990             audiohash=0
   3991             renderfix=True
   3992     dubfiles, dubmix, newmix = getdubs(filmfolder, filmname, scene, 0)
   3993     for p in dubfiles:
   3994         try:
   3995             audiohash += str(int(countsize(p)))
   3996         except:
   3997             audiohash=0
   3998     print('Audiohash of scene is: ' + audiohash)
   3999     try:
   4000         with open(scenedir + '.audiohash', 'r') as f:
   4001             oldaudiohash = f.readline().strip()
   4002         print('oldaudiohash is: ' + oldaudiohash)
   4003     except:
   4004         print('no audiohash found, making one...')
   4005         with open(scenedir + '.audiohash', 'w') as f:
   4006             f.write(audiohash) 
   4007         renderfixscene=True
   4008     if os.path.isfile(scenedir+'/.rerender') == True:
   4009         renderfixscene=True
   4010         os.system('rm '+scenedir+'/.rerender')
   4011     if audiohash != oldaudiohash or newmix == True or renderfix == True or renderfixscene == True:
   4012         renderaudio(filmfiles, renderfilename, dubfiles, dubmix)
   4013         print('updating audiohash...')
   4014         with open(scenedir + '.audiohash', 'w') as f:
   4015             f.write(audiohash)
   4016         for i in range(len(dubfiles)):
   4017             os.system('cp ' + scenedir + '/dub/.settings' + str(i + 1).zfill(3) + ' ' + scenedir + '/dub/.rendered' + str(i + 1).zfill(3))
   4018         print('Audio rendered!')
   4019         newaudiomix = True
   4020         muxing = True
   4021         if muxing == True:
   4022             #muxing mp3 layer to mp4 file
   4023             #count estimated audio filesize with a bitrate of 320 kb/s
   4024             try:
   4025                 audiosize = countsize(renderfilename + '.wav') * 0.453
   4026             except:
   4027                 print('noothing here')
   4028             os.system('mv ' + renderfilename + '.mp4 ' + renderfilename + '_tmp.mp4')
   4029             if debianversion == 'stretch':
   4030                 p = Popen(['avconv', '-y', '-i', renderfilename + '.wav', '-acodec', 'libmp3lame', '-ac', '2', '-b:a', '320k', renderfilename + '.mp3'])
   4031             else:
   4032                 p = Popen(['ffmpeg', '-y', '-i', renderfilename + '.wav', '-acodec', 'libmp3lame', '-ac', '2', '-b:a', '320k', renderfilename + '.mp3'])
   4033             while p.poll() is None:
   4034                 time.sleep(0.02)
   4035                 try:
   4036                     rendersize = countsize(renderfilename + '.mp3')
   4037                 except:
   4038                     continue
   4039                 writemessage('audio rendering ' + str(int(rendersize)) + ' of ' + str(int(audiosize)) + ' kb done')
   4040             ##MERGE AUDIO & VIDEO
   4041             writemessage('Merging audio & video')
   4042             #os.remove(renderfilename + '.mp4') 
   4043             call(['MP4Box', '-rem', '2',  renderfilename + '_tmp.mp4'], shell=False)
   4044             call(['MP4Box', '-add', renderfilename + '_tmp.mp4', '-add', renderfilename + '.mp3', '-new', renderfilename + '.mp4'], shell=False)
   4045             os.remove(renderfilename + '_tmp.mp4')
   4046             os.remove(renderfilename + '.mp3')
   4047     else:
   4048         print('Already rendered!')
   4049     return renderfilename, newaudiomix
   4050 
   4051 #-------------Render film------------
   4052 
   4053 def renderfilm(filmfolder, filmname, comp, scene, muxing):
   4054     global fps
   4055     def render(q, filmfolder, filmname, comp, scene, muxing):
   4056         newaudiomix = False
   4057         #if comp == 1:
   4058         #    newaudiomix = True
   4059         #This function checks and calls renderscene first then rendervideo & renderaudio if something has changed in the film
   4060         if scene > 0:
   4061             scenefilename, audiomix = renderscene(filmfolder, filmname, scene)
   4062             q.put(scenefilename)
   4063             return
   4064         scenes = countscenes(filmfolder, filmname)
   4065         for i in range(scenes):
   4066             scenefilename, audiomix = renderscene(filmfolder, filmname, i + 1)
   4067             #Check if a scene has a new audiomix
   4068             print('audiomix of scene ' + str(i + 1) + ' is ' + str(audiomix))
   4069             if audiomix == True:
   4070                 newaudiomix = True
   4071         filmfiles = scenefiles(filmfolder, filmname)
   4072         #Video
   4073         videohash = ''
   4074         oldvideohash = ''
   4075         renderfilename = filmfolder + filmname + '/' + filmname
   4076         filmdir = filmfolder + filmname + '/'
   4077         scenedir = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/'
   4078         for p in filmfiles:
   4079             print(p)
   4080             #compileshot(p,filmfolder,filmname)
   4081             videohash += str(int(countsize(p + '.mp4')))
   4082         print('Videohash of film is: ' + videohash)
   4083         try:
   4084             with open(filmdir + '.videohash', 'r') as f:
   4085                 oldvideohash = f.readline().strip()
   4086             print('oldvideohash is: ' + oldvideohash)
   4087         except:
   4088             print('no videohash found, making one...')
   4089             with open(filmdir + '.videohash', 'w') as f:
   4090                 f.write(videohash)
   4091         if videohash != oldvideohash:
   4092             rendervideo(filmfiles, renderfilename, filmname)
   4093             print('updating video hash')
   4094             with open(filmdir + '.videohash', 'w') as f:
   4095                 f.write(videohash)
   4096         #Audio
   4097         audiohash = ''
   4098         oldaudiohash = ''
   4099         for p in filmfiles:
   4100             print(p)
   4101             audiohash += str(int(countsize(p + '.wav')))
   4102         dubfiles, dubmix, newmix = getdubs(filmfolder, filmname, 0, 0)
   4103         for p in dubfiles:
   4104             audiohash += str(int(countsize(p)))
   4105         print('Audiohash of film is: ' + audiohash)
   4106         try:
   4107             with open(filmdir + '.audiohash', 'r') as f:
   4108                 oldaudiohash = f.readline().strip()
   4109             print('oldaudiohash is: ' + oldaudiohash)
   4110         except:
   4111             print('no audiohash found, making one...')
   4112             with open(filmdir+ '.audiohash', 'w') as f:
   4113                 f.write(audiohash)
   4114         #This is if the scene has a new audiomix
   4115         if newaudiomix == True:
   4116             newmix = True
   4117         if audiohash != oldaudiohash or newmix == True:
   4118             renderaudio(filmfiles, renderfilename, dubfiles, dubmix)
   4119             print('updating audiohash...')
   4120             with open(filmdir+ '.audiohash', 'w') as f:
   4121                 f.write(audiohash)
   4122             for i in range(len(dubfiles)):
   4123                 os.system('cp ' + filmdir + '/dub/.settings' + str(i + 1).zfill(3) + ' ' + filmdir + '/dub/.rendered' + str(i + 1).zfill(3))
   4124             print('Audio rendered!')
   4125             #compressing
   4126             if comp > 0:
   4127                 writemessage('compressing audio')
   4128                 os.system('mv ' + renderfilename + '.wav ' + renderfilename + '_tmp.wav')
   4129                 #run_command('sox ' + renderfilename + '_tmp.wav ' + renderfilename + '.wav compand 0.3,1 6:-70,-60,-20 -5 -90 0.2')
   4130                 run_command('sox ' + renderfilename + '_tmp.wav ' + renderfilename + '.wav compand 0.0,1 6:-70,-43,-20 -6 -90 0.1')
   4131                 os.remove(renderfilename + '_tmp.wav')
   4132             if muxing == True:
   4133                 #muxing mp3 layer to mp4 file
   4134                 #count estimated audio filesize with a bitrate of 320 kb/s
   4135                 audiosize = countsize(renderfilename + '.wav') * 0.453
   4136                 os.system('mv ' + renderfilename + '.mp4 ' + renderfilename + '_tmp.mp4')
   4137                 if debianversion == 'stretch':
   4138                     p = Popen(['avconv', '-y', '-i', renderfilename + '.wav', '-acodec', 'libmp3lame', '-ac', '2', '-b:a', '320k', renderfilename + '.mp3'])
   4139                 else:
   4140                     p = Popen(['ffmpeg', '-y', '-i', renderfilename + '.wav', '-acodec', 'libmp3lame', '-ac', '2', '-b:a', '320k', renderfilename + '.mp3'])
   4141                 while p.poll() is None:
   4142                     time.sleep(0.02)
   4143                     try:
   4144                         rendersize = countsize(renderfilename + '.mp3')
   4145                     except:
   4146                         continue
   4147                     writemessage('audio rendering ' + str(int(rendersize)) + ' of ' + str(int(audiosize)) + ' kb done')
   4148                 ##MERGE AUDIO & VIDEO
   4149                 writemessage('Merging audio & video')
   4150                 #os.remove(renderfilename + '.mp4') 
   4151                 call(['MP4Box', '-rem', '2',  renderfilename + '_tmp.mp4'], shell=False)
   4152                 call(['MP4Box', '-add', renderfilename + '_tmp.mp4', '-add', renderfilename + '.mp3', '-new', renderfilename + '.mp4'], shell=False)
   4153                 #call(['MP4Box', '-inter', '500', renderfilename + '.mp4'], shell=False)
   4154                 os.remove(renderfilename + '_tmp.mp4')
   4155                 os.remove(renderfilename + '.mp3')
   4156         else:
   4157             print('Already rendered!')
   4158         q.put(renderfilename)
   4159     q = mp.Queue()
   4160     proc = mp.Process(target=render, args=(q,filmfolder,filmname,comp,scene,muxing))
   4161     proc.start()
   4162     procdone = False
   4163     status = ''
   4164     while True:
   4165         if proc.is_alive() == False and procdone == False:
   4166             status = q.get()
   4167             print(status)
   4168             procdone = True
   4169             proc.join()
   4170             renderfilename = status
   4171             vumetermessage(status+'.mp4')
   4172             break
   4173         if middlebutton() == True:
   4174             proc.terminate()
   4175             proc.join()
   4176             procdone = True
   4177             q=''
   4178             os.system('pkill MP4Box')
   4179             vumetermessage('canceled for now, maybe u want to render later ;)')
   4180             writemessage('press any button to continue')
   4181             print('canceling videorender')
   4182             renderfilename = ''
   4183             break
   4184     return renderfilename
   4185 
   4186 #-------------Get dub files-----------
   4187 
   4188 def getdubs(filmfolder, filmname, scene, shot):
   4189     #search for dub files
   4190     print('getting scene dubs')
   4191     dubfiles = []
   4192     dubmix = []
   4193     rerender = False
   4194     if filmname == None and scene == None and shot == None:
   4195         filefolder = filmfolder
   4196     elif scene > 0 and shot == 0:
   4197         filefolder = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/dub/'
   4198     elif scene > 0 and shot > 0:
   4199         filefolder = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/dub/'
   4200     else:
   4201         filefolder = filmfolder + filmname + '/dub/'
   4202     try:
   4203         allfiles = os.listdir(filefolder)
   4204     except:
   4205         print('no dubs')
   4206         return dubfiles, dubmix, rerender
   4207     for a in allfiles:
   4208         if 'dub' in a:
   4209             print('Dub audio found! ' + filefolder + a)
   4210             dubfiles.append(filefolder + a)
   4211     #check if dub mix has changed
   4212     dubnr = 1
   4213     for i in dubfiles:
   4214         dub = []
   4215         rendered_dub = []
   4216         try:
   4217             with open(filefolder + '.settings' + str(dubnr).zfill(3), 'r') as f:
   4218                 dubstr = f.read().splitlines()
   4219             for i in dubstr:
   4220                 dub.append(float(i))
   4221             print('dub ' + str(dubnr).zfill(3) + ' loaded!')
   4222             print(dub)
   4223         except:
   4224             print('cant find settings file')
   4225             dub = [1.0, 1.0, 0.0, 0.0]
   4226             with open(filefolder + ".settings" + str(dubnr).zfill(3), "w") as f:
   4227                 for i in dub:
   4228                     f.write(str(i) + '\n')
   4229         try:
   4230             with open(filefolder + '.rendered' + str(dubnr).zfill(3), 'r') as f:
   4231                 dubstr = f.read().splitlines()
   4232             for i in dubstr:
   4233                 rendered_dub.append(float(i))
   4234             print('rendered dub loaded')
   4235             print(rendered_dub)
   4236         except:
   4237             print('no rendered dubmix found!')
   4238         if rendered_dub != dub:
   4239             rerender = True
   4240         dubmix.append(dub)
   4241         dubnr += 1
   4242     return dubfiles, dubmix, rerender
   4243 
   4244 #------------Remove Dubs----------------
   4245 
   4246 def removedub(dubfolder, dubnr):
   4247     pressed = ''
   4248     buttonpressed = ''
   4249     buttontime = time.time()
   4250     holdbutton = ''
   4251     selected = 0
   4252     header = 'Are you sure you want to remove dub ' + str(dubnr) + '?'
   4253     menu = 'NO', 'YES'
   4254     settings = '', ''
   4255     while True:
   4256         writemenu(menu,settings,selected,header,showmenu)
   4257         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   4258         if pressed == 'right':
   4259             if selected < (len(menu) - 1):
   4260                 selected = selected + 1
   4261         elif pressed == 'left':
   4262             if selected > 0:
   4263                 selected = selected - 1
   4264         elif pressed == 'middle' and selected == 0:
   4265             logger.info('dont remove dub')
   4266             time.sleep(0.3)
   4267             break
   4268         elif pressed == 'middle' and selected == 1: 
   4269             os.system('rm ' + dubfolder + 'dub' + str(dubnr).zfill(3) + '.wav')
   4270             os.system('rm ' + dubfolder + '.settings' + str(dubnr).zfill(3))
   4271             os.system('rm ' + dubfolder + '.rendered' + str(dubnr).zfill(3))
   4272             time.sleep(0.5)
   4273             print(dubfolder)
   4274             dubs = next(os.walk(dubfolder))[2]
   4275             print(dubs)
   4276             for i in dubs:
   4277                 if 'dub' not in i:
   4278                     dubs.remove(i)
   4279             organized_nr = 1
   4280             for s in sorted(dubs):
   4281                 if '.wav' in s and 'dub' in s:
   4282                     print(s)
   4283                     unorganized_nr = int(s[3:-4])
   4284                     if organized_nr == unorganized_nr:
   4285                         print('correct')
   4286                         pass
   4287                     if organized_nr != unorganized_nr:
   4288                         print('false, correcting from ' + str(unorganized_nr) + ' to ' + str(organized_nr))
   4289                         run_command('mv ' + dubfolder + 'dub' + str(unorganized_nr).zfill(3) + '.wav ' + dubfolder + 'dub' + str(organized_nr).zfill(3) + '.wav')
   4290                         run_command('mv ' + dubfolder + '.settings' + str(unorganized_nr).zfill(3) + ' ' + dubfolder + '.settings' + str(organized_nr).zfill(3))
   4291                         run_command('mv ' + dubfolder + '.rendered' + str(unorganized_nr).zfill(3) + ' ' + dubfolder + '.rendered' + str(organized_nr).zfill(3))
   4292                     organized_nr += 1
   4293             logger.info('removed dub file!')
   4294             vumetermessage('dub removed!')
   4295             break
   4296         time.sleep(0.05)
   4297 
   4298 #-------------Clip settings---------------
   4299 
   4300 def clipsettings(filmfolder, filmname, scene, shot, take, plughw):
   4301     vumetermessage('press record, view or retake to be dubbing')
   4302     pressed = ''
   4303     buttonpressed = ''
   4304     buttontime = time.time()
   4305     holdbutton = ''
   4306     selected = 0
   4307     dubfiles = []
   4308     dubmix = []
   4309     dubmix_old = []
   4310     if scene > 0 and shot == 0:
   4311         header = 'Scene ' + str(scene) + ' dubbing settings'
   4312         filefolder = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/dub/'
   4313         dubfiles, dubmix, newmix = getdubs(filmfolder, filmname, scene, 0)
   4314     elif scene > 0 and shot > 0:
   4315         header = 'Scene ' + str(scene) + ' shot ' + str(shot) + ' dubbing settings'
   4316         filefolder = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/dub/'
   4317         dubfiles, dubmix, newmix = getdubs(filmfolder, filmname, scene, shot)
   4318     else:
   4319         header = 'Film ' + filmname + ' dubbing settings'
   4320         filefolder = filmfolder + filmname + '/dub/'
   4321         dubfiles, dubmix, newmix = getdubs(filmfolder, filmname, 0, 0)
   4322     newdub = [1.0, 1.0, 0.1, 0.1]
   4323     dubselected = len(dubfiles) - 1
   4324     dubrecord = ''
   4325     while True:
   4326         nmix = round(newdub[0],1)
   4327         ndub = round(newdub[1],1)
   4328         nfadein = round(newdub[2],1)
   4329         nfadeout = round(newdub[3],1)
   4330         if dubfiles:
   4331             mix = round(dubmix[dubselected][0],1)
   4332             dub = round(dubmix[dubselected][1],1)
   4333             fadein = round(dubmix[dubselected][2],1)
   4334             fadeout = round(dubmix[dubselected][3],1)
   4335             menu = 'BACK', 'ADD:', '', '', 'DUB' + str(dubselected + 1) + ':', '', '', ''
   4336             settings = '', 'd:' + str(nmix) + '/o:' + str(ndub), 'in:' + str(nfadein), 'out:' + str(nfadeout), '', 'd:' + str(mix) + '/o' + str(dub), 'in:' + str(fadein), 'out:' + str(fadeout)
   4337         else:
   4338             menu = 'BACK', 'ADD:', '', ''
   4339             settings = '', 'd:' + str(nmix) + '/o:' + str(ndub), 'in:' + str(nfadein), 'out:' + str(nfadeout)
   4340         writemenu(menu,settings,selected,header,showmenu)
   4341         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   4342 
   4343         #NEW DUB SETTINGS
   4344         if pressed == 'up' and selected == 1:
   4345             if newdub[0] > 0.99 and newdub[1] > 0.01:
   4346                 newdub[1] -= 0.1
   4347             if newdub[1] > 0.99 and newdub[0] < 0.99:
   4348                 newdub[0] += 0.1
   4349         elif pressed == 'down' and selected == 1:
   4350             if newdub[1] > 0.99 and newdub[0] > 0.01:
   4351                 newdub[0] -= 0.1
   4352             if newdub[0] > 0.99 and newdub[1] < 0.99:
   4353                 newdub[1] += 0.1
   4354         elif pressed == 'up' and selected == 2:
   4355             newdub[2] += 0.1
   4356         elif pressed == 'down' and selected == 2:
   4357             if newdub[2] > 0.01:
   4358                 newdub[2] -= 0.1
   4359         elif pressed == 'up' and selected == 3:
   4360             newdub[3] += 0.1
   4361         elif pressed == 'down' and selected == 3:
   4362             if newdub[3] > 0.01:
   4363                 newdub[3] -= 0.1
   4364         elif pressed == 'record' or pressed == 'middle' and selected == 1:
   4365             dubmix.append(newdub)
   4366             dubrecord = filefolder + 'dub' + str(len(dubfiles)+1).zfill(3) + '.wav'
   4367             break
   4368         elif pressed == 'retake' and selected == 4:
   4369             dubrecord = filefolder + 'dub' + str(dubselected + 1).zfill(3) + '.wav'
   4370             break
   4371         #DUB SETTINGS
   4372         elif pressed == 'up' and selected == 4:
   4373             if dubselected + 1 < len(dubfiles):
   4374                 dubselected = dubselected + 1
   4375         elif pressed == 'down' and selected == 4:
   4376             if dubselected > 0:
   4377                 dubselected = dubselected - 1
   4378         elif pressed == 'remove' and selected == 4:
   4379             removedub(filefolder, dubselected + 1)
   4380             dubfiles, dubmix, newmix = getdubs(filmfolder, filmname, scene, shot)
   4381             dubselected = len(dubfiles) - 1
   4382             if len(dubfiles) == 0:
   4383                 #save original sound
   4384                 saveoriginal = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/take'+str(take).zfill(3)+'.wav'
   4385                 print('no dubs, copying original sound to original')
   4386                 os.system('cp '+filefolder+'original.wav '+saveoriginal)
   4387                 #removedub folder
   4388                 os.system('rm -r ' + filefolder)
   4389                 time.sleep(1)
   4390                 selected = 0
   4391         elif pressed == 'up' and selected == 5:
   4392             if dubmix[dubselected][0] >= 0.99 and dubmix[dubselected][1] > 0.01:
   4393                 dubmix[dubselected][1] -= 0.1
   4394             if dubmix[dubselected][1] >= 0.99 and dubmix[dubselected][0] < 0.99:
   4395                 dubmix[dubselected][0] += 0.1
   4396         elif pressed == 'down' and selected == 5:
   4397             if dubmix[dubselected][1] >= 0.99 and dubmix[dubselected][0] > 0.01:
   4398                 dubmix[dubselected][0] -= 0.1
   4399             if dubmix[dubselected][0] >= 0.99 and dubmix[dubselected][1] < 0.99:
   4400                 dubmix[dubselected][1] += 0.1
   4401         elif pressed == 'up' and selected == 6:
   4402             dubmix[dubselected][2] += 0.1
   4403         elif pressed == 'down' and selected == 6:
   4404             if dubmix[dubselected][2] > 0.01:
   4405                 dubmix[dubselected][2] -= 0.1
   4406         elif pressed == 'up' and selected == 7:
   4407             dubmix[dubselected][3] += 0.1
   4408         elif pressed == 'down' and selected == 7:
   4409             if dubmix[dubselected][3] > 0.01:
   4410                 dubmix[dubselected][3] -= 0.1
   4411         elif pressed == 'right':
   4412             if selected < (len(settings) - 1):
   4413                 selected = selected + 1
   4414         elif pressed == 'left':
   4415             if selected > 0:
   4416                 selected = selected - 1
   4417         elif pressed == 'middle' and menu[selected] == 'BACK':
   4418             os.system('pkill aplay')
   4419             break
   4420         elif pressed == 'view': # mix dub and listen
   4421             run_command('pkill aplay')
   4422             dubfiles, dubmix, rerender = getdubs(filmfolder, filmname, scene, shot)
   4423             if scene:
   4424                 filename = filmfolder + filmname + '/scene' + str(scene).zfill(3) +'/scene'
   4425             else:
   4426                 filename = filmfolder + filmname + '/' + filmname
   4427             renderfilename = renderfilm(filmfolder, filmname, 0, scene, False)
   4428             playdub(filmname,renderfilename, 'scene')
   4429         time.sleep(0.05)
   4430     #Save dubmix before returning
   4431     if dubmix != dubmix_old:
   4432         if os.path.isdir(filefolder) == False:
   4433             os.makedirs(filefolder)
   4434         c = 1
   4435         for i in dubmix:
   4436             with open(filefolder + ".settings" + str(c).zfill(3), "w") as f:
   4437                 for p in i:
   4438                     f.write(str(round(p,1)) + '\n')
   4439                     print(str(round(p,1)))
   4440             c += 1
   4441         dubmix_old = dubmix
   4442     return dubrecord
   4443 
   4444 #---------------Play & DUB--------------------
   4445 
   4446 def playdub(filmname, filename, player_menu):
   4447     global headphoneslevel, miclevel, plughw, channels, filmfolder, scene, soundrate, soundformat, showhelp, camera, overlay, overlay2, gonzopifolder
   4448     if showhelp == True:
   4449         overlay2 = removeimage(camera, overlay2)
   4450         overlay2 = displayimage(camera, gonzopifolder+'/extras/view-buttons.png', overlay, 4)
   4451     #read fastedit file
   4452     if player_menu == 'scene':
   4453         scenedir = filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/'
   4454         try:
   4455             with open(scenedir + '.fastedit', 'r') as f:
   4456                 fastedit = f.read().splitlines()
   4457                 print(fastedit)
   4458         except:
   4459             print('no fastedit file found')
   4460             fastedit = 9999999
   4461     #omxplayer hack
   4462     os.system('rm /tmp/omxplayer*')
   4463     video = True
   4464     if player_menu == 'dub':
   4465         dub = True
   4466     else:
   4467         dub = False
   4468     if not os.path.isfile(filename + '.mp4'):
   4469         #should probably check if its not a corrupted video file
   4470         logger.info("no file to play")
   4471         if dub == True:
   4472             video = False
   4473         else:
   4474             return
   4475     t = 0
   4476     pressed = ''
   4477     buttonpressed = ''
   4478     buttontime = time.time()
   4479     holdbutton = ''
   4480     playing = False
   4481     pause = False
   4482     trim = False
   4483     videolag = 0
   4484     trimfromstart=0
   4485     trimfromend=0
   4486     remove_shots = []
   4487     if video == True:
   4488         if player_menu == 'dubbb':
   4489             try:
   4490                 player = OMXPlayer(filename + '.mp4', args=['-n', '-1', '--fps', '25', '--layer', '3', '--no-osd', '--win', '0,15,800,475','--no-keys'], dbus_name='org.mpris.MediaPlayer2.omxplayer1', pause=True)
   4491             except:
   4492                 writemessage('Something wrong with omxplayer')
   4493                 time.sleep(0.5)
   4494                 return
   4495         else:
   4496             try:
   4497                 player = OMXPlayer(filename + '.mp4', args=['--adev', 'alsa:hw:'+str(plughw), '--fps', '25', '--layer', '3', '--no-osd', '--win', '0,15,800,475','--no-keys'], dbus_name='org.mpris.MediaPlayer2.omxplayer1', pause=True)
   4498             except:
   4499                 writemessage('Something wrong with omxplayer')
   4500                 time.sleep(0.5)
   4501                 return
   4502             #player = OMXPlayer(filename + '.mp4', args=['--fps', '25', '--layer', '3', '--win', '0,70,800,410', '--no-osd', '--no-keys'], dbus_name='org.mpris.MediaPlayer2.omxplayer1', pause=True)
   4503         writemessage('Loading..')
   4504         clipduration = player.duration()
   4505         #vumetermessage('up [fast-forward], down [rewind], help button for more')
   4506     #sound
   4507     #if player_menu != 'film':
   4508     #    try:
   4509     #        playerAudio = OMXPlayer(filename + '.wav', args=['--adev','alsa:hw:'+str(plughw)], dbus_name='org.mpris.MediaPlayer2.omxplayer2', pause=True)
   4510     #        time.sleep(0.2)
   4511     #    except:
   4512     #        writemessage('something wrong with audio player')
   4513     #        time.sleep(2)
   4514     #        return
   4515         #omxplayer hack to play really short videos.
   4516     if clipduration < 4:
   4517         logger.info("clip duration shorter than 4 sec")
   4518         player.previous()
   4519     if dub == True:
   4520         p = 0
   4521         while p < 3:
   4522             writemessage('Dubbing in ' + str(3 - p) + 's')
   4523             time.sleep(1)
   4524             p+=1
   4525     if video == True:
   4526         player.play()
   4527         #run_command('aplay -D plughw:0 ' + filename + '.wav &')
   4528         #run_command('mplayer ' + filename + '.wav &')
   4529     if player_menu == 'dub':
   4530         run_command(gonzopifolder + '/alsa-utils-1.1.3/aplay/arecord -D hw:'+str(plughw)+' -f '+soundformat+' -c '+str(channels)+' -r '+soundrate+' -vv /dev/shm/dub.wav &')
   4531     time.sleep(0.5)
   4532     #try:
   4533     #    playerAudio.play()
   4534     #except:
   4535     #    logger.info('something wrong with omxplayer audio or playing film mp4 audio')
   4536         #logger.warning(e)
   4537     starttime = time.time()
   4538     selected = 1
   4539     while True:
   4540         if player_menu == 'scene':
   4541             fastedit_shot = 1
   4542             for i in fastedit:
   4543                 if int(t) > float(int(i)/1000):
   4544                     fastedit_shot = fastedit_shot + 1
   4545             if not remove_shots:
   4546                 vumetermessage('shot ' + str(fastedit_shot))
   4547             else:
   4548                 p = ''
   4549                 for i in remove_shots:
   4550                     p = p + str(i) + ','
   4551                 vumetermessage('shot ' + str(fastedit_shot) + ' remove:' + p)
   4552         if trim == True:
   4553             menu = 'CANCEL', 'FROM BEGINNING', 'FROM END'
   4554             settings = '','',''
   4555         elif pause == True:
   4556             if player_menu == 'shot':
   4557                 menu = 'BACK', 'PLAY', 'REPLAY', 'TRIM'
   4558                 settings = '','','',''
   4559             else:
   4560                 menu = 'BACK', 'PLAY', 'REPLAY'
   4561                 settings = '','',''
   4562         elif player_menu == 'dub': 
   4563             menu = 'BACK', 'REDUB', 'PHONES:', 'MIC:'
   4564             settings = '', '', str(headphoneslevel), str(miclevel)
   4565         else:
   4566             menu = 'BACK', 'PAUSE', 'REPLAY', 'PHONES:'
   4567             settings = '', '', '', str(headphoneslevel)
   4568         if dub == True:
   4569             header = 'Dubbing ' + str(round(t,1))
   4570         else:
   4571             header = 'Playing ' + str(datetime.timedelta(seconds=round(t))) + ' of ' + str(datetime.timedelta(seconds=round(clipduration))) + ' s'
   4572         writemenu(menu,settings,selected,header,showmenu)
   4573         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   4574         if buttonpressed == True:
   4575             flushbutton()
   4576         if pressed == 'remove':
   4577             vumetermessage('add direct remove here')
   4578         #SHOWHELP
   4579         elif pressed == 'showhelp':
   4580             vumetermessage('Button layout')
   4581             if showhelp == False:
   4582                 overlay2 = removeimage(camera, overlay2)
   4583                 overlay2 = displayimage(camera, gonzopifolder+'/extras/view-buttons.png', overlay, 4)
   4584                 showhelp = True
   4585             elif showhelp == True:
   4586                 overlay2 = removeimage(camera, overlay2)
   4587                 updatethumb =  True
   4588                 showhelp = False
   4589         elif pressed == 'right':
   4590             if selected < (len(settings) - 1):
   4591                 selected = selected + 1
   4592         elif pressed == 'left':
   4593             if selected > 0:
   4594                 selected = selected - 1
   4595         elif pressed == 'up':
   4596             if menu[selected] == 'PHONES:':
   4597                 if headphoneslevel < 100:
   4598                     headphoneslevel = headphoneslevel + 2
   4599                     run_command('amixer -c 0 sset Speaker ' + str(headphoneslevel) + '%')
   4600             elif menu[selected] == 'MIC:':
   4601                 if miclevel < 100:
   4602                     miclevel = miclevel + 2
   4603                     run_command('amixer -c 0 sset Mic ' + str(miclevel) + '% unmute')
   4604             else:
   4605                 try:
   4606                     player.set_position(t+2)
   4607                     time.sleep(0.2)
   4608                     #playerAudio.set_position(player.position())
   4609                 except:
   4610                     print('couldnt set position of player')
   4611         elif pressed == 'down':
   4612             if menu[selected] == 'PHONES:':
   4613                 if headphoneslevel > 0:
   4614                     headphoneslevel = headphoneslevel - 2
   4615                     run_command('amixer -c 0 sset Speaker ' + str(headphoneslevel) + '%')
   4616             elif menu[selected] == 'MIC:':
   4617                 if miclevel > 0:
   4618                     miclevel = miclevel - 2
   4619                     run_command('amixer -c 0 sset Mic ' + str(miclevel) + '% unmute')
   4620             else:
   4621                 if t > 1:
   4622                     try:
   4623                         player.set_position(t-2)
   4624                         time.sleep(0.25)
   4625                         #playerAudio.set_position(player.position())
   4626                     except:
   4627                         print('couldnt set position of player')
   4628         elif pressed == 'view':
   4629             trimfromstart = player.position()
   4630             vumetermessage('shot start position set to: '+ str(trimfromstart))
   4631             player.pause()
   4632             time.sleep(0.5)
   4633             player.play()
   4634         elif pressed == 'retake':
   4635             trimfromend = player.position()
   4636             vumetermessage('shot end position set to: '+ str(trimfromend))
   4637             player.pause()
   4638             time.sleep(0.5)
   4639             player.play()
   4640         elif pressed == 'middle' or pressed == 'record':
   4641             time.sleep(0.2)
   4642             if menu[selected] == 'BACK' or player.playback_status() == "Stopped" or pressed == 'record':
   4643                 try:
   4644                     if video == True:
   4645                         #player.stop()
   4646                         #playerAudio.stop()
   4647                         player.quit()
   4648                         #playerAudio.quit()
   4649                     #os.system('pkill -9 aplay') 
   4650                 except:
   4651                     #kill it if it dont stop
   4652                     print('OMG! kill dbus-daemon')
   4653                 if dub == True:
   4654                     os.system('pkill arecord')
   4655                     time.sleep(0.2)
   4656                 os.system('pkill -9 omxplayer')
   4657                 #os.system('pkill -9 dbus-daemon')
   4658                 return [trimfromstart, trimfromend]
   4659             elif menu[selected] == 'REPLAY' or menu[selected] == 'REDUB':
   4660                 pause = False
   4661                 try:
   4662                     os.system('pkill aplay')
   4663                     if dub == True:
   4664                         os.system('pkill arecord')
   4665                     if video == True:
   4666                         player.pause()
   4667                         player.set_position(0)
   4668                         #if player_menu != 'film':
   4669                             #playerAudio.pause()
   4670                             #playerAudio.set_position(0)
   4671                     if dub == True:
   4672                         p = 0
   4673                         while p < 3:
   4674                             writemessage('Dubbing in ' + str(3 - p) + 's')
   4675                             time.sleep(1)
   4676                             p+=1
   4677                     player.play()
   4678                     #if player_menu != 'film':
   4679                     #    playerAudio.play()
   4680                     #run_command('aplay -D plughw:0 ' + filename + '.wav &')
   4681                     if dub == True:
   4682                         run_command(gonzopifolder + '/alsa-utils-1.1.3/aplay/arecord -D hw:'+str(plughw)+' -f '+soundformat+' -c '+str(channels)+' -r '+soundrate+' -vv /dev/shm/dub.wav &')
   4683                 except:
   4684                     pass
   4685                 starttime = time.time()
   4686             # check if not to close to end otherwise will throw error
   4687             elif menu[selected] == 'PAUSE':
   4688                 try:
   4689                     player.pause()
   4690                     pause = True
   4691                 except:
   4692                     pass
   4693                 #try:
   4694                 #    playerAudio.pause()
   4695                 #except:
   4696                 #    pass
   4697             elif menu[selected] == 'PLAY':
   4698                 try:
   4699                     player.play()
   4700                     pause = False
   4701                 except:
   4702                     pass
   4703                 #try:
   4704                 #    playerAudio.play()
   4705                 #except:
   4706                 #    pass
   4707             elif menu[selected] == 'TRIM':
   4708                 selected = 1
   4709                 trim = True
   4710             elif menu[selected] == 'CANCEL':
   4711                 selected = 1
   4712                 trim = False
   4713             elif menu[selected] == 'FROM BEGINNING':
   4714                 trim = ['beginning', player.position()]
   4715                 player.quit()
   4716                 #playerAudio.quit()
   4717                 return trim
   4718             elif menu[selected] == 'FROM END':
   4719                 trim = ['end', player.position()]
   4720                 player.quit()
   4721                 #playerAudio.quit()
   4722                 return trim
   4723         time.sleep(0.02)
   4724         if pause == False:
   4725             try:
   4726                 t = player.position()
   4727             except:
   4728                 os.system('pkill aplay') 
   4729                 if dub == True:
   4730                     os.system('pkill arecord')
   4731                 return [trimfromstart, trimfromend]
   4732                 #return remove_shots
   4733         if t > (clipduration - 0.3):
   4734             os.system('pkill aplay') 
   4735             if dub == True:
   4736                 os.system('pkill arecord')
   4737             return [trimfromstart, trimfromend]
   4738     try:
   4739         player.quit()
   4740     except:
   4741         pass
   4742     #playerAudio.quit()
   4743     #os.system('pkill dbus-daemon')
   4744 
   4745 #---------------View Film--------------------
   4746 
   4747 def viewfilm(filmfolder, filmname):
   4748     scenes, shots, takes = countlast(filmname, filmfolder)
   4749     scene = 1
   4750     filmfiles = []
   4751     while scene <= scenes:
   4752         shots = countshots(filmname, filmfolder, scene)
   4753         if shots > 0:
   4754             filmfiles.extend(shotfiles(filmfolder, filmname, scene))
   4755         scene = scene + 1
   4756     return filmfiles
   4757 
   4758 #---------------Video Trim--------------------
   4759 
   4760 def videotrim(foldername ,filename, trim_filename, where, s):
   4761     #theres two different ways of non-rerendering mp4 cut techniques that i know MP4Box and ffmpeg
   4762     if where == 'beginning':
   4763         logger.info('trimming clip from beginning')
   4764         #run_command('ffmpeg -ss ' + str(s) + ' -i ' + filename + '.mp4 -c copy ' + trim_filename + '.mp4')
   4765         run_command('MP4Box ' + filename + '.mp4 -splitx ' + str(s) + ':end -out ' + trim_filename + '.mp4')
   4766         run_command('cp ' + filename + '.wav ' + trim_filename + '.wav')
   4767         audiotrim(trim_filename, 'beginning','')
   4768         if os.path.exists(foldername+'dub') == True:
   4769             dubfiles, dubmix, rerender = getdubs(foldername+'dub/', None, None, None)
   4770             for d in dubfiles:
   4771                 writemessage('trimming dubs from beginning')
   4772                 vumetermessage(d)
   4773                 audiotrim(trim_filename, 'beginning', d)
   4774             writemessage('trimming original sound')
   4775             audiotrim(trim_filename, 'beginning', foldername+'dub/original.wav')
   4776     if where == 'end':
   4777         logger.info('trimming clip from end')
   4778         #run_command('ffmpeg -to ' + str(s) + ' -i ' + filename + '.mp4 -c copy ' + trim_filename + '.mp4')
   4779         run_command('MP4Box ' + filename + '.mp4 -splitx 0:' + str(s) + ' -out ' + trim_filename + '.mp4')
   4780         run_command('cp ' + filename + '.wav ' + trim_filename + '.wav')
   4781         audiotrim(trim_filename, 'end','')
   4782         if os.path.exists(foldername+'dub') == True:
   4783             dubfiles, dubmix, rerender = getdubs(foldername+'dub/', None, None, None)
   4784             for d in dubfiles:
   4785                 writemessage('trimming dubs from end')
   4786                 vumetermessage(d)
   4787                 audiotrim(trim_filename, 'end', d)
   4788             writemessage('trimming original sound')
   4789             audiotrim(trim_filename, 'end', foldername+'dub/original.wav')
   4790     #take last frame 
   4791     run_command('ffmpeg -y -sseof -1 -i ' + trim_filename + '.mp4 -update 1 -q:v 1 -vf scale=800:450 ' + trim_filename + '.jpeg')
   4792     return
   4793 
   4794 #---------------Video Trim From start and end--------------------
   4795 
   4796 def fastvideotrim(filename, trim_filename, beginning, end):
   4797     #theres two different ways of non-rerendering mp4 cut techniques that i know MP4Box and ffmpeg
   4798     logger.info('trimming clip from beginning and end')
   4799     #run_command('ffmpeg -to ' + str(s) + ' -i ' + filename + '.mp4 -c copy ' + trim_filename + '.mp4')
   4800     run_command('MP4Box ' + filename + '.mp4 -splitx '+ str(beginning)+ ':' + str(end) + ' -out ' + trim_filename + '.mp4')
   4801     run_command('cp ' + filename + '.wav ' + trim_filename + '.wav')
   4802     fastaudiotrim(trim_filename, beginning, end)
   4803     #take last frame 
   4804     run_command('ffmpeg -sseof -1 -i ' + trim_filename + '.mp4 -update 1 -q:v 1 -vf scale=800:450 ' + trim_filename + '.jpeg')
   4805     return
   4806 
   4807 #--------------Get Audio cards--------------
   4808 def getaudiocards():
   4809     with open("/proc/asound/cards") as fp:
   4810         cards = fp.readlines()
   4811     audiocards = []
   4812     for i in cards:
   4813         if i[1] in ['0','1','2','3']:
   4814             print('audio card 0: ' + i[22:].rstrip('\n'))
   4815             audiocards.append(i[22:].rstrip('\n'))
   4816     return audiocards
   4817 
   4818 #--------------Fast Audio Trim--------------------
   4819 # make audio file same lenght as video file
   4820 def fastaudiotrim(filename, beginning, end):
   4821     run_command('sox -V0 ' + filename + '.wav ' + filename + '_temp.wav trim ' + beginning + ' ' + end)
   4822     run_command('sox -V0 -G ' + filename + '_temp.wav ' + filename + '.wav fade 0.01 0 0.01')
   4823 
   4824 #--------------Audio Trim--------------------
   4825 # make audio file same lenght as video file
   4826 def audiotrim(filename, where, dub):
   4827     global channels, fps
   4828     videofile=filename
   4829     audiosync=0
   4830     print("chaaaaaaaaaaaaaaaanel8: " +str(channels))
   4831     writemessage('Audio syncing..')
   4832     pipe = subprocess.check_output('mediainfo --Inform="Video;%Duration%" ' + filename + '.mp4', shell=True)
   4833     videolenght = pipe.decode().strip()
   4834     print('videolenght:'+str(videolenght))
   4835     if dub:
   4836         pipe = subprocess.check_output('mediainfo --Inform="Audio;%Duration%" ' + dub[:-4] + '.wav', shell=True)
   4837         audiolenght = pipe.decode().strip()
   4838     else:
   4839         try:
   4840             pipe = subprocess.check_output('mediainfo --Inform="Audio;%Duration%" ' + filename + '.wav', shell=True)
   4841             audiolenght = pipe.decode().strip()
   4842         except:
   4843             audiosilence('',filename)
   4844             audiolenght=videolenght
   4845         #if there is no audio lenght
   4846     logger.info('audio is:' + audiolenght)
   4847     if not audiolenght.strip():
   4848         audiolenght = 0
   4849     #separate seconds and milliseconds
   4850     #videoms = int(videolenght) % 1000
   4851     #audioms = int(audiolenght) % 1000
   4852     #videos = int(videolenght) / 1000
   4853     #audios = int(audiolenght) / 1000
   4854     elif int(audiolenght) > int(videolenght):
   4855         #calculate difference
   4856         audiosync = int(audiolenght) - int(videolenght)
   4857         newaudiolenght = int(audiolenght) - audiosync
   4858         logger.info('Audiofile is: ' + str(audiosync) + 'ms longer')
   4859         #trim from end or beginning and put a 0.01 in- and outfade
   4860         if where == 'end':
   4861             if dub:
   4862                 run_command('sox -V0 ' + dub[:-4] + '.wav ' + dub[:-4] + '_temp.wav trim 0 -' + str(int(audiosync)/1000))
   4863             else:
   4864                 run_command('sox -V0 ' + filename + '.wav ' + filename + '_temp.wav trim 0 -' + str(int(audiosync)/1000))
   4865         if where == 'beginning':
   4866             if dub:
   4867                 logger.info('trimming from beginning at: '+str(int(audiosync)/1000))
   4868                 run_command('sox -V0 ' + dub[:-4] + '.wav ' + dub[:-4] + '_temp.wav trim ' + str(int(audiosync)/1000))
   4869             else:
   4870                 logger.info('trimming from beginning at: '+str(int(audiosync)/1000))
   4871                 run_command('sox -V0 ' + filename + '.wav ' + filename + '_temp.wav trim ' + str(int(audiosync)/1000))
   4872         if dub:
   4873             run_command('sox -V0 -G ' + dub[:-4] + '_temp.wav ' + dub[:-4] + '.wav fade 0.01 0 0.01')
   4874             os.remove(dub[:-4] + '_temp.wav')
   4875         else:
   4876             run_command('sox -V0 -G ' + filename + '_temp.wav ' + filename + '.wav fade 0.01 0 0.01')
   4877             os.remove(filename + '_temp.wav')
   4878         #if int(audiosync) > 400:
   4879         #    writemessage('WARNING!!! VIDEO FRAMES DROPPED!')
   4880         #    vumetermessage('Consider changing to a faster microsd card.')
   4881         #    time.sleep(10)
   4882         delayerr = 'A' + str(audiosync)
   4883         print(delayerr)
   4884     elif int(audiolenght) < int(videolenght):
   4885         audiosync = int(videolenght) - int(audiolenght)
   4886         #calculate difference
   4887         #audiosyncs = videos - audios
   4888         #audiosyncms = videoms - audioms
   4889         #if audiosyncms < 0:
   4890         #    if audiosyncs > 0:
   4891         #        audiosyncs = audiosyncs - 1
   4892         #    audiosyncms = 1000 + audiosyncms
   4893         logger.info('Videofile is: ' + str(audiosync) + 'ms longer')
   4894         logger.info('Videofile is: ' + str(int(audiosync)/1000) + 's longer')
   4895         #time.sleep(2)
   4896         #make fade
   4897         #make delay file
   4898         print(str(int(audiosync)/1000))
   4899         if dub:
   4900             run_command('sox -V0 -r '+soundrate+' -c 2 '+dub[:-4]+'.wav '+dub[:-4]+'_temp.wav trim 0.0 pad 0 ' + str(int(audiosync)/1000))
   4901             run_command('sox -V0 -G ' + dub[:-4] + '_temp.wav ' + dub[:-4] + '.wav fade 0.01 0 0.01')
   4902         else:
   4903             run_command('sox -V0 -r '+soundrate+' -c 2 '+filename+'.wav '+filename+'_temp.wav trim 0.0 pad 0 ' + str(int(audiosync)/1000))
   4904             run_command('sox -V0 -G ' + filename + '_temp.wav ' + filename + '.wav fade 0.01 0 0.01')
   4905         #add silence to end
   4906         #run_command('sox -V0 /dev/shm/silence.wav ' + filename + '_temp.wav')
   4907         #run_command('cp '+filename+'.wav '+filename+'_temp.wav')
   4908         #run_command('sox -V0 -G ' + filename + '_temp.wav /dev/shm/silence.wav ' + filename + '.wav')
   4909         if dub:
   4910             os.remove(dub[:-4] + '_temp.wav')
   4911         else:
   4912             os.remove(filename + '_temp.wav')
   4913         #os.remove('/dev/shm/silence.wav')
   4914         delayerr = 'V' + str(audiosync)
   4915         print(delayerr)
   4916     print('the results:')
   4917     if dub:
   4918         pipe = subprocess.check_output('mediainfo --Inform="Audio;%Duration%" ' + dub[:-4] + '.wav', shell=True)
   4919         audiolenght = pipe.decode().strip()
   4920     else:
   4921         pipe = subprocess.check_output('mediainfo --Inform="Audio;%Duration%" ' + filename + '.wav', shell=True)
   4922         audiolenght = pipe.decode().strip()
   4923     print('aftersyncvideo: '+str(videolenght) + ' audio:'+str(audiolenght))
   4924     if int(audiolenght) != int(videolenght):
   4925         vumetermessage('SYNCING FAILED!')
   4926         time.sleep(10)
   4927     #os.remove('/dev/shm/' + filename + '.wav')
   4928     return float(audiosync)/1000, int(videolenght), int(audiolenght)
   4929     #os.system('mv audiosynced.wav ' + filename + '.wav')
   4930     #os.system('rm silence.wav')
   4931 
   4932 #--------------Audiosilence--------------------
   4933 # make an empty audio file as long as a video file
   4934 
   4935 def audiosilence(foldername,filename):
   4936     global channels
   4937     writemessage('Creating audiosilence..')
   4938     pipe = subprocess.check_output('mediainfo --Inform="Video;%Duration%" ' + foldername + filename + '.mp4', shell=True)
   4939     videolenght = pipe.decode()
   4940     logger.info('Video lenght is ' + videolenght)
   4941     #separate seconds and milliseconds
   4942     videoms = int(videolenght) % 1000
   4943     videos = int(videolenght) / 1000
   4944     logger.info('Videofile is: ' + str(videos) + 's ' + str(videoms))
   4945     run_command('sox -V0 -n -r '+soundrate+' -c 2 /dev/shm/silence.wav trim 0.0 ' + str(videos))
   4946     os.system('cp /dev/shm/silence.wav ' + foldername + filename + '.wav')
   4947     os.system('rm /dev/shm/silence.wav')
   4948 
   4949 #--------------USB filmfolder-------------------
   4950 
   4951 def usbfilmfolder(dsk):
   4952     pressed = ''
   4953     buttonpressed = ''
   4954     buttontime = time.time()
   4955     holdbutton = ''
   4956     writemessage('Searching for usb storage device, middlebutton to cancel')
   4957     if os.path.exists('/dev/sda1') == True:
   4958         os.system('sudo mount /dev/sda1 /media/usb0')
   4959         os.system('sudo chown pi /media/usb0')
   4960         #os.system('sudo umount -l /media/usb0')
   4961     if dsk == 1:
   4962         usbmount = 1
   4963     else:
   4964         usbmount = 0
   4965     waiting = time.time() 
   4966     while True:
   4967         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   4968         usbconnected = os.path.ismount('/media/usb'+str(usbmount))
   4969         if pressed == 'middle' or time.time() - waiting > 8:
   4970             writemessage('canceling..')
   4971             break
   4972         time.sleep(0.02)
   4973         if usbconnected == True:
   4974             try:
   4975                 os.makedirs('/media/usb'+str(usbmount)+'/gonzopifilms/')
   4976             except:
   4977                 pass
   4978             try:
   4979                 p = subprocess.check_output('stat -f -c %T /media/usb'+str(usbmount), shell=True)
   4980                 filesystem = p.decode()
   4981                 print('filesystem info: ' + filesystem)
   4982             except:
   4983                 writemessage('Oh-no! dont know your filesystem')
   4984                 waitforanykey()
   4985             filmfolder = '/media/usb'+str(usbmount)+'/gonzopifilms/'
   4986             os.system('sudo chmod 755 '+filmfolder)
   4987             #run_command('pumount /media/usb'+str(usbmount))
   4988             writemessage('Filming to USB'+str(usbmount))
   4989             #time.sleep(1)
   4990             return filmfolder
   4991         else:
   4992             return
   4993 
   4994 #--------------Copy to USB-------------------
   4995 
   4996 def copytousb(filmfolder):
   4997     pressed = ''
   4998     buttonpressed = ''
   4999     buttontime = time.time()
   5000     holdbutton = ''
   5001     writemessage('Searching for usb storage device, middlebutton to cancel')
   5002     films = getfilms(filmfolder)
   5003     if 'usb0' in filmfolder:
   5004         usbmount = 1
   5005     else:
   5006         usbmount = 0
   5007     while True:
   5008         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   5009         usbconnected = os.path.ismount('/media/usb'+str(usbmount))
   5010         if pressed == 'middle':
   5011             writemessage('canceling..')
   5012             time.sleep(2)
   5013             break
   5014         time.sleep(0.02)
   5015         if usbconnected == True:
   5016             #Copy new files to usb device
   5017             try:
   5018                 os.makedirs('/media/usb'+str(usbmount)+'/gonzopifilms/')
   5019             except:
   5020                 pass
   5021             try:
   5022                 p = subprocess.check_output('stat -f -c %T /media/usb'+str(usbmount), shell=True)
   5023                 filesystem = p.decode()
   5024                 print('filesystem info: ' + filesystem)
   5025             except:
   5026                 writemessage('Oh-no! dont know your filesystem')
   5027                 waitforanykey()
   5028                 return
   5029             for filmname in films:
   5030                 #check filmhash
   5031                 filmname = filmname[0]
   5032                 usbpath = '/media/usb'+str(usbmount)+'/gonzopifilms/'+filmname
   5033                 usbvideopath = '/media/usb0/gonzopifilms/.videos/'
   5034                 usbfilmhash = ''
   5035                 filmhash = ''
   5036                 while True:
   5037                     if os.path.exists(usbpath) == False:
   5038                         break
   5039                     try:
   5040                         with open(filmfolder + filmname + '/.filmhash', 'r') as f:
   5041                             filmhash = f.readline().strip()
   5042                         print('filmhash is: ' + filmhash)
   5043                     except:
   5044                         print('no filmhash found!')
   5045                     try:
   5046                         with open(usbpath + '/.filmhash', 'r') as f:
   5047                             usbfilmhash = f.readline().strip()
   5048                         print('usbfilmhash is: ' + usbfilmhash)
   5049                     except:
   5050                         print('no usbfilmhash found!')
   5051                     if usbfilmhash == filmhash:
   5052                         print('same moviefilm found, updating clips...')
   5053                         break
   5054                     else:
   5055                         writemessage('Found a subsequent moviefilm...')
   5056                         print('same film exist with different filmhashes, copying to subsequent film folder')
   5057                         time.sleep(2)
   5058                         usbpath += '_new'
   5059                 try:
   5060                     os.makedirs(usbpath)
   5061                     writemessage('Copying film ' + filmname + '...')
   5062                 except:
   5063                     writemessage('Found existing ' + filmname + ', copying new files... ')
   5064                 try:
   5065                     run_command('rsync -avr -P ' + filmfolder + filmname + '/ ' + usbpath)
   5066                     run_command('rsync -avr -P ' + filmfolder + '.videos/ ' + usbvideopath)
   5067                 except:
   5068                     writemessage('couldnt copy film ' + filmname)
   5069                     waitforanykey()
   5070                     return
   5071             run_command('sync')
   5072             writemessage('all files copied successfully!')
   5073             waitforanykey()
   5074             run_command('pumount /media/usb'+str(usbmount))
   5075             writemessage('You can safely unplug the usb device now')
   5076             time.sleep(2)
   5077             return
   5078         else:
   5079             usbmount = usbmount + 1
   5080 
   5081 #-----------Check for the webz---------
   5082 
   5083 def webz_on():
   5084     try:
   5085         # connect to the host -- tells us if the host is actually
   5086         # reachable
   5087         socket.create_connection(("google.com", 80))
   5088         return True
   5089     except OSError:
   5090         pass
   5091     writemessage('No internet connection!')
   5092     time.sleep(2)
   5093     return False
   5094 
   5095 #-------------Upload film------------
   5096 
   5097 def uploadfilm(filename, filmname):
   5098     pressed = ''
   5099     buttonpressed = ''
   5100     buttontime = time.time()
   5101     holdbutton = ''
   5102     mods = ['Back']
   5103     settings = ['']
   5104     writemessage('Searching for upload mods')
   5105     with open(gonzopifolder + '/mods/upload-mods-enabled') as m:
   5106         mods.extend(m.read().splitlines())
   5107     for m in mods:
   5108         settings.append('')
   5109     menu = mods
   5110     selected = 0
   5111     while True:
   5112         header = 'Where do you want to upload?'
   5113         writemenu(menu,settings,selected,header,showmenu)
   5114         pressed, buttonpressed, buttontime, holdbutton, event, keydelay = getbutton(pressed, buttonpressed, buttontime, holdbutton)
   5115         if pressed == 'right':
   5116             if selected < (len(menu) - 1):
   5117                 selected = selected + 1
   5118         elif pressed == 'left':
   5119             if selected > 0:
   5120                 selected = selected - 1
   5121         elif pressed == 'middle' and  menu[selected] == 'Back':
   5122             return None
   5123         elif pressed == 'middle' and  menu[selected] in mods:
   5124             cmd = gonzopifolder + '/mods/' + menu[selected] + '.sh ' + filmname + ' ' + filename + '.mp4'
   5125             return cmd
   5126         time.sleep(0.02)
   5127 
   5128 
   5129 #-------------Streaming---------------
   5130 
   5131 def startstream(camera, stream, plughw, channels,network):
   5132     #youtube
   5133     #youtube="rtmp://a.rtmp.youtube.com/live2/"
   5134     #with open("/home/pi/.youtube-live") as fp:
   5135     #    key = fp.readlines()
   5136     #print('using key: ' + key[0])
   5137     #stream_cmd = 'ffmpeg -f h264 -r 25 -i - -itsoffset 5.5 -fflags nobuffer -f alsa -ac '+str(channels)+' -i hw:'+str(plughw)+' -ar 48000 -vcodec copy -acodec libmp3lame -b:a 128k -ar 48000 -map 0:0 -map 1:0 -strict experimental -f flv ' + youtube + key[0]
   5138     #
   5139     #stream_cmd = 'ffmpeg -f h264 -r 25 -i - -itsoffset 5.5 -fflags nobuffer -f alsa -ac '+str(channels)+' -i hw:'+str(plughw)+' -ar 44100 -vcodec copy -acodec libmp3lame -b:a 128k -ar 44100 -map 0:0 -map 1:0 -strict experimental -f mpegts tcp://0.0.0.0:3333\?listen'
   5140     #stream_cmd = 'ffmpeg -f h264 -r 25 -i - -itsoffset 5.5 -fflags nobuffer -f alsa -ac '+str(channels)+' -i hw:'+str(plughw)+' -ar '+soundrate+' -acodec mp2 -b:a 128k -ar '+soundrate+' -vcodec copy -map 0:0 -map 1:0 -g 0 -f mpegts udp://10.42.0.169:5002'
   5141     numbers_only = ' ','1','2','3','4','5','6','7','8','9','0'
   5142     newhost, hostport = newudp_ip(numbers_only, network)
   5143     stream_cmd = 'ffmpeg -f h264 -r 24.989 -i - -itsoffset 5.5 -fflags nobuffer -f alsa -ac '+str(channels)+' -i hw:'+str(plughw)+' -ar '+soundrate+' -acodec mp2 -b:a 128k -ar '+soundrate+' -vcodec copy -f mpegts udp://'+newhost+':'+hostport
   5144     try:
   5145         stream = subprocess.Popen(stream_cmd, shell=True, stdin=subprocess.PIPE) 
   5146         camera.start_recording(stream.stdin, splitter_port=2, format='h264', bitrate = 5555555, quality=quality)
   5147     except:
   5148         stream = ''
   5149     #now = time.strftime("%Y-%m-%d-%H:%M:%S") 
   5150     return stream
   5151 
   5152 def stopstream(camera, stream):
   5153     camera.stop_recording(splitter_port=2) 
   5154     os.system('pkill -9 ffmpeg') 
   5155     print("Camera safely shut down") 
   5156     print("Good bye")
   5157     stream = ''
   5158     return stream
   5159 
   5160 #-------------Beeps-------------------
   5161 
   5162 def beep(bus):
   5163     global gonzopifolder, plughw
   5164     if bus:
   5165         buzzerrepetitions = 100
   5166         buzzerdelay = 0.00001
   5167         for _ in range(buzzerrepetitions):
   5168             for value in [0xC, 0x4]:
   5169                 #GPIO.output(1, value)
   5170                 bus.write_byte_data(DEVICE,OLATA,value)
   5171                 time.sleep(buzzerdelay)
   5172     else:
   5173         run_command('aplay -D plughw:' + str(plughw) + ' '+ gonzopifolder + '/extras/beep.wav')
   5174     return
   5175 
   5176 def longbeep(bus):
   5177     global gonzopifolder, plughw
   5178     if bus:
   5179         buzzerrepetitions = 100
   5180         buzzerdelay = 0.0001
   5181         for _ in range(buzzerrepetitions * 5):
   5182             for value in [0xC, 0x4]:
   5183                 #GPIO.output(1, value)
   5184                 bus.write_byte_data(DEVICE,OLATA,value)
   5185                 buzzerdelay = buzzerdelay - 0.00000004
   5186                 time.sleep(buzzerdelay)
   5187         bus.write_byte_data(DEVICE,OLATA,0x4)
   5188     else:
   5189         run_command('aplay -D plughw:' + str(plughw) + ' '+ gonzopifolder + '/extras/beep_long.wav')
   5190     return
   5191 
   5192 def buzz(buzzerlenght):
   5193     buzzerdelay = 0.0001
   5194     for _ in range(buzzerlenght):
   5195         for value in [0xC, 0x4]:
   5196             #GPIO.output(1, value)
   5197             bus.write_byte_data(DEVICE,OLATA,value)
   5198             time.sleep(buzzerdelay)
   5199     return
   5200 
   5201 #---------reading in a lens shading table----------
   5202 
   5203 def read_table(inFile):
   5204     # q&d-way to read in ls_table.h
   5205     ls_table = []
   5206     channel  = []
   5207     with open(inFile) as file:       
   5208         for line in file:
   5209             # we skip the unimportant stuff
   5210             if not (   line.startswith("uint") \
   5211                     or line.startswith("}")):
   5212                 # the comments separate the color planes
   5213                 if line.startswith("//"):                
   5214                     channel = []
   5215                     ls_table.append(channel)
   5216                 else:
   5217                     # scan in a single line
   5218                     line = line.replace(',','')
   5219                     lineData = [int(x) for x in line.split()]
   5220                     channel.append(lineData)
   5221     return np.array(ls_table,dtype=np.uint8)    
   5222 
   5223 #-------------Check if file empty----------
   5224 
   5225 def empty(filename):
   5226     if os.path.isfile(filename + '.mp4') == False:
   5227         return False
   5228     if os.path.isfile(filename + '.mp4') == True:
   5229         writemessage('Take already exists')
   5230         time.sleep(1)
   5231         return True
   5232 
   5233 #--------------BUTTONS-------------
   5234 
   5235 def waitforanykey():
   5236     vumetermessage("press any key to continue..")
   5237     time.sleep(1)
   5238     while True:
   5239         with term.cbreak():
   5240             val = term.inkey(timeout=0)
   5241         if not val:
   5242             event = ''
   5243         elif val.is_sequence:
   5244             event = val.name
   5245         elif val:
   5246             event = val
   5247         if i2cbuttons == True:
   5248             readbus = bus.read_byte_data(DEVICE,GPIOB)
   5249             readbus2 = bus.read_byte_data(DEVICE,GPIOA)
   5250         else:
   5251             readbus = 255
   5252             readbus2 = 247
   5253         if readbus != 255 or readbus2 != 247 or event != '':
   5254             time.sleep(0.05)
   5255             vumetermessage(' ')
   5256             return
   5257 
   5258 def middlebutton():
   5259     with term.cbreak():
   5260         val = term.inkey(timeout=0)
   5261     if val.is_sequence:
   5262         event = val.name
   5263         #print(event)
   5264     elif val:
   5265         event = val
   5266         #print(event)
   5267     else:
   5268         event = ''
   5269     if i2cbuttons == True:
   5270         readbus = bus.read_byte_data(DEVICE,GPIOB)
   5271         readbus2 = bus.read_byte_data(DEVICE,GPIOA)
   5272         if readbus != 255:
   5273             print('i2cbutton pressed: ' + str(readbus))
   5274         if readbus2 != 247:
   5275             print('i2cbutton pressed: ' + str(readbus2))
   5276     else:
   5277         readbus = 255
   5278         readbus2 = 247
   5279     pressed = ''
   5280     if event == 'KEY_ENTER' or event == 10 or event == 13 or (readbus == 247 and readbus2 == 247):
   5281         pressed = 'middle'
   5282         return True
   5283     return False
   5284 
   5285 def flushbutton():
   5286     with term.cbreak():
   5287         while True:
   5288             inp = term.inkey(timeout=0)
   5289             #print('flushing ' + repr(inp))
   5290             if inp == '':
   5291                 break
   5292 
   5293 def getbutton(lastbutton, buttonpressed, buttontime, holdbutton):
   5294     global i2cbuttons, serverstate, nextstatus, process, que, gonzopictrl_ip, recording, onlysound, filmname, filmfolder, scene, shot, take, selected, camera, loadfilmsettings, selected, newfilmname, recordwithports
   5295     #Check controller
   5296     pressed = ''
   5297     nextstatus = ''
   5298     try:
   5299         if process.is_alive() == False and serverstate == 'on':
   5300             nextstatus = que.get()
   5301             if "*" in nextstatus:
   5302                 gonzopictrl_ip = nextstatus.split('*')[1]
   5303                 nextstatus = nextstatus.split('*')[0]
   5304                 print('gonzopictrl ip:' + gonzopictrl_ip)
   5305             process = Process(target=listenforclients, args=("0.0.0.0", port, que))
   5306             process.start()
   5307             if 'SELECTED' in nextstatus:
   5308                 try:
   5309                     selected=int(nextstatus.split(':')[1])
   5310                 except:
   5311                     print('wtf?')
   5312             if nextstatus=="PICTURE":
   5313                 pressed="picture"
   5314             elif nextstatus=="UP":
   5315                 pressed="up"
   5316             elif nextstatus=="DOWN":
   5317                 pressed="down"
   5318             elif nextstatus=="LEFT":
   5319                 pressed="left"
   5320             elif nextstatus=="RIGHT":
   5321                 pressed="right"
   5322             elif nextstatus=="VIEW":
   5323                 pressed="view"
   5324             elif nextstatus=="MIDDLE":
   5325                 pressed="middle"
   5326             elif nextstatus=="DELETE":
   5327                 pressed="remove"
   5328             elif nextstatus=="RECORD":
   5329                 pressed="record"
   5330             elif nextstatus=="REC":
   5331                 pressed="record_now"
   5332             elif nextstatus=="STOP":
   5333                 if recording == True:
   5334                     pressed="record"
   5335             elif nextstatus=="STOPRETAKE":
   5336                 if recording == True:
   5337                     pressed="retake"
   5338             elif nextstatus=="RECSOUND":
   5339                 if recording==False:
   5340                     pressed="record"
   5341                     onlysound=True
   5342             elif nextstatus=="PLACEHOLDER":
   5343                 pressed="insert_shot"
   5344             elif nextstatus=="TAKEPLACEHOLDER":
   5345                 pressed="insert_take"
   5346             elif nextstatus=="NEWSCENE":
   5347                 pressed="new_scene"
   5348             elif "NEWFILM:" in nextstatus:
   5349                 newfilmname = nextstatus.split(':')[1]
   5350                 pressed="new_film"
   5351             elif "SYNCIP:" in nextstatus:
   5352                 pressed=nextstatus
   5353             elif "SYNCDONE" in nextstatus:
   5354                 pressed=nextstatus
   5355             elif "RETAKE" in nextstatus:
   5356                 if recordwithports == True:
   5357                     pressed="retake"
   5358                 else:
   5359                     pressed="retake_now"
   5360             elif "RETAKE:" in nextstatus:
   5361                 pressed=nextstatus
   5362             elif "SCENE:" in nextstatus:
   5363                 pressed=nextstatus
   5364             elif "SHOT:" in nextstatus:
   5365                 pressed=nextstatus
   5366             elif "REMOVE:" in nextstatus:
   5367                 pressed=nextstatus
   5368             elif "Q:" in nextstatus:
   5369                 pressed=nextstatus
   5370             elif "CAMERA:" in nextstatus:
   5371                 pressed=nextstatus
   5372             elif "move" in nextstatus:
   5373                 pressed=nextstatus
   5374             elif "copy" in nextstatus:
   5375                 pressed=nextstatus
   5376             elif "paste" in nextstatus:
   5377                 pressed="insert"
   5378             elif "MAKEPLACEHOLDERS:" in nextstatus:
   5379                 pressed=nextstatus
   5380             #print(nextstatus)
   5381     except:
   5382         #print('process not found')
   5383         pass
   5384 
   5385     with term.cbreak():
   5386         val = term.inkey(timeout=0)
   5387     if val.is_sequence:
   5388         event = val.name
   5389         #print(event)
   5390         flushbutton()
   5391     elif val:
   5392         event = val
   5393         #print(event)
   5394         flushbutton()
   5395     else:
   5396         event = ''
   5397     keydelay = 0.08
   5398     if i2cbuttons == True:
   5399         readbus = bus.read_byte_data(DEVICE,GPIOB)
   5400         readbus2 = bus.read_byte_data(DEVICE,GPIOA)
   5401         if readbus == 0:
   5402             readbus = 255
   5403         if readbus2 == 0:
   5404             readbus2 = 247
   5405         if readbus != 255:
   5406             print('i2cbutton readbus pressed: ' + str(readbus))
   5407         if readbus2 != 247:
   5408             print('i2cbutton readbus2 pressed: ' + str(readbus2))
   5409     else:
   5410         readbus = 255
   5411         readbus2 = 247
   5412     if buttonpressed == False:
   5413         #if event != '':
   5414         #    print(term.clear+term.home)
   5415         if event == 27:
   5416             pressed = 'quit'
   5417         elif event == 'KEY_ENTER' or event == 10 or event == 13 or (readbus == 247 and readbus2 == 247):
   5418             pressed = 'middle'
   5419         elif event == 'KEY_UP' or (readbus == 191 and readbus2 == 247):
   5420             pressed = 'up'
   5421         elif event == 'KEY_DOWN' or (readbus == 254 and readbus2 == 247):
   5422             pressed = 'down'
   5423         elif event == 'KEY_LEFT' or (readbus == 239 and readbus2 == 247):
   5424             pressed = 'left'
   5425         elif event == 'KEY_RIGHT' or (readbus == 251 and readbus2 == 247):
   5426             pressed = 'right'
   5427         elif event == 'KEY_PGUP' or event == ' ' or (readbus == 127 and readbus2 == 247):
   5428             pressed = 'record'
   5429         elif event == 'KEY_PGDOWN' or (readbus == 253 and readbus2 == 247):
   5430             pressed = 'retake'
   5431         elif event == 'KEY_TAB' or readbus2 == 246:
   5432             pressed = 'view'
   5433         elif event == 'KEY_DELETE' or (readbus == 223 and readbus2 == 247):
   5434             pressed = 'remove'
   5435         elif event == 'KEY_BACKSPACE':
   5436             pressed = 'remove'
   5437         elif event == 'N' or (readbus2 == 245 and readbus == 191):
   5438             pressed = 'peak'
   5439         elif event == 'S' or (readbus2 == 245 and readbus == 223):
   5440             pressed = 'screen'
   5441         elif event == 'A' or (readbus2 == 245 and readbus == 127):
   5442             pressed = 'showmenu'
   5443         elif event == 'O' or (readbus2 == 245 and readbus == 239):
   5444             pressed = 'changemode'
   5445         elif event == 'H' or (readbus2 == 245 and readbus == 247):
   5446             pressed = 'showhelp'
   5447         elif event == 'P' or (readbus2 == 245 and readbus == 253):
   5448             pressed = 'insert'
   5449         elif event == 'C' or (readbus2 == 244):
   5450             pressed = 'copy'
   5451         elif event == 'M' or (readbus2 == 245 and readbus == 254):
   5452             pressed = 'move'
   5453         elif event == '|' or (readbus2 == 245 and readbus == 251):
   5454             pressed = 'split'
   5455         #elif readbus2 == 247:
   5456         #    pressed = 'shutdown'
   5457         #if pressed != '':
   5458             #print(pressed)
   5459         buttontime = time.time()
   5460         holdbutton = pressed
   5461         buttonpressed = True
   5462     if readbus == 255 and event == '' and nextstatus == '' :
   5463         buttonpressed = False
   5464     if float(time.time() - buttontime) > 0.2 and buttonpressed == True:
   5465         if holdbutton == 'up' or holdbutton == 'down' or holdbutton == 'right' or holdbutton == 'left' or holdbutton == 'shutdown' or holdbutton == 'remove':
   5466             pressed = holdbutton
   5467             keydelay = 0.1
   5468     if time.time() - buttontime > 2 and buttonpressed == True:
   5469         keydelay = 0.1
   5470     if time.time() - buttontime > 6 and buttonpressed == True:
   5471         keydelay = 0.05
   5472     if time.time() - buttontime > 8 and buttonpressed == True:
   5473         keydelay = 0.08
   5474     if time.time() - buttontime > 10 and buttonpressed == True:
   5475         keydelay = 0.01
   5476     return pressed, buttonpressed, buttontime, holdbutton, event, keydelay
   5477 
   5478 def startinterface():
   5479     call(['./startinterface.sh &'], shell = True)
   5480 
   5481 def stopinterface(camera):
   5482     try:
   5483         camera.stop_preview()
   5484         camera.close()
   5485     except:
   5486         print('no camera to close')
   5487     os.system('pkill arecord')
   5488     os.system('pkill startinterface')
   5489     os.system('pkill tarinagui')
   5490     os.system('sudo pkill -9 -f gonzopi_menu.py')
   5491     #run_command('sudo systemctl stop apache2')
   5492     return camera
   5493 
   5494 def startcamera(lens, fps):
   5495     global camera_model, fps_selection, fps_selected, cammode
   5496     camera = picamera.PiCamera()
   5497     if cammode == 'film':
   5498         reso=(1920,1080)
   5499     elif cammode == 'picture':
   5500         reso=(4056,3040)
   5501     camera.resolution = reso #tested modes 1920x816, 1296x552/578, v2 1640x698, 1640x1232, hqbinned 2028x1080, full 4056x3040
   5502     #Background image
   5503     underlay = None
   5504     bakgimg = gonzopifolder + '/extras/bakg.jpg'
   5505     displaybakg(camera, bakgimg, underlay, 2)
   5506     #lensshade = ''
   5507     #npzfile = np.load('lenses/' + lens)
   5508     #lensshade = npzfile['lens_shading_table']
   5509     #
   5510     #camera frame rate sync to audio clock
   5511     #
   5512     camera_model, camera_revision , filmfolder = getconfig(camera)
   5513     if os.path.isdir(filmfolder) == False:
   5514         os.makedirs(filmfolder)
   5515     # v1 = 'ov5647'
   5516     # v2 = ? 
   5517     logger.info("picamera version is: " + camera_model + ' ' + camera_revision)
   5518     if camera_model == 'imx219':
   5519         #table = read_table('lenses/' + lens)
   5520         #camera.lens_shading_table = table
   5521         camera.framerate = 24.97
   5522     elif camera_model == 'ov5647':
   5523         #table = read_table('lenses/' + lens)
   5524         camera.lens_shading_table = table
   5525         # Different versions of ov5647 with different clock speeds, need to make a config file
   5526         # if there's more frames then the video will be longer when converting it to 25 fps,
   5527         # I try to get it as perfect as possible with trial and error.
   5528         # ov5647 Rev C
   5529         if camera_revision == 'rev.C': 
   5530             #camera.framerate = 26.03
   5531             fps_selection=[5,8,10,11,12,13,14,15,26.03,35,49]
   5532             fps=fps_selection[fps_selected]
   5533             camera.framerate = fps 
   5534         # ov5647 Rev D"
   5535         if camera_revision == 'rev.D':
   5536             #camera.framerate = 23.15
   5537             fps_selection=[5,8,10,11,12,13,14,15,23.15,35,49]
   5538             fps=fps_selection[fps_selected]
   5539             camera.framerate = fps 
   5540     elif camera_model == 'imx477':
   5541         #fps_selection=[5,15,24.985,35,49]
   5542         #if sound is gettin before pic add 0.001
   5543         fps_selection=[5,8,10,11,12,13,14,15,24.989,35,49]
   5544         fps=fps_selection[fps_selected]
   5545         camera.framerate = fps 
   5546     else:
   5547         camera.framerate = fps
   5548     camera.crop = (0, 0, 1.0, 1.0)
   5549     #stabilization does not work in firmware
   5550     #camera.video_stabilization = True
   5551     camera.led = False
   5552     #lens_shading_table = np.zeros(camera._lens_shading_table_shape(), dtype=np.uint8) + 32
   5553     #camera.lens_shading_table = lens_shading_table
   5554     camera.start_preview()
   5555     camera.awb_mode = 'auto'
   5556     time.sleep(1)
   5557     return camera
   5558 
   5559 def gonzopiserver(state):
   5560     #Gonzopi server
   5561     if state == True:
   5562         #Try to run apache
   5563         try:
   5564             run_command('sudo systemctl start apache2')
   5565             os.system("sudo ln -sf -t "+gonzopifolder+"/srv/static/ " + filmfolder)
   5566             os.system("sudo chown -h www-data "+gonzopifolder+"/srv/static/gonzopifilms")
   5567             return 'on'
   5568         except:
   5569             os.system("sudo chown -h pi "+gonzopifolder+"/srv/static/gonzopifilms")
   5570             writemessage("could not run gonzopi server")
   5571             time.sleep(2)
   5572             return 'off'
   5573     if state == False:
   5574         run_command('sudo systemctl stop apache2')
   5575         return 'off'
   5576 
   5577 if __name__ == '__main__':
   5578     import sys
   5579     try:
   5580         main()
   5581     except:
   5582         os.system('pkill arecord')
   5583         os.system('pkill startinterface')
   5584         os.system('pkill tarinagui')
   5585         os.system('sudo pkill -9 -f gonzopi_menu.py')
   5586         print('Unexpected error : ', sys.exc_info()[0], sys.exc_info()[1])