OpenShot Library | libopenshot  0.1.9
Mask.cpp
Go to the documentation of this file.
1 /**
2  * @file
3  * @brief Source file for Mask class
4  * @author Jonathan Thomas <jonathan@openshot.org>
5  *
6  * @section LICENSE
7  *
8  * Copyright (c) 2008-2014 OpenShot Studios, LLC
9  * <http://www.openshotstudios.com/>. This file is part of
10  * OpenShot Library (libopenshot), an open-source project dedicated to
11  * delivering high quality video editing and animation solutions to the
12  * world. For more information visit <http://www.openshot.org/>.
13  *
14  * OpenShot Library (libopenshot) is free software: you can redistribute it
15  * and/or modify it under the terms of the GNU Lesser General Public License
16  * as published by the Free Software Foundation, either version 3 of the
17  * License, or (at your option) any later version.
18  *
19  * OpenShot Library (libopenshot) is distributed in the hope that it will be
20  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22  * GNU Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public License
25  * along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
26  */
27 
28 #include "../../include/effects/Mask.h"
29 
30 using namespace openshot;
31 
32 /// Blank constructor, useful when using Json to load the effect properties
33 Mask::Mask() : reader(NULL), replace_image(false) {
34  // Init effect properties
35  init_effect_details();
36 }
37 
38 // Default constructor
39 Mask::Mask(ReaderBase *mask_reader, Keyframe mask_brightness, Keyframe mask_contrast) :
40  reader(mask_reader), brightness(mask_brightness), contrast(mask_contrast), replace_image(false)
41 {
42  // Init effect properties
43  init_effect_details();
44 }
45 
46 // Init effect settings
47 void Mask::init_effect_details()
48 {
49  /// Initialize the values of the EffectInfo struct.
51 
52  /// Set the effect info
53  info.class_name = "Mask";
54  info.name = "Alpha Mask / Wipe Transition";
55  info.description = "Uses a grayscale mask image to gradually wipe / transition between 2 images.";
56  info.has_audio = false;
57  info.has_video = true;
58 }
59 
60 // Constrain a color value from 0 to 255
61 int Mask::constrain(int color_value)
62 {
63  // Constrain new color from 0 to 255
64  if (color_value < 0)
65  color_value = 0;
66  else if (color_value > 255)
67  color_value = 255;
68 
69  return color_value;
70 }
71 
72 // Get grayscale mask image
73 void Mask::set_grayscale_mask(std::shared_ptr<QImage> mask_frame_image, int width, int height, float brightness, float contrast)
74 {
75  // Get pixels for mask image
76  unsigned char *pixels = (unsigned char *) mask_frame_image->bits();
77 
78  // Convert the mask image to grayscale
79  // Loop through pixels
80  for (int pixel = 0, byte_index=0; pixel < mask_frame_image->width() * mask_frame_image->height(); pixel++, byte_index+=4)
81  {
82  // Get the RGB values from the pixel
83  int R = pixels[byte_index];
84  int G = pixels[byte_index + 1];
85  int B = pixels[byte_index + 2];
86 
87  // Get the average luminosity
88  int gray_value = qGray(R, G, B);
89 
90  // Adjust the contrast
91  int factor = (259 * (contrast + 255)) / (255 * (259 - contrast));
92  gray_value = constrain((factor * (gray_value - 128)) + 128);
93 
94  // Adjust the brightness
95  gray_value += (255 * brightness);
96 
97  // Constrain the value from 0 to 255
98  gray_value = constrain(gray_value);
99 
100  // Set all pixels to gray value
101  pixels[byte_index] = gray_value;
102  pixels[byte_index + 1] = gray_value;
103  pixels[byte_index + 2] = gray_value;
104  pixels[byte_index + 3] = 255;
105  }
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<Frame> Mask::GetFrame(std::shared_ptr<Frame> frame, int64_t frame_number)
111 {
112  // Get the mask image (from the mask reader)
113  std::shared_ptr<QImage> frame_image = frame->GetImage();
114 
115  // Check if mask reader is open
116  if (reader && !reader->IsOpen())
117  #pragma omp critical (open_mask_reader)
118  reader->Open();
119 
120  // No reader (bail on applying the mask)
121  if (!reader)
122  return frame;
123 
124  // Get mask image (if missing or different size than frame image)
125  if (!original_mask || !reader->info.has_single_image ||
126  (original_mask && original_mask->size() != frame_image->size())) {
127  #pragma omp critical (open_mask_reader)
128  {
129  // Only get mask if needed
130  std::shared_ptr<QImage> mask_without_sizing = std::shared_ptr<QImage>(new QImage(*reader->GetFrame(frame_number)->GetImage()));
131 
132  // Resize mask image to match frame size
133  original_mask = std::shared_ptr<QImage>(new QImage(
134  mask_without_sizing->scaled(frame_image->width(), frame_image->height(), Qt::IgnoreAspectRatio,
135  Qt::SmoothTransformation)));
136  }
137  }
138 
139  // Convert mask to grayscale and resize to frame size
140  std::shared_ptr<QImage> mask = std::shared_ptr<QImage>(new QImage(*original_mask));
141  set_grayscale_mask(mask, frame_image->width(), frame_image->height(), brightness.GetValue(frame_number), contrast.GetValue(frame_number));
142 
143  // Get pixels for frame image
144  unsigned char *pixels = (unsigned char *) frame_image->bits();
145  unsigned char *mask_pixels = (unsigned char *) mask->bits();
146 
147  // Convert the mask image to grayscale
148  // Loop through pixels
149  for (int pixel = 0, byte_index=0; pixel < frame_image->width() * frame_image->height(); pixel++, byte_index+=4)
150  {
151  // Get the RGB values from the pixel
152  int Frame_Alpha = pixels[byte_index + 3];
153  int Mask_Value = constrain(Frame_Alpha - (int)mask_pixels[byte_index]); // Red pixel (all colors should have the same value here)
154 
155  // Set all pixels to gray value
156  pixels[byte_index + 3] = Mask_Value;
157  }
158 
159  // Replace the frame's image with the current mask (good for debugging)
160  if (replace_image)
161  frame->AddImage(mask); // not typically called when using a mask
162 
163  // return the modified frame
164  return frame;
165 }
166 
167 // Generate JSON string of this object
168 string Mask::Json() {
169 
170  // Return formatted string
171  return JsonValue().toStyledString();
172 }
173 
174 // Generate Json::JsonValue for this object
175 Json::Value Mask::JsonValue() {
176 
177  // Create root json object
178  Json::Value root = EffectBase::JsonValue(); // get parent properties
179  root["type"] = info.class_name;
180  root["brightness"] = brightness.JsonValue();
181  root["contrast"] = contrast.JsonValue();
182  if (reader)
183  root["reader"] = reader->JsonValue();
184  else
185  root["reader"] = Json::objectValue;
186  root["replace_image"] = replace_image;
187 
188  // return JsonValue
189  return root;
190 }
191 
192 // Load JSON string into this object
193 void Mask::SetJson(string value) {
194 
195  // Parse JSON string into JSON objects
196  Json::Value root;
197  Json::Reader reader;
198  bool success = reader.parse( value, root );
199  if (!success)
200  // Raise exception
201  throw InvalidJSON("JSON could not be parsed (or is invalid)", "");
202 
203  try
204  {
205  // Set all values that match
206  SetJsonValue(root);
207  }
208  catch (exception e)
209  {
210  // Error parsing JSON (or missing keys)
211  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)", "");
212  }
213 }
214 
215 // Load Json::JsonValue into this object
216 void Mask::SetJsonValue(Json::Value root) {
217 
218  // Set parent data
220 
221  // Set data from Json (if key is found)
222  if (!root["replace_image"].isNull())
223  replace_image = root["replace_image"].asBool();
224  if (!root["brightness"].isNull())
225  brightness.SetJsonValue(root["brightness"]);
226  if (!root["contrast"].isNull())
227  contrast.SetJsonValue(root["contrast"]);
228  if (!root["reader"].isNull()) // does Json contain a reader?
229  {
230 
231  if (!root["reader"]["type"].isNull()) // does the reader Json contain a 'type'?
232  {
233  // Close previous reader (if any)
234  if (reader)
235  {
236  // Close and delete existing reader (if any)
237  reader->Close();
238  delete reader;
239  reader = NULL;
240  }
241 
242  // Create new reader (and load properties)
243  string type = root["reader"]["type"].asString();
244 
245  if (type == "FFmpegReader") {
246 
247  // Create new reader
248  reader = new FFmpegReader(root["reader"]["path"].asString());
249  reader->SetJsonValue(root["reader"]);
250 
251 #ifdef USE_IMAGEMAGICK
252  } else if (type == "ImageReader") {
253 
254  // Create new reader
255  reader = new ImageReader(root["reader"]["path"].asString());
256  reader->SetJsonValue(root["reader"]);
257 #endif
258 
259  } else if (type == "QtImageReader") {
260 
261  // Create new reader
262  reader = new QtImageReader(root["reader"]["path"].asString());
263  reader->SetJsonValue(root["reader"]);
264 
265  } else if (type == "ChunkReader") {
266 
267  // Create new reader
268  reader = new ChunkReader(root["reader"]["path"].asString(), (ChunkVersion) root["reader"]["chunk_version"].asInt());
269  reader->SetJsonValue(root["reader"]);
270 
271  }
272 
273  }
274  }
275 
276 }
277 
278 // Get all properties for a specific frame
279 string Mask::PropertiesJSON(int64_t requested_frame) {
280 
281  // Generate JSON properties list
282  Json::Value root;
283  root["id"] = add_property_json("ID", 0.0, "string", Id(), NULL, -1, -1, true, requested_frame);
284  root["position"] = add_property_json("Position", Position(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
285  root["layer"] = add_property_json("Track", Layer(), "int", "", NULL, 0, 20, false, requested_frame);
286  root["start"] = add_property_json("Start", Start(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
287  root["end"] = add_property_json("End", End(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
288  root["duration"] = add_property_json("Duration", Duration(), "float", "", NULL, 0, 30 * 60 * 60 * 48, true, requested_frame);
289  root["replace_image"] = add_property_json("Replace Image", replace_image, "int", "", NULL, 0, 1, false, requested_frame);
290 
291  // Add replace_image choices (dropdown style)
292  root["replace_image"]["choices"].append(add_property_choice_json("Yes", true, replace_image));
293  root["replace_image"]["choices"].append(add_property_choice_json("No", false, replace_image));
294 
295  // Keyframes
296  root["brightness"] = add_property_json("Brightness", brightness.GetValue(requested_frame), "float", "", &brightness, -1.0, 1.0, false, requested_frame);
297  root["contrast"] = add_property_json("Contrast", contrast.GetValue(requested_frame), "float", "", &contrast, 0, 20, false, requested_frame);
298 
299  // Return formatted string
300  return root.toStyledString();
301 }
302 
This class reads a special chunk-formatted file, which can be easily shared in a distributed environm...
Definition: ChunkReader.h:104
Json::Value JsonValue()
Generate Json::JsonValue for this object.
Definition: Mask.cpp:175
bool replace_image
Replace the frame image with a grayscale image representing the mask. Great for debugging a mask...
Definition: Mask.h:79
Json::Value JsonValue()
Generate Json::JsonValue for this object.
Definition: KeyFrame.cpp:321
std::shared_ptr< Frame > GetFrame(std::shared_ptr< Frame > frame, int64_t frame_number)
This method is required for all derived classes of EffectBase, and returns a modified openshot::Frame...
Definition: Mask.cpp:110
float End()
Get end position (in seconds) of clip (trim end of video)
Definition: ClipBase.h:86
Json::Value add_property_json(string name, float value, string type, string memo, Keyframe *keyframe, float min_value, float max_value, bool readonly, int64_t requested_frame)
Generate JSON for a property.
Definition: ClipBase.cpp:65
virtual void Close()=0
Close the reader (and any resources it was consuming)
This abstract class is the base class, used by all readers in libopenshot.
Definition: ReaderBase.h:95
int Layer()
Get layer of clip on timeline (lower number is covered by higher numbers)
Definition: ClipBase.h:84
string class_name
The class name of the effect.
Definition: EffectBase.h:51
virtual Json::Value JsonValue()=0
Generate Json::JsonValue for this object.
Definition: EffectBase.cpp:69
void SetJsonValue(Json::Value root)
Load Json::JsonValue into this object.
Definition: KeyFrame.cpp:362
bool has_audio
Determines if this effect manipulates the audio of a frame.
Definition: EffectBase.h:56
This class uses the ImageMagick++ libraries, to open image files, and return openshot::Frame objects ...
Definition: ImageReader.h:67
virtual std::shared_ptr< Frame > GetFrame(int64_t number)=0
This class uses the FFmpeg libraries, to open video files and audio files, and return openshot::Frame...
Definition: FFmpegReader.h:92
Keyframe contrast
Contrast keyframe to control the hardness of the wipe effect / mask.
Definition: Mask.h:81
Json::Value add_property_choice_json(string name, int value, int selected_value)
Generate JSON choice for a property (dropdown properties)
Definition: ClipBase.cpp:101
string Id()
Get basic properties.
Definition: ClipBase.h:82
float Position()
Get position on timeline (in seconds)
Definition: ClipBase.h:83
string Json()
Get and Set JSON methods.
Definition: Mask.cpp:168
string name
The name of the effect.
Definition: EffectBase.h:53
string description
The description of this effect and what it does.
Definition: EffectBase.h:54
bool has_single_image
Determines if this file only contains a single image.
Definition: ReaderBase.h:63
string PropertiesJSON(int64_t requested_frame)
Definition: Mask.cpp:279
virtual Json::Value JsonValue()=0
Generate Json::JsonValue for this object.
Definition: ReaderBase.cpp:106
virtual void SetJsonValue(Json::Value root)=0
Load Json::JsonValue into this object.
Definition: EffectBase.cpp:109
ChunkVersion
This enumeration allows the user to choose which version of the chunk they would like (low...
Definition: ChunkReader.h:75
virtual void SetJsonValue(Json::Value root)=0
Load Json::JsonValue into this object.
Definition: ReaderBase.cpp:155
Mask()
Blank constructor, useful when using Json to load the effect properties.
Definition: Mask.cpp:33
ReaderInfo info
Information about the current media file.
Definition: ReaderBase.h:111
double GetValue(int64_t index)
Get the value at a specific index.
Definition: KeyFrame.cpp:226
This namespace is the default namespace for all code in the openshot library.
void SetJsonValue(Json::Value root)
Load Json::JsonValue into this object.
Definition: Mask.cpp:216
Keyframe brightness
Brightness keyframe to control the wipe / mask effect. A constant value here will prevent animation...
Definition: Mask.h:80
bool has_video
Determines if this effect manipulates the image of a frame.
Definition: EffectBase.h:55
Exception for invalid JSON.
Definition: Exceptions.h:152
void SetJson(string value)
Load JSON string into this object.
Definition: Mask.cpp:193
This class uses the Qt library, to open image files, and return openshot::Frame objects containing th...
Definition: QtImageReader.h:69
A Keyframe is a collection of Point instances, which is used to vary a number or property over time...
Definition: KeyFrame.h:64
float Duration()
Get the length of this clip (in seconds)
Definition: ClipBase.h:87
float Start()
Get start position (in seconds) of clip (trim start of video)
Definition: ClipBase.h:85
virtual void Open()=0
Open the reader (and start consuming resources, such as images or video files)
EffectInfoStruct info
Information about the current effect.
Definition: EffectBase.h:73
virtual bool IsOpen()=0
Determine if reader is open or closed.