tarinaretake

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

tarinaretake.py (214044B)


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