gonzopi

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

gonzopi.py (237093B)


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