OpenShot Library | libopenshot  0.5.0
Mask.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 "Mask.h"
14 
15 #include "Exceptions.h"
16 
17 #include "ReaderBase.h"
18 #include "ChunkReader.h"
19 #include "FFmpegReader.h"
20 #include "QtImageReader.h"
21 #include "ZmqLogger.h"
22 #include <omp.h>
23 
24 #ifdef USE_IMAGEMAGICK
25  #include "ImageReader.h"
26 #endif
27 
28 using namespace openshot;
29 
31 Mask::Mask() : reader(NULL), replace_image(false), needs_refresh(true) {
32  // Init effect properties
33  init_effect_details();
34 }
35 
36 // Default constructor
37 Mask::Mask(ReaderBase *mask_reader, Keyframe mask_brightness, Keyframe mask_contrast) :
38  reader(mask_reader), brightness(mask_brightness), contrast(mask_contrast), replace_image(false), needs_refresh(true)
39 {
40  // Init effect properties
41  init_effect_details();
42 }
43 
44 // Init effect settings
45 void Mask::init_effect_details()
46 {
49 
51  info.class_name = "Mask";
52  info.name = "Alpha Mask / Wipe Transition";
53  info.description = "Uses a grayscale mask image to gradually wipe / transition between 2 images.";
54  info.has_audio = false;
55  info.has_video = true;
56 }
57 
58 // This method is required for all derived classes of EffectBase, and returns a
59 // modified openshot::Frame object
60 std::shared_ptr<openshot::Frame> Mask::GetFrame(std::shared_ptr<openshot::Frame> frame, int64_t frame_number) {
61  // Get the mask image (from the mask reader)
62  std::shared_ptr<QImage> frame_image = frame->GetImage();
63  bool mask_reader_failed = false;
64 
65  // Check if mask reader is open
66  #pragma omp critical (open_mask_reader)
67  {
68  if (reader && !reader->IsOpen()) {
69  try {
70  reader->Open();
71  } catch (const std::exception& e) {
72  // Invalid/missing mask source should never crash frame rendering.
74  std::string("Mask::GetFrame unable to open mask reader: ") + e.what());
75  delete reader;
76  reader = NULL;
77  needs_refresh = true;
78  mask_reader_failed = true;
79  }
80  }
81  }
82 
83  // No reader (bail on applying the mask)
84  if (!reader || mask_reader_failed)
85  return frame;
86 
87  // Get mask image (if missing or different size than frame image)
88  #pragma omp critical (open_mask_reader)
89  {
90  if (!original_mask || !reader->info.has_single_image || needs_refresh ||
91  (original_mask && original_mask->size() != frame_image->size())) {
92 
93  // Only get mask if needed
94  std::shared_ptr<QImage> mask_without_sizing;
95  try {
96  mask_without_sizing = std::make_shared<QImage>(
97  *reader->GetFrame(frame_number)->GetImage());
98  } catch (const std::exception& e) {
100  std::string("Mask::GetFrame unable to read mask frame: ") + e.what());
101  delete reader;
102  reader = NULL;
103  needs_refresh = true;
104  mask_reader_failed = true;
105  }
106  if (!mask_reader_failed && mask_without_sizing) {
107  // Resize mask image to match frame size
108  original_mask = std::make_shared<QImage>(
109  mask_without_sizing->scaled(
110  frame_image->width(), frame_image->height(),
111  Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
112  }
113  }
114  }
115  if (mask_reader_failed || !reader || !original_mask)
116  return frame;
117 
118  // Once we've done the necessary resizing, we no longer need to refresh again
119  needs_refresh = false;
120 
121  // Grab raw pointers and dimensions one time
122  unsigned char* pixels = reinterpret_cast<unsigned char*>(frame_image->bits());
123  unsigned char* mask_pixels = reinterpret_cast<unsigned char*>(original_mask->bits());
124  int width = original_mask->width();
125  int height = original_mask->height();
126  int num_pixels = width * height; // total pixel count
127 
128  // Evaluate brightness and contrast keyframes just once
129  double contrast_value = contrast.GetValue(frame_number);
130  double brightness_value = brightness.GetValue(frame_number);
131 
132  int brightness_adj = static_cast<int>(255 * brightness_value);
133  float contrast_factor = 20.0f / std::max(0.00001f, 20.0f - static_cast<float>(contrast_value));
134 
135  // Iterate over every pixel in parallel
136 #pragma omp parallel for schedule(static)
137  for (int i = 0; i < num_pixels; ++i)
138  {
139  int idx = i * 4;
140 
141  int R = mask_pixels[idx + 0];
142  int G = mask_pixels[idx + 1];
143  int B = mask_pixels[idx + 2];
144  int A = mask_pixels[idx + 3];
145 
146  // Compute base gray, then apply brightness + contrast
147  int gray = qGray(R, G, B);
148  gray += brightness_adj;
149  gray = static_cast<int>(contrast_factor * (gray - 128) + 128);
150 
151  // Clamp (A - gray) into [0, 255]
152  int diff = A - gray;
153  if (diff < 0) diff = 0;
154  else if (diff > 255) diff = 255;
155 
156  // Calculate the % change in alpha
157  float alpha_percent = static_cast<float>(diff) / 255.0f;
158 
159  // Set the alpha channel to the gray value
160  if (replace_image) {
161  // Replace frame pixels with gray value (including alpha channel)
162  auto new_val = static_cast<unsigned char>(diff);
163  pixels[idx + 0] = new_val;
164  pixels[idx + 1] = new_val;
165  pixels[idx + 2] = new_val;
166  pixels[idx + 3] = new_val;
167  } else {
168  // Premultiplied RGBA → multiply each channel by alpha_percent
169  pixels[idx + 0] = static_cast<unsigned char>(pixels[idx + 0] * alpha_percent);
170  pixels[idx + 1] = static_cast<unsigned char>(pixels[idx + 1] * alpha_percent);
171  pixels[idx + 2] = static_cast<unsigned char>(pixels[idx + 2] * alpha_percent);
172  pixels[idx + 3] = static_cast<unsigned char>(pixels[idx + 3] * alpha_percent);
173  }
174 
175  }
176 
177  // return the modified frame
178  return frame;
179 }
180 
181 // Generate JSON string of this object
182 std::string Mask::Json() const {
183 
184  // Return formatted string
185  return JsonValue().toStyledString();
186 }
187 
188 // Generate Json::Value for this object
189 Json::Value Mask::JsonValue() const {
190 
191  // Create root json object
192  Json::Value root = EffectBase::JsonValue(); // get parent properties
193  root["type"] = info.class_name;
194  root["brightness"] = brightness.JsonValue();
195  root["contrast"] = contrast.JsonValue();
196  if (reader)
197  root["reader"] = reader->JsonValue();
198  else
199  root["reader"] = Json::objectValue;
200  root["replace_image"] = replace_image;
201 
202  // return JsonValue
203  return root;
204 }
205 
206 // Load JSON string into this object
207 void Mask::SetJson(const std::string value) {
208 
209  // Parse JSON string into JSON objects
210  try
211  {
212  const Json::Value root = openshot::stringToJson(value);
213  // Set all values that match
214  SetJsonValue(root);
215  }
216  catch (const std::exception& e)
217  {
218  // Error parsing JSON (or missing keys)
219  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
220  }
221 }
222 
223 // Load Json::Value into this object
224 void Mask::SetJsonValue(const Json::Value root) {
225 
226  // Set parent data
228 
229  // Set data from Json (if key is found)
230  if (!root["replace_image"].isNull())
231  replace_image = root["replace_image"].asBool();
232  if (!root["brightness"].isNull())
233  brightness.SetJsonValue(root["brightness"]);
234  if (!root["contrast"].isNull())
235  contrast.SetJsonValue(root["contrast"]);
236  if (!root["reader"].isNull()) // does Json contain a reader?
237  {
238  #pragma omp critical (open_mask_reader)
239  {
240  // This reader has changed, so refresh cached assets
241  needs_refresh = true;
242 
243  if (!root["reader"]["type"].isNull()) // does the reader Json contain a 'type'?
244  {
245  // Close previous reader (if any)
246  if (reader) {
247  // Close and delete existing reader (if any)
248  reader->Close();
249  delete reader;
250  reader = NULL;
251  }
252 
253  // Create new reader (and load properties)
254  std::string type = root["reader"]["type"].asString();
255 
256  if (type == "FFmpegReader") {
257 
258  // Create new reader
259  reader = new FFmpegReader(root["reader"]["path"].asString(), false);
260  reader->SetJsonValue(root["reader"]);
261 
262  #ifdef USE_IMAGEMAGICK
263  } else if (type == "ImageReader") {
264 
265  // Create new reader
266  reader = new ImageReader(root["reader"]["path"].asString(), false);
267  reader->SetJsonValue(root["reader"]);
268  #endif
269 
270  } else if (type == "QtImageReader") {
271 
272  // Create new reader
273  reader = new QtImageReader(root["reader"]["path"].asString(), false);
274  reader->SetJsonValue(root["reader"]);
275 
276  } else if (type == "ChunkReader") {
277 
278  // Create new reader
279  reader = new ChunkReader(root["reader"]["path"].asString(), (ChunkVersion) root["reader"]["chunk_version"].asInt());
280  reader->SetJsonValue(root["reader"]);
281 
282  }
283  }
284 
285  }
286  }
287 
288 }
289 
290 // Get all properties for a specific frame
291 std::string Mask::PropertiesJSON(int64_t requested_frame) const {
292 
293  // Generate JSON properties list
294  Json::Value root = BasePropertiesJSON(requested_frame);
295 
296  // Add replace_image choices (dropdown style)
297  root["replace_image"] = add_property_json("Replace Image", replace_image, "int", "", NULL, 0, 1, false, requested_frame);
298  root["replace_image"]["choices"].append(add_property_choice_json("Yes", true, replace_image));
299  root["replace_image"]["choices"].append(add_property_choice_json("No", false, replace_image));
300 
301  // Keyframes
302  root["brightness"] = add_property_json("Brightness", brightness.GetValue(requested_frame), "float", "", &brightness, -1.0, 1.0, false, requested_frame);
303  root["contrast"] = add_property_json("Contrast", contrast.GetValue(requested_frame), "float", "", &contrast, 0, 20, false, requested_frame);
304 
305  if (reader)
306  root["reader"] = add_property_json("Source", 0.0, "reader", reader->Json(), NULL, 0, 1, false, requested_frame);
307  else
308  root["reader"] = add_property_json("Source", 0.0, "reader", "{}", NULL, 0, 1, false, requested_frame);
309 
310  // Return formatted string
311  return root.toStyledString();
312 }
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::Mask::JsonValue
Json::Value JsonValue() const override
Generate Json::Value for this object.
Definition: Mask.cpp:189
openshot::EffectBase::info
EffectInfoStruct info
Information about the current effect.
Definition: EffectBase.h:69
openshot::ReaderBase::JsonValue
virtual Json::Value JsonValue() const =0
Generate Json::Value for this object.
Definition: ReaderBase.cpp:106
openshot::ChunkReader
This class reads a special chunk-formatted file, which can be easily shared in a distributed environm...
Definition: ChunkReader.h:78
openshot::ReaderBase::GetFrame
virtual std::shared_ptr< openshot::Frame > GetFrame(int64_t number)=0
openshot::ReaderBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)=0
Load Json::Value into this object.
Definition: ReaderBase.cpp:157
openshot::ReaderBase::Json
virtual std::string Json() const =0
Generate JSON string of this object.
openshot
This namespace is the default namespace for all code in the openshot library.
Definition: Compressor.h:28
openshot::Mask::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: Mask.h:69
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::ZmqLogger::Log
void Log(std::string message)
Log message to all subscribers of this logger (if any)
Definition: ZmqLogger.cpp:103
openshot::EffectBase::JsonValue
virtual Json::Value JsonValue() const
Generate Json::Value for this object.
Definition: EffectBase.cpp:79
openshot::Mask::contrast
Keyframe contrast
Contrast keyframe to control the hardness of the wipe effect / mask.
Definition: Mask.h:49
openshot::ReaderBase::info
openshot::ReaderInfo info
Information about the current media file.
Definition: ReaderBase.h:88
openshot::Keyframe::SetJsonValue
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: KeyFrame.cpp:372
openshot::Mask::Mask
Mask()
Blank constructor, useful when using Json to load the effect properties.
Definition: Mask.cpp:31
openshot::Keyframe::JsonValue
Json::Value JsonValue() const
Generate Json::Value for this object.
Definition: KeyFrame.cpp:339
openshot::Mask::PropertiesJSON
std::string PropertiesJSON(int64_t requested_frame) const override
Definition: Mask.cpp:291
openshot::QtImageReader
This class uses the Qt library, to open image files, and return openshot::Frame objects containing th...
Definition: QtImageReader.h:74
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:179
ZmqLogger.h
Header file for ZeroMQ-based Logger class.
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::ReaderBase::Open
virtual void Open()=0
Open the reader (and start consuming resources, such as images or video files)
openshot::ReaderBase::IsOpen
virtual bool IsOpen()=0
Determine if reader is open or closed.
openshot::InvalidJSON
Exception for invalid JSON.
Definition: Exceptions.h:223
openshot::ImageReader
This class uses the ImageMagick++ libraries, to open image files, and return openshot::Frame objects ...
Definition: ImageReader.h:55
openshot::EffectBase::InitEffectInfo
void InitEffectInfo()
Definition: EffectBase.cpp:24
openshot::EffectInfoStruct::has_audio
bool has_audio
Determines if this effect manipulates the audio of a frame.
Definition: EffectBase.h:41
openshot::ReaderInfo::has_single_image
bool has_single_image
Determines if this file only contains a single image.
Definition: ReaderBase.h:42
openshot::FFmpegReader
This class uses the FFmpeg libraries, to open video files and audio files, and return openshot::Frame...
Definition: FFmpegReader.h:103
ChunkReader.h
Header file for ChunkReader class.
openshot::ZmqLogger::Instance
static ZmqLogger * Instance()
Create or get an instance of this logger singleton (invoke the class with this method)
Definition: ZmqLogger.cpp:35
Mask.h
Header file for Mask class.
openshot::Mask::replace_image
bool replace_image
Replace the frame image with a grayscale image representing the mask. Great for debugging a mask.
Definition: Mask.h:47
openshot::EffectInfoStruct::class_name
std::string class_name
The class name of the effect.
Definition: EffectBase.h:36
ReaderBase.h
Header file for ReaderBase class.
openshot::EffectInfoStruct::description
std::string description
The description of this effect and what it does.
Definition: EffectBase.h:38
openshot::EffectInfoStruct::has_video
bool has_video
Determines if this effect manipulates the image of a frame.
Definition: EffectBase.h:40
openshot::Mask::Json
std::string Json() const override
Generate JSON string of this object.
Definition: Mask.cpp:182
openshot::ReaderBase
This abstract class is the base class, used by all readers in libopenshot.
Definition: ReaderBase.h:75
openshot::EffectInfoStruct::name
std::string name
The name of the effect.
Definition: EffectBase.h:37
openshot::ReaderBase::Close
virtual void Close()=0
Close the reader (and any resources it was consuming)
openshot::Mask::SetJson
void SetJson(const std::string value) override
Load JSON string into this object.
Definition: Mask.cpp:207
QtImageReader.h
Header file for QtImageReader class.
openshot::Mask::brightness
Keyframe brightness
Brightness keyframe to control the wipe / mask effect. A constant value here will prevent animation.
Definition: Mask.h:48
ImageReader.h
Header file for ImageReader class.
openshot::Mask::SetJsonValue
void SetJsonValue(const Json::Value root) override
Load Json::Value into this object.
Definition: Mask.cpp:224
openshot::ChunkVersion
ChunkVersion
This enumeration allows the user to choose which version of the chunk they would like (low,...
Definition: ChunkReader.h:49
Exceptions.h
Header file for all Exception classes.
FFmpegReader.h
Header file for FFmpegReader class.
openshot::EffectBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: EffectBase.cpp:115
openshot::Keyframe::GetValue
double GetValue(int64_t index) const
Get the value at a specific index.
Definition: KeyFrame.cpp:258