OpenShot Library | libopenshot  0.2.6
Compressor.cpp
Go to the documentation of this file.
1 /**
2  * @file
3  * @brief Source file for Compressor audio effect class
4  * @author
5  *
6  * @ref License
7  */
8 
9 /* LICENSE
10  *
11  * Copyright (c) 2008-2019 OpenShot Studios, LLC
12  * <http://www.openshotstudios.com/>. This file is part of
13  * OpenShot Library (libopenshot), an open-source project dedicated to
14  * delivering high quality video editing and animation solutions to the
15  * world. For more information visit <http://www.openshot.org/>.
16  *
17  * OpenShot Library (libopenshot) is free software: you can redistribute it
18  * and/or modify it under the terms of the GNU Lesser General Public License
19  * as published by the Free Software Foundation, either version 3 of the
20  * License, or (at your option) any later version.
21  *
22  * OpenShot Library (libopenshot) is distributed in the hope that it will be
23  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25  * GNU Lesser General Public License for more details.
26  *
27  * You should have received a copy of the GNU Lesser General Public License
28  * along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
29  */
30 
31 #include "Compressor.h"
32 #include "Exceptions.h"
33 
34 using namespace openshot;
35 
36 /// Blank constructor, useful when using Json to load the effect properties
37 Compressor::Compressor() : threshold(-10), ratio(1), attack(1), release(1), makeup_gain(1), bypass(false) {
38  // Init effect properties
39  init_effect_details();
40 }
41 
42 // Default constructor
43 Compressor::Compressor(Keyframe new_threshold, Keyframe new_ratio, Keyframe new_attack, Keyframe new_release, Keyframe new_makeup_gain, Keyframe new_bypass) :
44  threshold(new_threshold), ratio(new_ratio), attack(new_attack), release(new_release), makeup_gain(new_makeup_gain), bypass(new_bypass)
45 {
46  // Init effect properties
47  init_effect_details();
48 }
49 
50 // Init effect settings
51 void Compressor::init_effect_details()
52 {
53  /// Initialize the values of the EffectInfo struct.
55 
56  /// Set the effect info
57  info.class_name = "Compressor";
58  info.name = "Compressor";
59  info.description = "Reduce the volume of loud sounds or amplify quiet sounds.";
60  info.has_audio = true;
61  info.has_video = false;
62 
63  input_level = 0.0f;
64  yl_prev = 0.0f;
65 }
66 
67 // This method is required for all derived classes of EffectBase, and returns a
68 // modified openshot::Frame object
69 std::shared_ptr<openshot::Frame> Compressor::GetFrame(std::shared_ptr<openshot::Frame> frame, int64_t frame_number)
70 {
71  // Adding Compressor
72  const int num_input_channels = frame->audio->getNumChannels();
73  const int num_output_channels = frame->audio->getNumChannels();
74  const int num_samples = frame->audio->getNumSamples();
75 
76  mixed_down_input.setSize(1, num_samples);
77  inverse_sample_rate = 1.0f / frame->SampleRate();
78  inverseE = 1.0f / M_E;
79 
80  if ((bool)bypass.GetValue(frame_number))
81  return frame;
82 
83  mixed_down_input.clear();
84 
85  for (int channel = 0; channel < num_input_channels; ++channel)
86  mixed_down_input.addFrom(0, 0, *frame->audio, channel, 0, num_samples, 1.0f / num_input_channels);
87 
88  for (int sample = 0; sample < num_samples; ++sample) {
89  float T = threshold.GetValue(frame_number);
90  float R = ratio.GetValue(frame_number);
91  float alphaA = calculateAttackOrRelease(attack.GetValue(frame_number));
92  float alphaR = calculateAttackOrRelease(release.GetValue(frame_number));
93  float gain = makeup_gain.GetValue(frame_number);
94  float input_squared = powf(mixed_down_input.getSample(0, sample), 2.0f);
95 
96  input_level = input_squared;
97 
98  xg = (input_level <= 1e-6f) ? -60.0f : 10.0f * log10f(input_level);
99 
100  if (xg < T)
101  yg = xg;
102  else
103  yg = T + (xg - T) / R;
104 
105  xl = xg - yg;
106 
107  if (xl > yl_prev)
108  yl = alphaA * yl_prev + (1.0f - alphaA) * xl;
109  else
110  yl = alphaR * yl_prev + (1.0f - alphaR) * xl;
111 
112  control = powf (10.0f, (gain - yl) * 0.05f);
113  yl_prev = yl;
114 
115  for (int channel = 0; channel < num_input_channels; ++channel) {
116  float new_value = frame->audio->getSample(channel, sample)*control;
117  frame->audio->setSample(channel, sample, new_value);
118  }
119  }
120 
121  for (int channel = num_input_channels; channel < num_output_channels; ++channel)
122  frame->audio->clear(channel, 0, num_samples);
123 
124  // return the modified frame
125  return frame;
126 }
127 
129 {
130  if (value == 0.0f)
131  return 0.0f;
132  else
133  return pow (inverseE, inverse_sample_rate / value);
134 }
135 
136 // Generate JSON string of this object
137 std::string Compressor::Json() const {
138 
139  // Return formatted string
140  return JsonValue().toStyledString();
141 }
142 
143 // Generate Json::Value for this object
144 Json::Value Compressor::JsonValue() const {
145 
146  // Create root json object
147  Json::Value root = EffectBase::JsonValue(); // get parent properties
148  root["type"] = info.class_name;
149  root["threshold"] = threshold.JsonValue();
150  root["ratio"] = ratio.JsonValue();
151  root["attack"] = attack.JsonValue();
152  root["release"] = release.JsonValue();
153  root["makeup_gain"] = makeup_gain.JsonValue();
154  root["bypass"] = bypass.JsonValue();
155 
156  // return JsonValue
157  return root;
158 }
159 
160 // Load JSON string into this object
161 void Compressor::SetJson(const std::string value) {
162 
163  // Parse JSON string into JSON objects
164  try
165  {
166  const Json::Value root = openshot::stringToJson(value);
167  // Set all values that match
168  SetJsonValue(root);
169  }
170  catch (const std::exception& e)
171  {
172  // Error parsing JSON (or missing keys)
173  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
174  }
175 }
176 
177 // Load Json::Value into this object
178 void Compressor::SetJsonValue(const Json::Value root) {
179 
180  // Set parent data
182 
183  // Set data from Json (if key is found)
184  if (!root["threshold"].isNull())
185  threshold.SetJsonValue(root["threshold"]);
186 
187  if (!root["ratio"].isNull())
188  ratio.SetJsonValue(root["ratio"]);
189 
190  if (!root["attack"].isNull())
191  attack.SetJsonValue(root["attack"]);
192 
193  if (!root["release"].isNull())
194  release.SetJsonValue(root["release"]);
195 
196  if (!root["makeup_gain"].isNull())
197  makeup_gain.SetJsonValue(root["makeup_gain"]);
198 
199  if (!root["bypass"].isNull())
200  bypass.SetJsonValue(root["bypass"]);
201 }
202 
203 // Get all properties for a specific frame
204 std::string Compressor::PropertiesJSON(int64_t requested_frame) const {
205 
206  // Generate JSON properties list
207  Json::Value root;
208  root["id"] = add_property_json("ID", 0.0, "string", Id(), NULL, -1, -1, true, requested_frame);
209  root["layer"] = add_property_json("Track", Layer(), "int", "", NULL, 0, 20, false, requested_frame);
210  root["start"] = add_property_json("Start", Start(), "float", "", NULL, 0, 1000 * 60 * 30, false, requested_frame);
211  root["end"] = add_property_json("End", End(), "float", "", NULL, 0, 1000 * 60 * 30, false, requested_frame);
212  root["duration"] = add_property_json("Duration", Duration(), "float", "", NULL, 0, 1000 * 60 * 30, true, requested_frame);
213 
214  // Keyframes
215  root["threshold"] = add_property_json("Threshold (dB)", threshold.GetValue(requested_frame), "float", "", &threshold, -60, 0, false, requested_frame);
216  root["ratio"] = add_property_json("Ratio", ratio.GetValue(requested_frame), "float", "", &ratio, 1, 100, false, requested_frame);
217  root["attack"] = add_property_json("Attack (ms)", attack.GetValue(requested_frame), "float", "", &attack, 0.1, 100, false, requested_frame);
218  root["release"] = add_property_json("Release (ms)", release.GetValue(requested_frame), "float", "", &release, 10, 1000, false, requested_frame);
219  root["makeup_gain"] = add_property_json("Makeup gain (dB)", makeup_gain.GetValue(requested_frame), "float", "", &makeup_gain, -12, 12, false, requested_frame);
220  root["bypass"] = add_property_json("Bypass", bypass.GetValue(requested_frame), "bool", "", &bypass, 0, 1, false, requested_frame);
221 
222  // Return formatted string
223  return root.toStyledString();
224 }
std::shared_ptr< openshot::Frame > GetFrame(int64_t frame_number) override
This method is required for all derived classes of ClipBase, and returns a new openshot::Frame object...
Definition: Compressor.h:97
std::string Id() const
Get the Id of this clip object.
Definition: ClipBase.h:107
Keyframe makeup_gain
Definition: Compressor.h:65
float Start() const
Get start position (in seconds) of clip (trim start of video)
Definition: ClipBase.h:110
virtual void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: EffectBase.cpp:127
std::string PropertiesJSON(int64_t requested_frame) const override
Definition: Compressor.cpp:204
const Json::Value stringToJson(const std::string value)
Definition: Json.cpp:34
virtual Json::Value JsonValue() const
Generate Json::Value for this object.
Definition: EffectBase.cpp:92
bool has_audio
Determines if this effect manipulates the audio of a frame.
Definition: EffectBase.h:59
Json::Value JsonValue() const override
Generate Json::Value for this object.
Definition: Compressor.cpp:144
Header file for all Exception classes.
Compressor()
Blank constructor, useful when using Json to load the effect properties.
Definition: Compressor.cpp:37
std::string class_name
The class name of the effect.
Definition: EffectBase.h:54
std::string name
The name of the effect.
Definition: EffectBase.h:55
std::string Json() const override
Generate JSON string of this object.
Definition: Compressor.cpp:137
float Duration() const
Get the length of this clip (in seconds)
Definition: ClipBase.h:112
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: KeyFrame.cpp:368
void SetJson(const std::string value) override
Load JSON string into this object.
Definition: Compressor.cpp:161
This namespace is the default namespace for all code in the openshot library.
Definition: Compressor.h:46
Json::Value JsonValue() const
Generate Json::Value for this object.
Definition: KeyFrame.cpp:335
std::string description
The description of this effect and what it does.
Definition: EffectBase.h:56
juce::AudioSampleBuffer mixed_down_input
Definition: Compressor.h:68
bool has_video
Determines if this effect manipulates the image of a frame.
Definition: EffectBase.h:58
Exception for invalid JSON.
Definition: Exceptions.h:205
double GetValue(int64_t index) const
Get the value at a specific index.
Definition: KeyFrame.cpp:268
void SetJsonValue(const Json::Value root) override
Load Json::Value into this object.
Definition: Compressor.cpp:178
float calculateAttackOrRelease(float value)
Definition: Compressor.cpp:128
Header file for Compressor audio effect class.
float End() const
Get end position (in seconds) of clip (trim end of video)
Definition: ClipBase.h:111
A Keyframe is a collection of Point instances, which is used to vary a number or property over time...
Definition: KeyFrame.h:72
Json::Value add_property_json(std::string name, float value, std::string type, std::string memo, const Keyframe *keyframe, float min_value, float max_value, bool readonly, int64_t requested_frame) const
Generate JSON for a property.
Definition: ClipBase.cpp:68
int Layer() const
Get layer of clip on timeline (lower number is covered by higher numbers)
Definition: ClipBase.h:109
EffectInfoStruct info
Information about the current effect.
Definition: EffectBase.h:87