Welcome to mirror list, hosted at ThFree Co, Russian Federation.

functions.py « kinoraw_tools - git.blender.org/blender-addons.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cdbac3dedd4ca8414131667a81ef1593e6ecab98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

import bpy
import os.path, operator, subprocess, random

from bpy.props import IntProperty
from bpy.props import FloatProperty
from bpy.props import EnumProperty
from bpy.props import BoolProperty
from bpy.props import StringProperty

imb_ext_image = [
    # IMG
    ".png", ".tga", ".bmp", ".jpg", ".jpeg", ".sgi", ".rgb",
    ".rgba", ".tif", ".tiff", ".tx", ".jp2", ".hdr", ".dds",
    ".dpx", ".cin", ".exr", ".rw2",
    # IMG QT
    ".gif", ".psd", ".pct", ".pict", ".pntg", ".qtif"]

imb_ext_audio = [
    ".wav", ".ogg", ".oga", ".mp3", ".mp2", ".ac3", ".aac",
    ".flac", ".wma", ".eac3", ".aif", ".aiff", ".m4a"]

imb_ext_movie = [
    ".avi", ".flc", ".mov", ".movie", ".mp4", ".m4v", ".m2v",
    ".m2t", ".m2ts", ".mts", ".mv", ".avs", ".wmv", ".ogv", ".ogg",
    ".dv", ".mpeg", ".mpg", ".mpg2", ".vob", ".mkv", ".flv",
    ".divx", ".xvid", ".mxf"]
    
movieextdict = [("1", ".avi", ""),
            ("2", ".flc", ""), ("3", ".mov", ""),
            ("4", ".movie", ""), ("5", ".mp4", ""),
            ("6", ".m4v", ""), ("7", ".m2v", ""),
            ("8", ".m2t", ""), ("9", ".m2ts", ""),
            ("10", ".mts", ""), ("11", ".mv", ""),
            ("12", ".avs", ""), ("13", ".wmv", ""),
            ("14", ".ogv", ""), ("15", ".dv", ""),
            ("16", ".mpeg", ""), ("17", ".mpg", ""),
            ("18", ".mpg2", ""), ("19", ".vob", ""),
            ("20", ".mkv", ""), ("21", ".flv", ""),
            ("22", ".divx", ""), ("23", ".xvid", ""), 
            ("24", ".mxf", "")]

# Functions



def initSceneProperties(context):
    # initSceneProperties is ONLY for varaibles that should 
    # be keeped with the blend file. Any other addon preferences
    # should go to the addon preferences operator in __init__
    try:
        if context.scene.kr_scn_init == True:
            return False
    except AttributeError:
        pass

    scn = context.scene

    # JUMP TO CUT
    bpy.types.Scene.kr_auto_markers = BoolProperty(
        name='kr_auto_markers',
        description='activate auto markers',
        default=False)
    scn.kr_auto_markers = False
    
    bpy.types.Scene.kr_in_marker = IntProperty(
        name='in',
        description='in frame position',
        min=-30000, max=30000,
        default=1)
    scn.kr_in_marker = 1
    
    bpy.types.Scene.kr_out_marker = IntProperty(
        name='out',
        description='out frame position',
        min=scn.kr_in_marker, max=30000,
        default=75)
    scn.kr_out_marker = 75
    
    # SEQUENCER EXTRA ACTIONS
    bpy.types.Scene.kr_default_fade_duration = IntProperty(
        name='Duration',
        description='Number of frames to fade',
        min=1, max=250,
        default=scn.render.fps)
    scn.kr_default_fade_duration = scn.render.fps
    
    bpy.types.Scene.kr_default_fade_amount = FloatProperty(
        name='Amount',
        description='Maximum value of fade',
        min=0.0,
        max=100.0,
        default=1.0)
    scn.kr_default_fade_amount = 1.0

    # RECURSIVE LOADER
    bpy.types.Scene.kr_recursive = BoolProperty(
        name='Recursive',
        description='Load in recursive folders',
        default=False)
    scn.kr_recursive = False

    bpy.types.Scene.kr_recursive_select_by_extension = BoolProperty(
        name='Recursive ext',
        description='Load only clips with selected extension',
        default=False)
    scn.kr_recursive_select_by_extension = False
    
    bpy.types.Scene.kr_default_ext = EnumProperty(
        items=movieextdict,
        name="ext enum",
        default="3")
    scn.kr_default_ext = "3"
    
    bpy.types.Scene.kr_scn_init = BoolProperty(
        name='Init',
        default=False)
    scn.kr_scn_init = True

    return True

def get_selected_strips(context):
    "return a list of selected strips"
    strips=[]
    for i in context.scene.sequence_editor.sequences_all:
        if i.select == True:
            strips.append(i)
    return strips

def create_folder(path):
    if not os.path.isdir(bpy.path.abspath(path)):
        folder = bpy.path.abspath(path)
        command = "mkdir "+folder
        subprocess.call(command,shell=True)

def add_marker(context, text, frame):
    scn = context.scene
    markers = scn.timeline_markers
    mark = markers.new(name=text)
    mark.frame = frame

def act_strip(context):
    try:
        return context.scene.sequence_editor.active_strip
    except AttributeError:
        return None

def detect_strip_type(filepath):
    extension = os.path.splitext(filepath)[1]
    extension = extension.lower()
    if extension in imb_ext_image:
        type = 'IMAGE'
    elif extension in imb_ext_movie:
        type = 'MOVIE'
    elif extension in imb_ext_audio:
        type = 'SOUND'
    else:
        type = None

    return type

# recursive load functions 

def getpathfrombrowser(context):
    '''
    returns path from filebrowser
    '''
    scn = context.scene
    for a in context.window.screen.areas:
        if a.type == 'FILE_BROWSER':
            params = a.spaces[0].params
            break
    try:
        params
    except UnboundLocalError:
        #print("no browser")
        self.report({'ERROR_INVALID_INPUT'}, 'No visible File Browser')
        return {'CANCELLED'}
    path = params.directory
    return path

def getfilepathfrombrowser(context):
    '''
    returns path and file from filebrowser
    '''
    scn = context.scene
    for a in context.window.screen.areas:
        if a.type == 'FILE_BROWSER':
            params = a.spaces[0].params
            break
    try:
        params
    except UnboundLocalError:
        #print("no browser")
        #self.report({'ERROR_INVALID_INPUT'}, 'No visible File Browser')
        return {'CANCELLED'}

    if params.filename == '':
        #print("no file selected")
        #self.report({'ERROR_INVALID_INPUT'}, 'No file selected')
        return {'CANCELLED'}
    path = params.directory
    filename = params.filename
    return path, filename

def setpathinbrowser(context, path, file):
    '''
    set path and file in the filebrowser
    '''
    scn = context.scene
    for a in context.window.screen.areas:
        if a.type == 'FILE_BROWSER':
            params = a.spaces[0].params
            break
    try:
        params
    except UnboundLocalError:
        #print("no browser")
        self.report({'ERROR_INVALID_INPUT'}, 'No visible File Browser')
        return {'CANCELLED'}

    params.directory = path
    params.filename = file
    return path, params

def sortlist(filelist):
    '''
    given a list of tuplas (path, filename) returns a list sorted by filename
    '''
    filelist_sorted = sorted(filelist, key=operator.itemgetter(1))
    return filelist_sorted

def onefolder(context, recursive_select_by_extension, ext):
    '''
    returns a list of MOVIE type files from folder selected in file browser
    '''
    filelist = []
    path, filename = getfilepathfrombrowser(context)
    
    for i in movieextdict: 
        if i[0] == ext:
            extension = i[1].rpartition(".")[2]
            break

    scn = context.scene

    if detect_strip_type(path + filename) == 'MOVIE':
        if recursive_select_by_extension == True:
            #filtering by extension...
            for file in os.listdir(path):
                if file.rpartition(".")[2].lower() == extension:
                    filelist.append((path, file))
        else:
            #looking for all known extensions
            for file in os.listdir(path):
                for i in movieextdict:
                    if file.rpartition(".")[2].lower() == i[1].rpartition(".")[2]:
                        filelist.append((path, file))
    return (filelist)

def recursive(context, recursive_select_by_extension, ext):
    '''
    returns a list of MOVIE type files recursively from file browser
    '''
    filelist = []
    path = getpathfrombrowser(context)
    
    for i in movieextdict:
        if i[0] == ext:
            extension = i[1].rpartition(".")[2]
            break
    
    scn = context.scene        
    for root, dirs, files in os.walk(path):
        for file in files:
            if recursive_select_by_extension == True:
                #filtering by extension...
                if file.rpartition(".")[2].lower() == extension:
                    filelist.append((root, file))
            else:
                #looking for all known extensions
                for i in movieextdict:
                    if file.rpartition(".")[2].lower() == i[1].rpartition(".")[2]:
                        filelist.append((root, file))
    return filelist   

# jump to cut functions

def triminout(strip, sin, sout):

    """trim the strip to in and out, and returns 
    true if the strip is outside given in and out"""
    
    start = strip.frame_start + strip.frame_offset_start - strip.frame_still_start
    end = start + strip.frame_final_duration

    remove = False
    if end < sin: remove = True
    if start > sout: remove = True
    
    if end > sin:
        if start < sin:
            strip.select_right_handle = False
            strip.select_left_handle = True
            bpy.ops.sequencer.snap(frame=sin)
            strip.select_left_handle = False
    if start < sout:
        if end > sout:
            strip.select_left_handle = False
            strip.select_right_handle = True
            bpy.ops.sequencer.snap(frame=sout)
            strip.select_right_handle = False

    return remove


#------------ random editor functions.

def randompartition(lst,n,rand):
    division = len(lst) / float(n)
    lista = []
    for i in range(n):  lista.append(division)
    var=0
    for i in range(n-1):
        lista[i]+= random.randint(-int(rand*division),int(rand*division))
        var+=lista[i]
    if lista[n-1] != len(lst)-var:
        lista[n-1] = len(lst)-var
    random.shuffle(lista)
    division = len(lst) / float(n)
    count = 0
    newlist=[]
    for i in range(n):
        #print(lst[count : int(lista[i]-1)+count])
        newlist.append([lst[count : int(lista[i]-1)+count]])
        count += int(lista[i]) 
    return newlist

def randomframe(strip):
    #random frame between a and b
    a = strip.frame_start
    b = strip.frame_final_duration
    rand = a+int(random.random()*b)
    #print(a, a+b, rand)
    return rand

# ???
def get_matching_markers(scene, name=None):
    '''return a list of markers with same name 
     from the scene, or all markers if name is None'''
    selected_markers=[]
    markers = scene.timeline_markers
    for mark in markers:
        #print(mark.name, name)
        if mark.name == name or name==None:
            selected_markers.append(mark.frame)
    return selected_markers

# ???
def generate_subsets_list(number_of_subsets):
    #generate marker subsets list
    subset_list = []
    subset_names = ['A','B','C','D','E','F']
    for subset in range(number_of_subsets):
        subset_list.append(subset_names[subset])
    return subset_list


def get_marker_dict(scene, number_of_subsets):
    '''return a dict where: 
            keys = subset names
            values = list of markers'''
    #get markers from scene
    markers = scene.timeline_markers
    subset_list = generate_subsets_list(number_of_subsets)
    #generate dict with a list for each subset
    marker_dict = {}
    for subset in subset_list:
        list=get_matching_markers(scene, subset)
        marker_dict[subset] = list
    return marker_dict


def get_cut_dict(scene, number_of_subsets):
    '''return a dict where: 
            keys = markers in the scene + start and end
            values = duration in frames from key marker to next marker'''
    #generate cut_list
    
    list=get_matching_markers(scene)
    list.append(scene.frame_start)
    list.append(scene.frame_end)
    list.sort()
    #print("lista:",len(list),list)
    cut_dict ={}
    for i, j in enumerate(list):
        try:
            #print(j,list[i+1]-1-j)
            cut_dict[j] = list[i+1]-j
        except IndexError:
            continue  
    return cut_dict
    

def random_edit_from_random_subset(cut_dict, sources_dict):
    '''return a random edit from random subsets'''
    #generate subset list (strings)
    subset_list = generate_subsets_list(number_of_subsets)
    # copy sources_dict
    random_edit = []
    for cut in sorted(cut_dict.keys()):
        #escoge un subset al azar:   
        rand = random.randrange(number_of_subsets)
        subset = subset_list[rand]
        #check if source subset is empty
        print(len(sources_dict[subset]),subset)
        if len(sources_dict[subset]) == 0:
            sources_dict[subset] = get_matching_markers(selected_scene, subset)
            print("repeating "+ subset + " clips")
        marker = sources_dict[subset].pop()
        random_edit.append((cut, cut_dict[cut], subset, marker))
    return random_edit