File: renderconsumer.py

package info (click to toggle)
flowblade 2.24-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 49,320 kB
  • sloc: python: 69,104; xml: 2,604; sh: 121; javascript: 28; makefile: 12
file content (722 lines) | stat: -rw-r--r-- 27,075 bytes parent folder | download | duplicates (3)
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
"""
    Flowblade Movie Editor is a nonlinear video editor.
    Copyright 2012 Janne Liljeblad.

    This file is part of Flowblade Movie Editor <https://github.com/jliljebl/flowblade/>.

    Flowblade Movie Editor 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 3 of the License, or
    (at your option) any later version.

    Flowblade Movie Editor 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 Flowblade Movie Editor.  If not, see <http://www.gnu.org/licenses/>.
"""

"""
Module contains objects and methods needed to create render consumers.
"""

try:
    import mlt7 as mlt
except:
    import mlt
import time
import threading
import xml.dom.minidom
import os
import subprocess

import appconsts
import editorpersistance
import mltenv
import respaths
import translations

# File describing existing encoding and quality options
RENDER_ENCODING_FILE = "/res/render/renderencoding.xml"

# Node, attribute names.
NAME = "name"
TYPE = "type"
ID = "id"
EXTENSION = "extension"
RESIZABLE = "resize"
ARGS = "args"
REPLACED_VALUES = "replvalues"
ADDED_ATTRIBUTES = "addargs"
BITRATE_OPTION = "boption"
QUALITY_GROUP = "qualityqroup"
ENCODING_OPTION = "encodingoption"
PROXY_ENCODING_OPTION = "proxyencodingoption"
QGROUP = "qgroup"
DEFAULT_INDEX = "defaultindex"
PROFILE = "profile"
QUALITY = "quality"
BITRATE = "bitrate"
AUDIO_DESCRIPTION = "audiodesc"
NON_USER = "nonuser"
FFMPEG_GPU_ENC = "ffmpeggpuenc"
PRESET_GROUP = appconsts.PRESET_GROUP
PRESET_GROUP_H264 = appconsts.PRESET_GROUP_H264
PRESET_GROUP_NVENC = appconsts.PRESET_GROUP_NVENC 
PRESET_GROUP_VAAPI = appconsts.PRESET_GROUP_VAAPI 
PRESET_GROUP_MPEG = appconsts.PRESET_GROUP_MPEG 
PRESET_GROUP_LOSSLESS = appconsts.PRESET_GROUP_LOSSLESS
PRESET_GROUP_IMAGE_SEQUENCE = appconsts.PRESET_GROUP_IMAGE_SEQUENCE
PRESET_GROUP_AUDIO = appconsts.PRESET_GROUP_AUDIO
PRESET_GROUP_MISC = appconsts.PRESET_GROUP_MISC 
PRESET_GROUP_ALPHA = appconsts.PRESET_GROUP_ALPHA 

# ffmpeg arg values sometimes need equals signs in them.
EQUALS_SIGN_ENCODING = "@#@#"

# GPU encoding availability.
FFMPEG_TEST = ["ffmpeg", "-version"]

# These are filled here with all possible GPU encodings, and then rendergputest.py 
# uses these to test and make available GPU encodings.
NVENC_encs = []
VAAPI_encs = []

# Default encoding name.
DEFAULT_ENCODING_NAME = "H.264 / .mp4" 

# Replace strings and attribute values.
BITRATE_RPL = "%BITRATE%"
VARIABLE_VAL = "%VARIABLE%"
SCREEN_SIZE_RPL = "%SCREENSIZE%"
ASPECT_RPL = "%ASPECT%"

render_encoding_doc = None
encoding_options = []
categorized_encoding_options = []
not_supported_encoding_options = []
quality_option_groups = {}
quality_option_groups_default_index = {}
non_user_encodings = []
proxy_encodings = None

# We pick this up on init to get alpha encoding later on request.
_default_alpha_enc_opt = None
        
# This is used to turn performance settings off for proxy rendering.
performance_settings_enabled = True

# replace empty strings with None values
def _get_attribute(node, attr_name):
    value = node.getAttribute(attr_name)
    if value == "":
        return None
    
    return value

def get_encoding_index(encoding):
    for i in range(0, len(encoding_options)):
        if encoding == encoding_options[i]:
            return i
            
    return -1

def get_default_alpha_enc_quality_ext():
    if _default_alpha_enc_opt == None:
        return (-1, None, None)
    return (get_encoding_index(_default_alpha_enc_opt), _default_alpha_enc_opt.quality_default_index, _default_alpha_enc_opt.extension)



class QualityOption:
    """
    A render quality option for an EncodingOption.
    
    Values of mlt render consumer properties (usually bitrate) that equal 
    key expressions are replaced with corresponding values.
    """
    def __init__(self, quality_node):
        self.name = _get_attribute(quality_node, NAME)
        # Replaced render arguments
        replaced_values_str = _get_attribute(quality_node, REPLACED_VALUES)
        self.replaced_expressions = []
        self.replace_map = {}
        if replaced_values_str != None:
            tokens = replaced_values_str.split(";")
            for token in tokens:
                token_sides = token.split(" ")
                self.replaced_expressions.append(token_sides[0])
                self.replace_map[token_sides[0]] = token_sides[1]
        # Added render arguments
        added_atrrs_str = _get_attribute(quality_node, ADDED_ATTRIBUTES)
        self.add_map = {}
        if added_atrrs_str != None:
            tokens = added_atrrs_str.split(" ")
            for token in tokens:
                token_sides = token.split("=")
                self.add_map[token_sides[0]] = token_sides[1]

class EncodingOption:
    """
    An object that groups together vcodoc, acodec, format and quality options group.
    Object is used to set mlt render consumer properties.
    """
    def __init__(self, option_node):
        self.name = _get_attribute(option_node, NAME)
        self.type = _get_attribute(option_node, TYPE)
        self.presetgroup = _get_attribute(option_node, PRESET_GROUP)
        self.resizable = (_get_attribute(option_node, RESIZABLE) == "True")
        self.extension = _get_attribute(option_node, EXTENSION)
        self.nonuser = _get_attribute(option_node, NON_USER)
        self.quality_qroup_id = _get_attribute(option_node, QGROUP)
        self.quality_options = quality_option_groups[self.quality_qroup_id]
        self.ffmpeggpuenc =  _get_attribute(option_node, FFMPEG_GPU_ENC)
        try:
            quality_default_index = int(quality_option_groups_default_index[self.quality_qroup_id])
        except KeyError:
            quality_default_index = None
        self.quality_default_index = quality_default_index
        self.audio_desc = _get_attribute(option_node, AUDIO_DESCRIPTION)
        profile_node = option_node.getElementsByTagName(PROFILE).item(0)
        self.attr_string =  _get_attribute(profile_node, ARGS)
        self.acodec = None
        self.vcodec = None
        self.format = None

        tokens = self.attr_string.split(" ")
        for token in tokens:
            token_sides = token.split("=")
            if token_sides[0] == "acodec":
                self.acodec = token_sides[1]
            elif token_sides[0] == "vcodec":
                self.vcodec = token_sides[1]
            elif token_sides[0] == "f":
                self.format = token_sides[1]

        self.supported, self.err_msg = mltenv.render_profile_supported(self.format, 
                                                         self.vcodec,
                                                         self.acodec)
                                                         
    def get_args_vals_tuples_list(self, profile, quality_option=None):
        # Encoding options
        tokens = self.attr_string.split(" ")
        args_tuples = []
        for token in tokens:
            # Get property keys and values
            token_sides = token.split("=")
            arg1 = str(token_sides[0])
            arg2 = str(token_sides[1])
            # Sometimes arg values need equals signs in them
            arg2 = arg2.replace(EQUALS_SIGN_ENCODING, "=")
            
            # Replace keyword values
            if arg2 == SCREEN_SIZE_RPL:
                arg2 = str(profile.width())+ "x" + str(profile.height())
            if arg2 == ASPECT_RPL:
                arg2 = "@" + str(profile.display_aspect_num()) + "/" + str(profile.display_aspect_den())

            # Replace keyword values from quality options values
            if quality_option != None:
                if arg2 in quality_option.replaced_expressions:
                    arg2 = str(quality_option.replace_map[arg2])
            args_tuples.append((arg1, arg2))
        
        return args_tuples

    def get_audio_description(self):
        if self.audio_desc == None:
            desc = "Not available"
        else:
            desc = self.audio_desc 
        return "<small>" + desc + "</small>"

        
def load_render_profiles():
    """
    Load render profiles from xml into DOM at start-up and build
    object tree.
    """
    print("Loading render profiles...")
    file_path = respaths.ROOT_PATH + RENDER_ENCODING_FILE
    global render_encoding_doc
    render_encoding_doc = xml.dom.minidom.parse(file_path)

    ret_code = _test_command(FFMPEG_TEST, True)
    if (ret_code == 0):
        print("ffmpeg CLI available")
    else:
        print("ffmpeg CLI NOT available")

    # Create quality option groups
    global quality_option_groups
    qgroup_nodes = render_encoding_doc.getElementsByTagName(QUALITY_GROUP)
    for qgnode in qgroup_nodes:
        quality_qroup = []
        group_key = _get_attribute(qgnode, ID)
        group_default_index = _get_attribute(qgnode, DEFAULT_INDEX)
        if group_default_index != None: 
            quality_option_groups_default_index[group_key] = group_default_index
        option_nodes = qgnode.getElementsByTagName(QUALITY)
        for option_node in option_nodes:
            q_option = QualityOption(option_node)
            quality_qroup.append(q_option)
        quality_option_groups[group_key] = quality_qroup

    # Create encoding options
    global encoding_options, not_supported_encoding_options, non_user_encodings
    encoding_option_nodes = render_encoding_doc.getElementsByTagName(ENCODING_OPTION)
    for eo_node in encoding_option_nodes:
        encoding_option = EncodingOption(eo_node)
        if encoding_option.supported:
            if encoding_option.nonuser == None:
                encoding_options.append(encoding_option)
            else:
                non_user_encodings.append(encoding_option) 
        else:
            not_supported_encoding_options.append(encoding_option)

    # Create categorised structure.
    global categorized_encoding_options, NVENC_encs, VAAPI_encs
    H264_encs = []
    NVENC_encs = []
    VAAPI_encs = []
    MPEG_encs = []
    OGG_ETC_encs = []
    LOSSLESS_encs = []
    IMG_SEQ_encs = []
    AUDIO_encs = []
    ALPHA_encs = []
    
    for enc in encoding_options:
        if enc.presetgroup == PRESET_GROUP_H264:
            H264_encs.append((enc.name, enc))
        elif enc.presetgroup == PRESET_GROUP_NVENC:
            NVENC_encs.append((enc.name, enc))
        elif enc.presetgroup == PRESET_GROUP_VAAPI:
            VAAPI_encs.append((enc.name, enc))
        elif enc.presetgroup == PRESET_GROUP_MPEG:
            MPEG_encs.append((enc.name, enc))
        elif enc.presetgroup == PRESET_GROUP_MISC:
            OGG_ETC_encs.append((enc.name, enc))
        elif enc.presetgroup == PRESET_GROUP_LOSSLESS:
            LOSSLESS_encs.append((enc.name, enc))
        elif enc.presetgroup == PRESET_GROUP_IMAGE_SEQUENCE:
            IMG_SEQ_encs.append((enc.name, enc))
        elif enc.presetgroup == PRESET_GROUP_AUDIO:
            AUDIO_encs.append((enc.name, enc))
        elif enc.presetgroup == PRESET_GROUP_ALPHA:
            ALPHA_encs.append((enc.name, enc))

    if len(H264_encs) > 0:
        categorized_encoding_options.append((translations.get_encoder_group_name(PRESET_GROUP_H264), H264_encs))
    if len(MPEG_encs) > 0:
        categorized_encoding_options.append((translations.get_encoder_group_name(PRESET_GROUP_MPEG), MPEG_encs))
    if len(OGG_ETC_encs) > 0:
        categorized_encoding_options.append((translations.get_encoder_group_name(PRESET_GROUP_MISC), OGG_ETC_encs))
    if len(LOSSLESS_encs) > 0:
        categorized_encoding_options.append((translations.get_encoder_group_name(PRESET_GROUP_LOSSLESS), LOSSLESS_encs))
    if len(IMG_SEQ_encs) > 0:
        categorized_encoding_options.append((translations.get_encoder_group_name(PRESET_GROUP_IMAGE_SEQUENCE), IMG_SEQ_encs))

    if len(ALPHA_encs) > 0:
        categorized_encoding_options.append((translations.get_encoder_group_name(PRESET_GROUP_ALPHA), ALPHA_encs))
        # Save default alpha encoding option for later use
        global _default_alpha_enc_opt
        enc_name, enc = ALPHA_encs[0]
        _default_alpha_enc_opt = enc

    if len(AUDIO_encs) > 0:
        categorized_encoding_options.append((translations.get_encoder_group_name(PRESET_GROUP_AUDIO), AUDIO_encs))

    # If GPU rendering available it is added from rendergputest.py

    # Proxy encoding
    proxy_encoding_nodes = render_encoding_doc.getElementsByTagName(PROXY_ENCODING_OPTION)
    found_proxy_encodings = []
    for proxy_node in proxy_encoding_nodes:
        proxy_encoding_option = EncodingOption(proxy_node)
        if proxy_encoding_option.supported:
            found_proxy_encodings.append(proxy_encoding_option)
        else:
            print("proxy encoding " + proxy_encoding_option.name + " NOT AVAILABLE.")

    global proxy_encodings
    proxy_encodings = found_proxy_encodings

def remove_non_working_proxy_encodings(vcodec):
    global proxy_encodings
    proxy_encodings = [proxy_enc_opt for proxy_enc_opt in proxy_encodings if proxy_enc_opt.ffmpeggpuenc != vcodec]

def _test_command(bash_args_list, print_output=False):
    if print_output == False:
        process = subprocess.Popen(bash_args_list, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    else:
        process = subprocess.Popen(bash_args_list)
    
    out, err = process.communicate()
    
    if print_output == True:
        print(bash_args_list)
        print("return code:", process.returncode)

    return process.returncode

def get_default_render_consumer(file_path, profile):
    return get_render_consumer_for_encoding_and_quality(file_path, profile, 0, 10) # values get their meaning from /res/renderencoding.xml
                                                                                    # first <encodingoption> with 10th quality option
                                                                                    # should be H.264 with 10000 kb/s

def get_render_consumer_for_encoding_and_quality(file_path, profile, enc_opt_index, quality_opt_index):
    args_vals_list = get_args_vals_tuples_list_for_encoding_and_quality(profile,
                                                                       enc_opt_index,
                                                                       quality_opt_index)
        
    return get_mlt_render_consumer(file_path, profile, args_vals_list)

def get_render_consumer_for_encoding(file_path, profile, encoding_option):
    # Encoding options key, value list
    args_vals_list = encoding_option.get_args_vals_tuples_list(profile)

    return get_mlt_render_consumer(file_path, profile, args_vals_list)

def get_render_consumer_for_text_buffer(file_path, profile, buf):
    args_vals_list, error = get_ffmpeg_opts_args_vals_tuples_list(buf)
    if error != None:
        return (None, error)

    render_consumer = get_mlt_render_consumer(file_path, profile, args_vals_list)
    return (render_consumer, None)

def get_img_seq_render_consumer(file_path, profile, encoding_option):
    #render_path = "%1/%2-%05d.%3" + file_path
    args_vals_list = encoding_option.get_args_vals_tuples_list(profile)
    
    vcodec = None
    for arg_val in args_vals_list:
        arg, val = arg_val
        if arg == "vcodec":
            vcodec = val

    render_path = os.path.dirname(file_path) + "/" + os.path.basename(file_path).split(".")[0] + "_%05d." + encoding_option.extension
    
    consumer = mlt.Consumer(profile, "avformat", str(render_path))
    # Jan-2017 - SvdB - perf_value instead of -1
    if performance_settings_enabled == True:
        if editorpersistance.prefs.perf_drop_frames == True:
            perf_value = 1 * editorpersistance.prefs.perf_render_threads
        else:
            perf_value = -1 * editorpersistance.prefs.perf_render_threads
        consumer.set("real_time", perf_value)
    else:
        consumer.set("real_time", -1)
    consumer.set("rescale", "bicubic")
    consumer.set("vcodec", str(vcodec))

    return consumer

def get_img_seq_render_consumer_codec_ext(file_path, profile, vcodec, ext):
    render_path = os.path.dirname(file_path) + "/" + os.path.basename(file_path).split(".")[0] + "_%05d." + ext
    
    consumer = mlt.Consumer(profile, "avformat", str(render_path))
    # Jan-2017 - SvdB - perf_value instead of -1
    if performance_settings_enabled == True:
        if editorpersistance.prefs.perf_drop_frames == True:
            perf_value = 1 * editorpersistance.prefs.perf_render_threads
        else:
            perf_value = -1 * editorpersistance.prefs.perf_render_threads
        consumer.set("real_time", perf_value)
    else:
        consumer.set("real_time", -1)
    consumer.set("rescale", "bicubic")
    consumer.set("vcodec", str(vcodec))

    return consumer
    
def get_mlt_render_consumer(file_path, profile, args_vals_list):
    consumer = mlt.Consumer(profile, "avformat", str(file_path))
    # Jan-2017 - SvdB - perf_value instead of -1
    if performance_settings_enabled == True:
        if editorpersistance.prefs.perf_drop_frames == True:
            perf_value = 1 * editorpersistance.prefs.perf_render_threads
        else:
            perf_value = -1 * editorpersistance.prefs.perf_render_threads
        consumer.set("real_time", perf_value)
    else:
        consumer.set("real_time", -1)
    consumer.set("rescale", "bicubic")

    args_msg = ""
    for arg_val in args_vals_list:
        k, v = arg_val
        consumer.set(str(k), str(v))
        args_msg = args_msg + str(k) + "="+ str(v) + ", "
        
    args_msg = args_msg.strip(", ")

    return consumer

def get_args_vals_tuples_list_for_encoding_and_quality(profile, enc_opt_index, quality_opt_index):
    encoding_option = encoding_options[enc_opt_index]
    if quality_opt_index >= 0:
        quality_option = encoding_option.quality_options[quality_opt_index]
    else:
        quality_option = None

    args_vals_list = encoding_option.get_args_vals_tuples_list(profile, quality_option)
    
    # Quality options  key, value list
    if quality_option != None:
        for k, v in quality_option.add_map.items():
            args_vals_list.append((str(k), str(v)))
    
    return args_vals_list

def get_video_non_user_encodigs():
    video_non_user_encs = []
    for enc in non_user_encodings:
        if enc.type != "audio":
            video_non_user_encs.append(enc)

    return video_non_user_encs

def get_ffmpeg_opts_args_vals_tuples_list(buf):
    end = buf.get_end_iter()
    arg_vals = []
    for i in range(0, buf.get_line_count()):
        line_start = buf.get_iter_at_line(i)
        if i == buf.get_line_count() - 1:
            line_end = end
        else:
            line_end = buf.get_iter_at_line(i + 1)
        av_tuple, error = _parse_line(line_start, line_end, buf)
        if error != None:
            errs_str = _("Error on line ") + str(i + 1) + ": " + error + _("\nLine contents: ") \
                       + buf.get_text(line_start, line_end, include_hidden_chars=False)
            return (None, errs_str)
        if av_tuple != None:
            arg_vals.append(av_tuple)
    
    return (arg_vals, None)

def _parse_line(line_start, line_end, buf):
    line = buf.get_text(line_start, line_end, include_hidden_chars=False)
    if len(line) == 0:
        return (None, None)
    if line.find("=") == -1:
        return (None, _("No \'=\' found."))
    sides = line.split("=")
    if len(sides) != 2:
        k = sides[0].strip()
        rest = sides[1:len(sides)]
        v = ""
        for token in rest:
            v = v + token + "="
        v = v.strip("=")
        v = v.strip()
    else:
        k = sides[0].strip()
        v = sides[1].strip()
    if len(k) == 0:
        return (None, _("Arg name token is empty."))
    if len(v) == 0:
        return (None, _("Arg value token is empty."))
    if k.find(" ") != -1:
        return (None,  _("Whitespace in Arg name."))
    if v.find(" ") != -1:
        return (None,  _("Whitespace in Arg value."))

    return ((k,v), None)

def get_encoding_option(enc_opt_index):
    return encoding_options[enc_opt_index]



# Convenience function needed because FileRenderPlayer no longer stops on last
# frame with 'wait_for_producer_end_stop' set True and naked producer as producer.
# With tractor we get full length rendered and player stops correctly.
def get_producer_as_tractor(producer, last_frame):
    tractor = mlt.Tractor()
    multitrack = tractor.multitrack()
    track0 = mlt.Playlist(producer.profile())
    multitrack.connect(track0, 0)
    track0.insert(producer, 0, 0, last_frame)
    return tractor

def get_clipped_producer_as_tractor(producer, clip_in, clip_out):
    tractor = mlt.Tractor()
    multitrack = tractor.multitrack()
    track0 = mlt.Playlist(producer.profile())
    multitrack.connect(track0, 0)
    track0.insert(producer, 0, clip_in, clip_out)
    return tractor

class FileRenderPlayer(threading.Thread):
    def __init__(self, file_name, producer, consumer, start_frame, stop_frame):
        self.file_name = file_name
        self.producer = producer
        self.consumer = consumer
        self.start_frame = start_frame
        self.stop_frame = stop_frame
        self.stopped = False
        self.wait_for_producer_end_stop = True
        self.running = False
        self.has_started_running = False
        self.do_consumer_position_wait = True
        print("FileRenderPlayer started, start frame: " + str(self.start_frame) + ", stop frame: " + str(self.stop_frame))
        self.consumer_pos_stop_add = 1 # HACK!!! File renders work then this is one, screenshot render requires this to be 2 to work 
        threading.Thread.__init__(self)

    def run(self):
        
        self.consumer.set("plays", 1) # maybe not strictly necessary but default value here seems to  be 'None' which is wrong.
        
        self.running = True
        self.has_started_running = True
        self.connect_and_start()

        while self.running: # set false at shutdown() for abort

            if self.producer.frame() >= self.stop_frame:
                # This method of stopping makes sure that whole producer is rendered and written to disk
                # Used when producer out frame is last frame.
                if self.wait_for_producer_end_stop:

                    while self.producer.get_speed() > 0:
                        time.sleep(0.2)
                    while not self.consumer.is_stopped():
                        time.sleep(0.2)
                    
                # This method of stopping stops producer
                # and waits for consumer to reach that frame.
                # Used when producer out frame is NOT last frame.
                else:
                    self.producer.set_speed(0)
                    last_frame = self.producer.frame()
                    if self.do_consumer_position_wait == True:
                        while self.consumer.position() + self.consumer_pos_stop_add < last_frame:
                            time.sleep(0.2)

                    self.consumer.stop()
                                        
                self.running = False

            time.sleep(0.1)

        print("FileRenderPlayer stopped, producer frame: " + str(self.producer.frame()))

        self.stopped = True
                
    def shutdown(self):
        self.consumer.stop()
        self.producer.set_speed(0)
        self.running = False

    def connect_and_start(self):
        self.consumer.connect(self.producer)
        self.producer.set_speed(0)
        self.producer.seek(self.start_frame)
        self.producer.set_speed(1)
        self.consumer.start()

    def get_render_fraction(self):
        render_length = self.stop_frame - self.start_frame + 1
        if (self.producer.get_length() - 1) < 1:
            render_fraction = 1.0
        else:
            current_frame = self.producer.frame() - self.start_frame
            render_fraction = (float(current_frame)) / (float(render_length))
        if render_fraction > 1.0:
            render_fraction = 1.0
        return render_fraction


class XMLRenderPlayer(threading.Thread):
    def __init__(self, file_name, callback, data, rendered_sequence, project, player):
        self.file_name = file_name
        self.render_done_callback = callback
        self.data = data
        self.current_playback_frame = 0
        self.rendered_sequence = rendered_sequence
        self.project = project
        self.player = player
        
        threading.Thread.__init__(self)

    def run(self):
        print("Starting XML render")
        player = self.player

        # Stop all playback before producer is disconnected
        self.current_playback_frame = player.producer.frame()
        player.stop_ticker()
        player.consumer.stop()
        player.producer.set_speed(0)
        player.producer.seek(0)
        
        # Wait until producer is at start
        while player.producer.frame() != 0:
            time.sleep(0.1)
        
        # Get render producer
        timeline_producer = self.rendered_sequence.tractor

        # Get render consumer
        xml_consumer = mlt.Consumer(self.project.profile, "xml", str(self.file_name))

        # Connect and start rendering
        xml_consumer.connect(timeline_producer)
        xml_consumer.start()
        timeline_producer.set_speed(1)

        # Wait until done
        while xml_consumer.is_stopped() == False:
            print("In XML render wait loop...")
            time.sleep(0.1)
    
        print("XML render done")

        # Get app player going again
        player.connect_and_start()
        player.seek_frame(0)

        self.render_done_callback(self.data)


class XMLCompoundRenderPlayer(threading.Thread):
    def __init__(self, file_name, media_name, callback, tractor, project):
        self.file_name = file_name
        self.media_name = media_name
        self.render_done_callback = callback
        self.tractor = tractor
        self.project = project

        threading.Thread.__init__(self)

    def run(self):
        tractor = self.tractor
        tractor.set_speed(0)
        tractor.seek(0)
        
        # Wait until producer is at start
        while tractor.frame() != 0:
            time.sleep(0.1)

        # Get render consumer
        xml_consumer = mlt.Consumer(self.project.profile, "xml", str(self.file_name))

        # Connect and start rendering
        xml_consumer.connect(tractor)
        xml_consumer.start()
        tractor.set_speed(1)

        # Wait until done
        while xml_consumer.is_stopped() == False:
            print("In XML render wait loop...")
            time.sleep(0.1)
    
        print("XML compound clip render done")

        self.render_done_callback(self.file_name, self.media_name)