OpenShot Library | libopenshot  0.2.0
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 // This method is required for all derived classes of EffectBase, and returns a
61 // modified openshot::Frame object
62 std::shared_ptr<Frame> Mask::GetFrame(std::shared_ptr<Frame> frame, int64_t frame_number) {
63  // Get the mask image (from the mask reader)
64  std::shared_ptr<QImage> frame_image = frame->GetImage();
65 
66  // Check if mask reader is open
67  #pragma omp critical (open_mask_reader)
68  {
69  if (reader && !reader->IsOpen())
70  reader->Open();
71  }
72 
73  // No reader (bail on applying the mask)
74  if (!reader)
75  return frame;
76 
77  // Get mask image (if missing or different size than frame image)
78  #pragma omp critical (open_mask_reader)
79  {
80  if (!original_mask || !reader->info.has_single_image ||
81  (original_mask && original_mask->size() != frame_image->size())) {
82 
83  // Only get mask if needed
84  std::shared_ptr<QImage> mask_without_sizing = std::shared_ptr<QImage>(
85  new QImage(*reader->GetFrame(frame_number)->GetImage()));
86 
87  // Resize mask image to match frame size
88  original_mask = std::shared_ptr<QImage>(new QImage(
89  mask_without_sizing->scaled(frame_image->width(), frame_image->height(), Qt::IgnoreAspectRatio,
90  Qt::SmoothTransformation)));
91  }
92  }
93 
94  // Get pixel arrays
95  unsigned char *pixels = (unsigned char *) frame_image->bits();
96  unsigned char *mask_pixels = (unsigned char *) original_mask->bits();
97 
98  int R = 0;
99  int G = 0;
100  int B = 0;
101  int A = 0;
102  int gray_value = 0;
103  float factor = 0.0;
104  double contrast_value = (contrast.GetValue(frame_number));
105  double brightness_value = (brightness.GetValue(frame_number));
106 
107  // Loop through mask pixels, and apply average gray value to frame alpha channel
108  for (int pixel = 0, byte_index=0; pixel < original_mask->width() * original_mask->height(); pixel++, byte_index+=4)
109  {
110  // Get the RGB values from the pixel
111  R = mask_pixels[byte_index];
112  G = mask_pixels[byte_index + 1];
113  B = mask_pixels[byte_index + 2];
114 
115  // Get the average luminosity
116  gray_value = qGray(R, G, B);
117 
118  // Adjust the contrast
119  factor = (259 * (contrast_value + 255)) / (255 * (259 - contrast_value));
120  gray_value = constrain((factor * (gray_value - 128)) + 128);
121 
122  // Adjust the brightness
123  gray_value += (255 * brightness_value);
124 
125  // Constrain the value from 0 to 255
126  gray_value = constrain(gray_value);
127 
128  // Set the alpha channel to the gray value
129  if (replace_image) {
130  // Replace frame pixels with gray value
131  pixels[byte_index + 0] = gray_value;
132  pixels[byte_index + 1] = gray_value;
133  pixels[byte_index + 2] = gray_value;
134  } else {
135  // Set alpha channel
136  A = pixels[byte_index + 3];
137  pixels[byte_index + 3] = constrain(A - gray_value);
138  }
139 
140  }
141 
142  // return the modified frame
143  return frame;
144 }
145 
146 // Generate JSON string of this object
147 string Mask::Json() {
148 
149  // Return formatted string
150  return JsonValue().toStyledString();
151 }
152 
153 // Generate Json::JsonValue for this object
154 Json::Value Mask::JsonValue() {
155 
156  // Create root json object
157  Json::Value root = EffectBase::JsonValue(); // get parent properties
158  root["type"] = info.class_name;
159  root["brightness"] = brightness.JsonValue();
160  root["contrast"] = contrast.JsonValue();
161  if (reader)
162  root["reader"] = reader->JsonValue();
163  else
164  root["reader"] = Json::objectValue;
165  root["replace_image"] = replace_image;
166 
167  // return JsonValue
168  return root;
169 }
170 
171 // Load JSON string into this object
172 void Mask::SetJson(string value) {
173 
174  // Parse JSON string into JSON objects
175  Json::Value root;
176  Json::Reader reader;
177  bool success = reader.parse( value, root );
178  if (!success)
179  // Raise exception
180  throw InvalidJSON("JSON could not be parsed (or is invalid)", "");
181 
182  try
183  {
184  // Set all values that match
185  SetJsonValue(root);
186  }
187  catch (exception e)
188  {
189  // Error parsing JSON (or missing keys)
190  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)", "");
191  }
192 }
193 
194 // Load Json::JsonValue into this object
195 void Mask::SetJsonValue(Json::Value root) {
196 
197  // Set parent data
199 
200  // Set data from Json (if key is found)
201  if (!root["replace_image"].isNull())
202  replace_image = root["replace_image"].asBool();
203  if (!root["brightness"].isNull())
204  brightness.SetJsonValue(root["brightness"]);
205  if (!root["contrast"].isNull())
206  contrast.SetJsonValue(root["contrast"]);
207  if (!root["reader"].isNull()) // does Json contain a reader?
208  {
209 
210  if (!root["reader"]["type"].isNull()) // does the reader Json contain a 'type'?
211  {
212  // Close previous reader (if any)
213  if (reader)
214  {
215  // Close and delete existing reader (if any)
216  reader->Close();
217  delete reader;
218  reader = NULL;
219  }
220 
221  // Create new reader (and load properties)
222  string type = root["reader"]["type"].asString();
223 
224  if (type == "FFmpegReader") {
225 
226  // Create new reader
227  reader = new FFmpegReader(root["reader"]["path"].asString());
228  reader->SetJsonValue(root["reader"]);
229 
230 #ifdef USE_IMAGEMAGICK
231  } else if (type == "ImageReader") {
232 
233  // Create new reader
234  reader = new ImageReader(root["reader"]["path"].asString());
235  reader->SetJsonValue(root["reader"]);
236 #endif
237 
238  } else if (type == "QtImageReader") {
239 
240  // Create new reader
241  reader = new QtImageReader(root["reader"]["path"].asString());
242  reader->SetJsonValue(root["reader"]);
243 
244  } else if (type == "ChunkReader") {
245 
246  // Create new reader
247  reader = new ChunkReader(root["reader"]["path"].asString(), (ChunkVersion) root["reader"]["chunk_version"].asInt());
248  reader->SetJsonValue(root["reader"]);
249 
250  }
251 
252  }
253  }
254 
255 }
256 
257 // Get all properties for a specific frame
258 string Mask::PropertiesJSON(int64_t requested_frame) {
259 
260  // Generate JSON properties list
261  Json::Value root;
262  root["id"] = add_property_json("ID", 0.0, "string", Id(), NULL, -1, -1, true, requested_frame);
263  root["position"] = add_property_json("Position", Position(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
264  root["layer"] = add_property_json("Track", Layer(), "int", "", NULL, 0, 20, false, requested_frame);
265  root["start"] = add_property_json("Start", Start(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
266  root["end"] = add_property_json("End", End(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
267  root["duration"] = add_property_json("Duration", Duration(), "float", "", NULL, 0, 30 * 60 * 60 * 48, true, requested_frame);
268  root["replace_image"] = add_property_json("Replace Image", replace_image, "int", "", NULL, 0, 1, false, requested_frame);
269 
270  // Add replace_image choices (dropdown style)
271  root["replace_image"]["choices"].append(add_property_choice_json("Yes", true, replace_image));
272  root["replace_image"]["choices"].append(add_property_choice_json("No", false, replace_image));
273 
274  // Keyframes
275  root["brightness"] = add_property_json("Brightness", brightness.GetValue(requested_frame), "float", "", &brightness, -1.0, 1.0, false, requested_frame);
276  root["contrast"] = add_property_json("Contrast", contrast.GetValue(requested_frame), "float", "", &contrast, 0, 20, false, requested_frame);
277 
278  // Return formatted string
279  return root.toStyledString();
280 }
281 
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:154
bool replace_image
Replace the frame image with a grayscale image representing the mask. Great for debugging a mask...
Definition: Mask.h:73
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:62
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:96
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:81
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:75
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:147
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:258
virtual Json::Value JsonValue()=0
Generate Json::JsonValue for this object.
Definition: ReaderBase.cpp:113
virtual void SetJsonValue(Json::Value root)=0
Load Json::JsonValue into this object.
Definition: EffectBase.cpp:121
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:168
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:112
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:195
Keyframe brightness
Brightness keyframe to control the wipe / mask effect. A constant value here will prevent animation...
Definition: Mask.h:74
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:172
int constrain(int color_value)
Constrain a color value from 0 to 255.
Definition: EffectBase.cpp:62
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.