gonzopi

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

gonzopi.py (244824B)


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