1# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
2#
3# Use of this source code is governed by a BSD-style license
4# that can be found in the LICENSE file in the root of the source
5# tree. An additional intellectual property rights grant can be found
6# in the file PATENTS.  All contributing project authors may
7# be found in the AUTHORS file in the root of the source tree.
8"""Input signal creator module.
9"""
10
11from . import exceptions
12from . import signal_processing
13
14
15class InputSignalCreator(object):
16    """Input signal creator class.
17  """
18
19    @classmethod
20    def Create(cls, name, raw_params):
21        """Creates a input signal and its metadata.
22
23    Args:
24      name: Input signal creator name.
25      raw_params: Tuple of parameters to pass to the specific signal creator.
26
27    Returns:
28      (AudioSegment, dict) tuple.
29    """
30        try:
31            signal = {}
32            params = {}
33
34            if name == 'pure_tone':
35                params['frequency'] = float(raw_params[0])
36                params['duration'] = int(raw_params[1])
37                signal = cls._CreatePureTone(params['frequency'],
38                                             params['duration'])
39            else:
40                raise exceptions.InputSignalCreatorException(
41                    'Invalid input signal creator name')
42
43            # Complete metadata.
44            params['signal'] = name
45
46            return signal, params
47        except (TypeError, AssertionError) as e:
48            raise exceptions.InputSignalCreatorException(
49                'Invalid signal creator parameters: {}'.format(e))
50
51    @classmethod
52    def _CreatePureTone(cls, frequency, duration):
53        """
54    Generates a pure tone at 48000 Hz.
55
56    Args:
57      frequency: Float in (0-24000] (Hz).
58      duration: Integer (milliseconds).
59
60    Returns:
61      AudioSegment instance.
62    """
63        assert 0 < frequency <= 24000
64        assert duration > 0
65        template = signal_processing.SignalProcessingUtils.GenerateSilence(
66            duration)
67        return signal_processing.SignalProcessingUtils.GeneratePureTone(
68            template, frequency)
69