summaryrefslogtreecommitdiff
path: root/src/flufigut.py
blob: bc389f1102b72d4d9cc3f336496ab03ec9a1f1d9 (plain) (blame)
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
#!/usr/bin/python3
#
# flufigut
#
# flufigut, the flumotion configuration utility, is a simple tool
# that generates flumotion configuration files using pyhton jinja2
# template engine. flufigut generates planet.xml and worker.xml
# files from configuration templates and an easy to understand
# representation of the flow structure written in json or yaml.
#
#
# Copyright (C) 2018 Christian Pointner <equinox@spreadspace.org>
#
# This file is part of flufigut.
#
# flufigut 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
# any later version.
#
# flufigut 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 flufigut. If not, see <http://www.gnu.org/licenses/>.
#

import string
import random
import sys
import yaml
# from jinja2 import Environment, FileSystemLoader

# helper functions ############################################
#


def rand_string(size=8, chars=string.ascii_lowercase + string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range(size))


# a flufigut stream description ###############################
#

class Description:

    def __init__(self):
        self.globals = {}
        self.inputs = {}
        self.muxes = {}
        self.streams = {}
        self.records = {}

    def _sanity_check(self):
        # TODO: add more sanity checks
        components = {}
        for _, worker in self.globals['workers'].items():
            for c in worker:
                if c in components:
                    raise Exception("ERROR: component '%s' is assigned to more than one worker!" % c)
                else:
                    components[c] = 1

    def parse(self, config_file):
        cf = open(config_file, 'r')
        config = yaml.load(cf)
        cf.close()

        self.globals = config['globals']
        self.inputs = config['inputs']
        self.muxes = config['muxes']
        self.streams = config['streams']
        if 'records' in config:
            self.records = config['records']

        return self._sanity_check()


# a flumtion planet configuration #############################
#

class Planet:

    def __init__(self):
        self.atmosphere = {}
        self.flow = {}
        self._workers = {}
        self._components = {}

    #
    # inputs
    def __set_input_properties(self, name, props, globals):
        for prop in props.keys():
            if prop == 'resolution':
                self.flow['inputs'][name]['properties']['width'] = globals['resolutions'][props[prop]]['width']
                self.flow['inputs'][name]['properties']['height'] = globals['resolutions'][props[prop]]['height']
                self.flow['inputs'][name]['properties']['framerate'] = globals['resolutions'][props[prop]]['rate']
            else:
                self.flow['inputs'][name]['properties'][prop] = props[prop]

    def _generate_inputs(self, inputs, globals):
        self.flow['inputs'] = {}
        master_cnt = 0
        for source, input in inputs.items():
            name = 'input-%s' % source
            if name not in self._components:
                self._components[name] = -1
            else:
                self._components[name] = 1
            self.flow['inputs'][name] = {
                'type': input['type'],
                'desc': "capture raw data from %s" % (source),
                'worker': name,
                'master': input['master'],
                'properties': {},
            }
            if input['master']:
                master_cnt += 1
            self.__set_input_properties(name, input['properties'], globals)

        if master_cnt == 0:
            raise exception("You have not configured any master clock device!")
        elif master_cnt > 1:
            raise exception("You have configured multiple master clock devices!")

    #
    # muxes
    def __generate_audio_resampler(self, mux, format, inputs, globals):
        source = mux['audio'].split(':')[0]
        input_samplerate = inputs[source]['properties']['samplerate']
        if 'samplerate' in globals['formats'][format]:
            samplerate = globals['formats'][format]['samplerate']
            if samplerate != input_samplerate:
                comp_name = 'resample-%s' % (source)
                if comp_name not in self._components:
                    self._components[comp_name] = -1
                else:
                    self._components[comp_name] = 1
                feeder = 'input-%s' % (mux['audio'])
                self.flow['inputs']['resample-%s-%s' % (source, samplerate)] = {
                    'type': 'audio-resample',
                    'desc': "resample audio from %s to %s Hz" % (source, samplerate),
                    'worker': comp_name,
                    'feeder': feeder,
                    'properties': {
                        'samplerate': samplerate,
                    },
                }

    def __generate_video_resizer(self, mux, format, inputs, globals):
        source = mux['video'].split(':')[0]
        input_resolution = inputs[source]['properties']['resolution']
        for profile in mux['formats'][format]:
            if 'video' in globals['profiles'][profile]:
                if input_resolution == "":
                    raise exception("format definition needs video but no video input given")
                resolution = globals['profiles'][profile]['video']
                if input_resolution != resolution:
                    if globals['resolutions'][resolution]['rate'] != globals['resolutions'][input_resolution]['rate']:
                        raise exception("ERROR: video rate conversion is not yet supported!!!")
                    comp_name = 'resize-%s' % (source)
                    if comp_name not in self._components:
                        self._components[comp_name] = -1
                    else:
                        self._components[comp_name] = 1
                    feeder = 'input-%s' % (mux['video'])
                    self.flow['inputs']['resize-%s-%s' % (source, resolution)] = {
                        'type': 'video-resize',
                        'desc': "resize video from %s to %sx%s" % (source, globals['resolutions'][resolution]['width'], globals['resolutions'][resolution]['height']),
                        'worker': comp_name,
                        'feeder': feeder,
                        'properties': {
                            'width': globals['resolutions'][resolution]['width'],
                            'height': globals['resolutions'][resolution]['height'],
                        },
                    }

    def _generate_muxes(self, muxes, inputs, globals):
        for _, mux in muxes.items():
            for format in mux['formats'].keys():
                if 'audio' in mux:
                    self.__generate_audio_resampler(mux, format, inputs, globals)
                if 'video' in mux:
                    self.__generate_video_resizer(mux, format, inputs, globals)

        # TODO: add encoder and muxer

    #
    # all
    def generate(self, desc):
        self._generate_inputs(desc.inputs, desc.globals)
        self._generate_muxes(desc.muxes, desc.inputs, desc.globals)


# Main ########################################################
#

if __name__ == '__main__':
    import traceback
    import pprint
    __pp = pprint.PrettyPrinter(indent=4, width=160)

    if len(sys.argv) <= 1:
        print("ERROR: No configuration file given")
        sys.exit(-1)
    config_file = sys.argv[1]

    ret = 0
    try:
        d = Description()
        d.parse(config_file)

        p = Planet()
        p.generate(d)

        print("****************************************************")
        print("** atmosphere **")
        print("**")
        __pp.pprint(p.atmosphere)

        print("**")
        print("**************************")
        print("** planet **")
        print("**")
        __pp.pprint(p.flow)

        print("**")
        print("****************************************************")
        print("** _workers **")
        print("**")
        __pp.pprint(p._workers)

        print("**")
        print("**************************")
        print("** _components **")
        print("**")
        __pp.pprint(p._components)
        print("**")
        print("****************************************************")

    except Exception as e:
        print("ERROR: while running app: %s" % e)
        print(traceback.format_exc())
        sys.exit(1)

    sys.exit(ret)