gonzopi

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

gonzopi.py (285321B)


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