OpenShot Library | libopenshot  0.5.0
Saturation.cpp
Go to the documentation of this file.
1 
9 // Copyright (c) 2008-2019 OpenShot Studios, LLC
10 //
11 // SPDX-License-Identifier: LGPL-3.0-or-later
12 
13 #include "Saturation.h"
14 #include "Exceptions.h"
15 #include <array>
16 #include <cmath>
17 
18 using namespace openshot;
19 
21 Saturation::Saturation() : saturation(1.0), saturation_R(1.0), saturation_G(1.0), saturation_B(1.0),
22  mask_mode(SATURATION_MASK_POST_BLEND) {
23  // Init effect properties
24  init_effect_details();
25 }
26 
27 // Default constructor
28 Saturation::Saturation(Keyframe saturation, Keyframe saturation_R, Keyframe saturation_G, Keyframe saturation_B) :
29  saturation(saturation), saturation_R(saturation_R), saturation_G(saturation_G), saturation_B(saturation_B),
31 {
32  // Init effect properties
33  init_effect_details();
34 }
35 
36 bool Saturation::UseCustomMaskBlend(int64_t frame_number) const {
37  (void) frame_number;
39 }
40 
41 void Saturation::ApplyCustomMaskBlend(std::shared_ptr<QImage> original_image, std::shared_ptr<QImage> effected_image,
42  std::shared_ptr<QImage> mask_image, int64_t frame_number) const {
43  (void) frame_number;
44  if (!original_image || !effected_image || !mask_image)
45  return;
46  if (original_image->size() != effected_image->size() || effected_image->size() != mask_image->size())
47  return;
48 
49  unsigned char* original_pixels = reinterpret_cast<unsigned char*>(original_image->bits());
50  unsigned char* effected_pixels = reinterpret_cast<unsigned char*>(effected_image->bits());
51  unsigned char* mask_pixels = reinterpret_cast<unsigned char*>(mask_image->bits());
52  const int pixel_count = effected_image->width() * effected_image->height();
53 
54  if (mask_invert) {
55  #pragma omp parallel for schedule(static)
56  for (int i = 0; i < pixel_count; ++i) {
57  const int idx = i * 4;
58  float factor = static_cast<float>(qGray(mask_pixels[idx], mask_pixels[idx + 1], mask_pixels[idx + 2])) / 255.0f;
59  factor = 1.0f - factor;
60  // Use a non-linear response curve for custom saturation drive mode.
61  factor = factor * factor;
62  const float inverse = 1.0f - factor;
63 
64  // Drive saturation strength with mask while preserving source alpha.
65  effected_pixels[idx] = static_cast<unsigned char>(
66  (original_pixels[idx] * inverse) + (effected_pixels[idx] * factor));
67  effected_pixels[idx + 1] = static_cast<unsigned char>(
68  (original_pixels[idx + 1] * inverse) + (effected_pixels[idx + 1] * factor));
69  effected_pixels[idx + 2] = static_cast<unsigned char>(
70  (original_pixels[idx + 2] * inverse) + (effected_pixels[idx + 2] * factor));
71  effected_pixels[idx + 3] = original_pixels[idx + 3];
72  }
73  } else {
74  #pragma omp parallel for schedule(static)
75  for (int i = 0; i < pixel_count; ++i) {
76  const int idx = i * 4;
77  float factor = static_cast<float>(qGray(mask_pixels[idx], mask_pixels[idx + 1], mask_pixels[idx + 2])) / 255.0f;
78  // Use a non-linear response curve for custom saturation drive mode.
79  factor = factor * factor;
80  const float inverse = 1.0f - factor;
81 
82  // Drive saturation strength with mask while preserving source alpha.
83  effected_pixels[idx] = static_cast<unsigned char>(
84  (original_pixels[idx] * inverse) + (effected_pixels[idx] * factor));
85  effected_pixels[idx + 1] = static_cast<unsigned char>(
86  (original_pixels[idx + 1] * inverse) + (effected_pixels[idx + 1] * factor));
87  effected_pixels[idx + 2] = static_cast<unsigned char>(
88  (original_pixels[idx + 2] * inverse) + (effected_pixels[idx + 2] * factor));
89  effected_pixels[idx + 3] = original_pixels[idx + 3];
90  }
91  }
92 }
93 
94 // Init effect settings
95 void Saturation::init_effect_details()
96 {
99 
101  info.class_name = "Saturation";
102  info.name = "Color Saturation";
103  info.description = "Adjust the color saturation.";
104  info.has_audio = false;
105  info.has_video = true;
106 }
107 
108 // This method is required for all derived classes of EffectBase, and returns a
109 // modified openshot::Frame object
110 std::shared_ptr<openshot::Frame> Saturation::GetFrame(std::shared_ptr<openshot::Frame> frame, int64_t frame_number)
111 {
112  // Get the frame's image
113  std::shared_ptr<QImage> frame_image = frame->GetImage();
114 
115  if (!frame_image)
116  return frame;
117 
118  const int pixel_count = frame_image->width() * frame_image->height();
119 
120  // Get keyframe values for this frame
121  const float saturation_value = saturation.GetValue(frame_number);
122  const float saturation_value_R = saturation_R.GetValue(frame_number);
123  const float saturation_value_G = saturation_G.GetValue(frame_number);
124  const float saturation_value_B = saturation_B.GetValue(frame_number);
125 
126  // Constants used for color saturation formula
127  const float pR = 0.299f;
128  const float pG = 0.587f;
129  const float pB = 0.114f;
130  const float sqrt_pR = std::sqrt(pR);
131  const float sqrt_pG = std::sqrt(pG);
132  const float sqrt_pB = std::sqrt(pB);
133  // Rec.601 fixed-point luma weights used in many image/video pipelines.
134  // This avoids per-pixel sqrt() while keeping output stable.
135  static const std::array<float, 65026> sqrt_lut = [] {
136  std::array<float, 65026> lut{};
137  for (int i = 0; i <= 65025; ++i)
138  lut[i] = std::sqrt(static_cast<float>(i));
139  return lut;
140  }();
141 
142  // Loop through pixels
143  unsigned char *pixels = reinterpret_cast<unsigned char *>(frame_image->bits());
144  // LUT for undoing premultiplication without a per-pixel divide.
145  static const std::array<float, 256> inv_alpha = [] {
146  std::array<float, 256> lut{};
147  lut[0] = 0.0f;
148  for (int i = 1; i < 256; ++i)
149  lut[i] = 255.0f / static_cast<float>(i);
150  return lut;
151  }();
152  const auto clamp_i = [](int value) -> int {
153  if (value < 0) return 0;
154  if (value > 255) return 255;
155  return value;
156  };
157 
158  const auto apply_saturation = [&](int &R, int &G, int &B) {
159  // Approximate sqrt(R^2*pR + G^2*pG + B^2*pB) with fixed-point weighted
160  // intensity and lookup table. 77/150/29 ~= 0.299/0.587/0.114.
161  const int weighted_sq = (77 * R * R + 150 * G * G + 29 * B * B + 128) >> 8;
162  const float p = sqrt_lut[weighted_sq];
163 
164  // Adjust common saturation
165  R = clamp_i(static_cast<int>(p + (R - p) * saturation_value));
166  G = clamp_i(static_cast<int>(p + (G - p) * saturation_value));
167  B = clamp_i(static_cast<int>(p + (B - p) * saturation_value));
168 
169  // Compute per-channel replacement brightness
170  const float p_r = R * sqrt_pR;
171  const float p_g = G * sqrt_pG;
172  const float p_b = B * sqrt_pB;
173 
174  // Adjust channel-separated saturation
175  const int Rr = static_cast<int>(p_r + (R - p_r) * saturation_value_R);
176  const int Gr = static_cast<int>(p_r - p_r * saturation_value_R);
177  const int Br = static_cast<int>(p_r - p_r * saturation_value_R);
178 
179  const int Rg = static_cast<int>(p_g - p_g * saturation_value_G);
180  const int Gg = static_cast<int>(p_g + (G - p_g) * saturation_value_G);
181  const int Bg = static_cast<int>(p_g - p_g * saturation_value_G);
182 
183  const int Rb = static_cast<int>(p_b - p_b * saturation_value_B);
184  const int Gb = static_cast<int>(p_b - p_b * saturation_value_B);
185  const int Bb = static_cast<int>(p_b + (B - p_b) * saturation_value_B);
186 
187  // Recombine and constrain values
188  R = clamp_i(Rr + Rg + Rb);
189  G = clamp_i(Gr + Gg + Gb);
190  B = clamp_i(Br + Bg + Bb);
191  };
192 
193  #pragma omp parallel for if(pixel_count >= 16384) schedule(static) shared (pixels)
194  for (int pixel = 0; pixel < pixel_count; ++pixel)
195  {
196  const int idx = pixel * 4;
197 
198  // Split hot paths by alpha to avoid unnecessary premultiply/unpremultiply work.
199  const int A = pixels[idx + 3];
200  if (A <= 0)
201  continue;
202  int R = 0;
203  int G = 0;
204  int B = 0;
205  if (A == 255) {
206  R = pixels[idx + 0];
207  G = pixels[idx + 1];
208  B = pixels[idx + 2];
209  apply_saturation(R, G, B);
210  pixels[idx + 0] = static_cast<unsigned char>(R);
211  pixels[idx + 1] = static_cast<unsigned char>(G);
212  pixels[idx + 2] = static_cast<unsigned char>(B);
213  } else {
214  const float alpha_percent = static_cast<float>(A) * (1.0f / 255.0f);
215  const float inv_alpha_percent = inv_alpha[A];
216 
217  // Get RGB values, and remove pre-multiplied alpha
218  R = static_cast<int>(pixels[idx + 0] * inv_alpha_percent);
219  G = static_cast<int>(pixels[idx + 1] * inv_alpha_percent);
220  B = static_cast<int>(pixels[idx + 2] * inv_alpha_percent);
221  apply_saturation(R, G, B);
222 
223  // Pre-multiply alpha back into color channels
224  pixels[idx + 0] = static_cast<unsigned char>(R * alpha_percent);
225  pixels[idx + 1] = static_cast<unsigned char>(G * alpha_percent);
226  pixels[idx + 2] = static_cast<unsigned char>(B * alpha_percent);
227  }
228  }
229 
230  // return the modified frame
231  return frame;
232 }
233 
234 // Generate JSON string of this object
235 std::string Saturation::Json() const {
236 
237  // Return formatted string
238  return JsonValue().toStyledString();
239 }
240 
241 // Generate Json::Value for this object
242 Json::Value Saturation::JsonValue() const {
243 
244  // Create root json object
245  Json::Value root = EffectBase::JsonValue(); // get parent properties
246  root["type"] = info.class_name;
247  root["saturation"] = saturation.JsonValue();
248  root["saturation_R"] = saturation_R.JsonValue();
249  root["saturation_G"] = saturation_G.JsonValue();
250  root["saturation_B"] = saturation_B.JsonValue();
251  root["mask_mode"] = mask_mode;
252 
253  // return JsonValue
254  return root;
255 }
256 
257 // Load JSON string into this object
258 void Saturation::SetJson(const std::string value) {
259 
260  // Parse JSON string into JSON objects
261  try
262  {
263  const Json::Value root = openshot::stringToJson(value);
264  // Set all values that match
265  SetJsonValue(root);
266  }
267  catch (const std::exception& e)
268  {
269  // Error parsing JSON (or missing keys)
270  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
271  }
272 }
273 
274 // Load Json::Value into this object
275 void Saturation::SetJsonValue(const Json::Value root) {
276 
277  // Set parent data
279 
280  // Set data from Json (if key is found)
281  if (!root["saturation"].isNull())
282  saturation.SetJsonValue(root["saturation"]);
283  if (!root["saturation_R"].isNull())
284  saturation_R.SetJsonValue(root["saturation_R"]);
285  if (!root["saturation_G"].isNull())
286  saturation_G.SetJsonValue(root["saturation_G"]);
287  if (!root["saturation_B"].isNull())
288  saturation_B.SetJsonValue(root["saturation_B"]);
289  if (!root["mask_mode"].isNull())
290  mask_mode = root["mask_mode"].asInt();
291 }
292 
293 // Get all properties for a specific frame
294 std::string Saturation::PropertiesJSON(int64_t requested_frame) const {
295 
296  // Generate JSON properties list
297  Json::Value root = BasePropertiesJSON(requested_frame);
298 
299  // Keyframes
300  root["saturation"] = add_property_json("Saturation", saturation.GetValue(requested_frame), "float", "", &saturation, 0.0, 4.0, false, requested_frame);
301  root["saturation_R"] = add_property_json("Saturation (Red)", saturation_R.GetValue(requested_frame), "float", "", &saturation_R, 0.0, 4.0, false, requested_frame);
302  root["saturation_G"] = add_property_json("Saturation (Green)", saturation_G.GetValue(requested_frame), "float", "", &saturation_G, 0.0, 4.0, false, requested_frame);
303  root["saturation_B"] = add_property_json("Saturation (Blue)", saturation_B.GetValue(requested_frame), "float", "", &saturation_B, 0.0, 4.0, false, requested_frame);
304  root["mask_mode"] = add_property_json("Mask Mode", mask_mode, "int", "", NULL, 0, 1, false, requested_frame);
305  root["mask_mode"]["choices"].append(add_property_choice_json("Limit to Mask", SATURATION_MASK_POST_BLEND, mask_mode));
306  root["mask_mode"]["choices"].append(add_property_choice_json("Vary Strength", SATURATION_MASK_DRIVE_AMOUNT, mask_mode));
307 
308  // Return formatted string
309  return root.toStyledString();
310 }
openshot::ClipBase::add_property_json
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:96
openshot::stringToJson
const Json::Value stringToJson(const std::string value)
Definition: Json.cpp:16
openshot::EffectBase::info
EffectInfoStruct info
Information about the current effect.
Definition: EffectBase.h:110
openshot::Saturation::Json
std::string Json() const override
Generate JSON string of this object.
Definition: Saturation.cpp:235
openshot::EffectBase::mask_invert
bool mask_invert
Invert grayscale mask values before blending.
Definition: EffectBase.h:111
openshot
This namespace is the default namespace for all code in the openshot library.
Definition: Compressor.h:28
openshot::ClipBase::add_property_choice_json
Json::Value add_property_choice_json(std::string name, int value, int selected_value) const
Generate JSON choice for a property (dropdown properties)
Definition: ClipBase.cpp:132
openshot::EffectBase::JsonValue
virtual Json::Value JsonValue() const
Generate Json::Value for this object.
Definition: EffectBase.cpp:96
openshot::Keyframe::SetJsonValue
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: KeyFrame.cpp:372
openshot::Saturation::mask_mode
int mask_mode
How to apply common masks to saturation (post-blend or drive-amount).
Definition: Saturation.h:62
openshot::Saturation::saturation_R
Keyframe saturation_R
Red color saturation.
Definition: Saturation.h:59
openshot::Saturation::SetJsonValue
void SetJsonValue(const Json::Value root) override
Load Json::Value into this object.
Definition: Saturation.cpp:275
openshot::Saturation::JsonValue
Json::Value JsonValue() const override
Generate Json::Value for this object.
Definition: Saturation.cpp:242
openshot::SATURATION_MASK_DRIVE_AMOUNT
@ SATURATION_MASK_DRIVE_AMOUNT
Definition: Saturation.h:37
openshot::Keyframe::JsonValue
Json::Value JsonValue() const
Generate Json::Value for this object.
Definition: KeyFrame.cpp:339
openshot::EffectBase::BasePropertiesJSON
Json::Value BasePropertiesJSON(int64_t requested_frame) const
Generate JSON object of base properties (recommended to be used by all effects)
Definition: EffectBase.cpp:236
openshot::Keyframe
A Keyframe is a collection of Point instances, which is used to vary a number or property over time.
Definition: KeyFrame.h:53
openshot::InvalidJSON
Exception for invalid JSON.
Definition: Exceptions.h:223
openshot::EffectBase::InitEffectInfo
void InitEffectInfo()
Definition: EffectBase.cpp:37
openshot::EffectInfoStruct::has_audio
bool has_audio
Determines if this effect manipulates the audio of a frame.
Definition: EffectBase.h:44
openshot::EffectInfoStruct::class_name
std::string class_name
The class name of the effect.
Definition: EffectBase.h:39
openshot::EffectInfoStruct::description
std::string description
The description of this effect and what it does.
Definition: EffectBase.h:41
openshot::EffectInfoStruct::has_video
bool has_video
Determines if this effect manipulates the image of a frame.
Definition: EffectBase.h:43
openshot::Saturation::GetFrame
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: Saturation.h:81
openshot::Saturation::saturation_G
Keyframe saturation_G
Green color saturation.
Definition: Saturation.h:60
openshot::Saturation::saturation_B
Keyframe saturation_B
Blue color saturation.
Definition: Saturation.h:61
openshot::Saturation::UseCustomMaskBlend
bool UseCustomMaskBlend(int64_t frame_number) const override
Optional override for effects that need custom mask behavior.
Definition: Saturation.cpp:36
Saturation.h
Header file for Saturation class.
openshot::EffectInfoStruct::name
std::string name
The name of the effect.
Definition: EffectBase.h:40
openshot::Saturation::PropertiesJSON
std::string PropertiesJSON(int64_t requested_frame) const override
Definition: Saturation.cpp:294
openshot::Saturation::ApplyCustomMaskBlend
void ApplyCustomMaskBlend(std::shared_ptr< QImage > original_image, std::shared_ptr< QImage > effected_image, std::shared_ptr< QImage > mask_image, int64_t frame_number) const override
Optional override for effects with custom mask implementation.
Definition: Saturation.cpp:41
openshot::Saturation::Saturation
Saturation()
Blank constructor, useful when using Json to load the effect properties.
Definition: Saturation.cpp:21
openshot::SATURATION_MASK_POST_BLEND
@ SATURATION_MASK_POST_BLEND
Definition: Saturation.h:36
openshot::Saturation::SetJson
void SetJson(const std::string value) override
Load JSON string into this object.
Definition: Saturation.cpp:258
Exceptions.h
Header file for all Exception classes.
openshot::Saturation::saturation
Keyframe saturation
Overall color saturation: 0.0 = greyscale, 1.0 = normal, 2.0 = double saturation.
Definition: Saturation.h:58
openshot::EffectBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: EffectBase.cpp:139
openshot::Keyframe::GetValue
double GetValue(int64_t index) const
Get the value at a specific index.
Definition: KeyFrame.cpp:258