tarinaretake

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

tarina.py (213405B)


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