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

audio_tools.py « kinoraw_tools - git.blender.org/blender-addons.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d0278de01995458031a04321c63400752ae3f59a (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
import bpy, os
from bpy.props import IntProperty, StringProperty, BoolProperty
import subprocess

from . import functions


proxy_qualities = [  ( "1", "25%", "" ), ( "2", "50%", "" ),
                    ( "3", "75%", "" ), ( "4", "100%", "" )]
                    
#
#  ls *.sh | parallel -j 8 sh {}
#

# functions




def createsyncfile(filename):
    if not os.path.isfile(bpy.path.abspath(filename)):
        f = open(bpy.path.abspath(filename), "w")
        data = []

        try:
            f.writelines(data) # Write a sequence of strings to a file
        finally:
            f.close()


def readsyncfile(filename):
    try:
        file = open(bpy.path.abspath(filename))
        data = file.readlines()
        file.close()

        return data

    except IOError:
        pass


def writesyncfile(filename, data):
    try:
        f = open(bpy.path.abspath(filename), "w")
        try:
            for line in data:
                f.writelines(line) # Write a sequence of strings to a file
        finally:
            f.close()

    except IOError:
        pass


# classes


class ExtractWavOperator(bpy.types.Operator):
    """ Use ffmpeg to extract audio from video and import it synced"""
    bl_idname = "sequencer.extract_wav_operator"
    bl_label = "Extract Wav from movie strip Operator"

    @staticmethod
    def has_sequencer(context):
        return (context.space_data.view_type\
        in {'SEQUENCER', 'SEQUENCER_PREVIEW'})

    @classmethod
    def poll(self, context):
        strip = functions.act_strip(context)
        scn = context.scene
        if scn and scn.sequence_editor and scn.sequence_editor.active_strip:
            return strip.type in ('MOVIE')
        else:
            return False



    def execute(self, context):

        preferences = context.user_preferences
        audio_dir = preferences.addons[__package__].preferences.audio_dir

        functions.create_folder(bpy.path.abspath(audio_dir))

        for strip in context.selected_editable_sequences:

            # get filename
            if strip.type == "MOVIE":
                filename = bpy.path.abspath(strip.filepath)
                newfilename = bpy.path.abspath(strip.filepath).rpartition(
                    "/")[2]
                fileoutput = os.path.join(bpy.path.abspath(audio_dir),
                             newfilename)+".wav"

            # check for wav existing file
            if not os.path.isfile(fileoutput):
                #if not, extract the file
                extract_audio = "ffmpeg -i '{}' -acodec pcm_s16le -ac 2 {}".\
                format(filename, fileoutput)
                print(extract_audio)
                os.system(extract_audio)
            else:
                print("ya existe")

            if strip.type == "MOVIE":
                # import the file and trim in the same way the original
                bpy.ops.sequencer.sound_strip_add(filepath=fileoutput,\
                 frame_start=strip.frame_start, channel=strip.channel+1,\
                 replace_sel=True, overlap=False, cache=False)

                # Update scene
                context.scene.update()

                newstrip = context.scene.sequence_editor.active_strip

                 # deselect all other strips
                for i in context.selected_editable_sequences:
                    if i.name != newstrip.name:
                        i.select=False

                # Update scene
                context.scene.update()

                #Match the original clip's length
                
                newstrip.frame_start = strip.frame_start - strip.animation_offset_start

                #print(newstrip.name)
                functions.triminout(newstrip,
                            strip.frame_start + strip.frame_offset_start,
                            strip.frame_start + strip.frame_offset_start + \
                            strip.frame_final_duration)

        return {'FINISHED'}



class ExternalAudioSetSyncOperator(bpy.types.Operator):
    """get sync info from selected audio and video strip and store it into a text file """
    bl_idname = "sequencer.external_audio_set_sync"
    bl_label = "set sync info"

    @staticmethod
    def has_sequencer(context):
        return (context.space_data.view_type\
        in {'SEQUENCER', 'SEQUENCER_PREVIEW'})

    @classmethod
    def poll(cls, context):
        if cls.has_sequencer(context):
            if len(context.selected_editable_sequences) == 2:
                types = []
                for i in context.selected_editable_sequences:
                    types.append(i.type)
                if 'MOVIE' and 'SOUND' in types:
                    return True
                else:
                    return False


    def execute(self, context):

        preferences = context.user_preferences
        filename = preferences.addons[__package__].preferences.audio_external_filename

        for strip in context.selected_editable_sequences:
            if strip.type == "MOVIE":
                moviestrip = strip
            elif strip.type == "SOUND":
                soundstrip = strip

        offset = str(moviestrip.frame_start - soundstrip.frame_start)

        data1 = readsyncfile(filename)
        data2 = []
        newline = moviestrip.filepath + " " + soundstrip.filepath + " " + offset + "\n"

        if data1 != None:
            repeated = False
            for line in data1:
                if line.split()[0] == moviestrip.filepath and line.split()[1] == soundstrip.filepath:
                    data2.append(newline)
                    repeated = True
                else:
                    data2.append(line)
            if not repeated:
                data2.append(newline)
        else:
            data2.append(newline)

        createsyncfile(filename)
        writesyncfile(filename, data2)

        return {'FINISHED'}


class ExternalAudioReloadOperator(bpy.types.Operator):
    """ reload external audio synced to selected movie strip acording to info from a text file """
    bl_idname = "sequencer.external_audio_reload"
    bl_label = "reload external audio"

    @staticmethod
    def has_sequencer(context):
        return (context.space_data.view_type\
        in {'SEQUENCER', 'SEQUENCER_PREVIEW'})

    @classmethod
    def poll(cls, context):
        if cls.has_sequencer(context):
            if len(context.selected_editable_sequences) == 1:
                if context.selected_editable_sequences[0].type == 'MOVIE':
                    return True
                else:
                    return False


    def execute(self, context):

        preferences = context.user_preferences
        filename = preferences.addons[__package__].preferences.audio_external_filename

        data = readsyncfile(filename)

        for strip in context.selected_editable_sequences:

            sounds =  []
            for line in data:
                if line.split()[0] == strip.filepath:
                    moviefile = bpy.path.abspath(line.split()[0])
                    soundfile = bpy.path.abspath(line.split()[1])
                    offset = int(line.split()[2])
                    sounds.append((soundfile, offset))


            for soundfile, offset in sounds:
                print(soundfile,offset)
                print(strip.filepath)
                # find start frame for sound strip (using offset from file)
                sound_frame_start = strip.frame_start - strip.animation_offset_start - offset

                # import the file and trim in the same way the original
                bpy.ops.sequencer.sound_strip_add(filepath=soundfile,\
                 frame_start=sound_frame_start, channel=strip.channel+1,\
                 replace_sel=True, overlap=False, cache=False)

                # Update scene
                context.scene.update()

                newstrip = context.scene.sequence_editor.active_strip

                 # deselect all other strips
                for i in context.selected_editable_sequences:
                    if i.name != newstrip.name:
                        i.select=False

                # Update scene
                context.scene.update()

                # trim sound strip like original one
                functions.triminout(newstrip,
                            strip.frame_start + strip.frame_offset_start,
                            strip.frame_start + strip.frame_offset_start + \
                            strip.frame_final_duration)

        return {'FINISHED'}


class AudioToolPanel(bpy.types.Panel):
    """  """
    bl_label = "Audio Tools"
    bl_idname = "OBJECT_PT_AudioTool"
    bl_space_type = 'SEQUENCE_EDITOR'
    bl_region_type = 'UI'

    @classmethod
    def poll(self, context):
        if context.space_data.view_type in {'SEQUENCER', 'SEQUENCER_PREVIEW'}:
            strip = functions.act_strip(context)
            scn = context.scene
            preferences = context.user_preferences
            prefs = preferences.addons[__package__].preferences
            if scn and scn.sequence_editor and scn.sequence_editor.active_strip:
                if prefs.use_audio_tools:
                    return True
        else:
            return False

    def draw_header(self, context):
        layout = self.layout
        layout.label(text="", icon="PLAY_AUDIO")

    def draw(self, context):

        preferences = context.user_preferences
        prefs = preferences.addons[__package__].preferences

        strip = functions.act_strip(context)

        if strip.type == "MOVIE":
            layout = self.layout
            layout.prop(prefs, "audio_dir", text="path for audio files")


            layout.operator("sequencer.extract_wav_operator", text="Extract Wav")


            layout = self.layout
            layout.prop(prefs, "audio_scripts")

            if prefs.audio_scripts:
                layout = self.layout
                layout.prop(prefs, "audio_scripts_path", text="path for scripts")

            layout = self.layout
            layout.prop(prefs, "audio_use_external_links", text="external audio sync")


            if prefs.audio_use_external_links:
                layout = self.layout
                layout.prop(prefs, "audio_external_filename", text="sync data")

                row = layout.row(align=True)
                row.operator("sequencer.external_audio_set_sync", text="set sync")
                row.operator("sequencer.external_audio_reload", text="reload audio")

        layout = self.layout
                
        row = layout.row()
        row.prop(prefs, "metertype", text="")
        row.operator("sequencer.openmeterbridge", text="Launch Audio Meter", icon = "SOUND")


class OpenMeterbridgeOperator(bpy.types.Operator):
    """  """
    bl_idname = "sequencer.openmeterbridge"
    bl_label = "open external vu meter to work with jack"

    @staticmethod
    def has_sequencer(context):
        return (context.space_data.view_type in {'SEQUENCER', 'SEQUENCER_PREVIEW'})

    @classmethod
    def poll(cls, context):
        if cls.has_sequencer(context):
            if len(context.selected_editable_sequences) == 1:
                return True
                

    def execute(self, context):
        preferences = context.user_preferences
        prefs = preferences.addons[__package__].preferences

        command = "meterbridge -t {} 'PulseAudio JACK Sink:front-left' 'PulseAudio JACK Sink:front-right' &".format(prefs.metertype.lower())
        p = subprocess.Popen(command,stdout=subprocess.PIPE, shell = True)
        
        return {'FINISHED'}