OpenShot Library | libopenshot  0.2.2
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), needs_refresh(true) {
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), needs_refresh(true)
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 || needs_refresh ||
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  // Refresh no longer needed
95  needs_refresh = false;
96 
97  // Get pixel arrays
98  unsigned char *pixels = (unsigned char *) frame_image->bits();
99  unsigned char *mask_pixels = (unsigned char *) original_mask->bits();
100 
101  int R = 0;
102  int G = 0;
103  int B = 0;
104  int A = 0;
105  int gray_value = 0;
106  float factor = 0.0;
107  double contrast_value = (contrast.GetValue(frame_number));
108  double brightness_value = (brightness.GetValue(frame_number));
109 
110  // Loop through mask pixels, and apply average gray value to frame alpha channel
111  for (int pixel = 0, byte_index=0; pixel < original_mask->width() * original_mask->height(); pixel++, byte_index+=4)
112  {
113  // Get the RGB values from the pixel
114  R = mask_pixels[byte_index];
115  G = mask_pixels[byte_index + 1];
116  B = mask_pixels[byte_index + 2];
117 
118  // Get the average luminosity
119  gray_value = qGray(R, G, B);
120 
121  // Adjust the contrast
122  factor = (259 * (contrast_value + 255)) / (255 * (259 - contrast_value));
123  gray_value = constrain((factor * (gray_value - 128)) + 128);
124 
125  // Adjust the brightness
126  gray_value += (255 * brightness_value);
127 
128  // Constrain the value from 0 to 255
129  gray_value = constrain(gray_value);
130 
131  // Set the alpha channel to the gray value
132  if (replace_image) {
133  // Replace frame pixels with gray value
134  pixels[byte_index + 0] = gray_value;
135  pixels[byte_index + 1] = gray_value;
136  pixels[byte_index + 2] = gray_value;
137  } else {
138  // Set alpha channel
139  A = pixels[byte_index + 3];
140  pixels[byte_index + 3] = constrain(A - gray_value);
141  }
142 
143  }
144 
145  // return the modified frame
146  return frame;
147 }
148 
149 // Generate JSON string of this object
150 string Mask::Json() {
151 
152  // Return formatted string
153  return JsonValue().toStyledString();
154 }
155 
156 // Generate Json::JsonValue for this object
157 Json::Value Mask::JsonValue() {
158 
159  // Create root json object
160  Json::Value root = EffectBase::JsonValue(); // get parent properties
161  root["type"] = info.class_name;
162  root["brightness"] = brightness.JsonValue();
163  root["contrast"] = contrast.JsonValue();
164  if (reader)
165  root["reader"] = reader->JsonValue();
166  else
167  root["reader"] = Json::objectValue;
168  root["replace_image"] = replace_image;
169 
170  // return JsonValue
171  return root;
172 }
173 
174 // Load JSON string into this object
175 void Mask::SetJson(string value) {
176 
177  // Parse JSON string into JSON objects
178  Json::Value root;
179  Json::Reader reader;
180  bool success = reader.parse( value, root );
181  if (!success)
182  // Raise exception
183  throw InvalidJSON("JSON could not be parsed (or is invalid)", "");
184 
185  try
186  {
187  // Set all values that match
188  SetJsonValue(root);
189  }
190  catch (exception e)
191  {
192  // Error parsing JSON (or missing keys)
193  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)", "");
194  }
195 }
196 
197 // Load Json::JsonValue into this object
198 void Mask::SetJsonValue(Json::Value root) {
199 
200  // Set parent data
202 
203  // Set data from Json (if key is found)
204  if (!root["replace_image"].isNull())
205  replace_image = root["replace_image"].asBool();
206  if (!root["brightness"].isNull())
207  brightness.SetJsonValue(root["brightness"]);
208  if (!root["contrast"].isNull())
209  contrast.SetJsonValue(root["contrast"]);
210  if (!root["reader"].isNull()) // does Json contain a reader?
211  {
212  #pragma omp critical (open_mask_reader)
213  {
214  // This reader has changed, so refresh cached assets
215  needs_refresh = true;
216 
217  if (!root["reader"]["type"].isNull()) // does the reader Json contain a 'type'?
218  {
219  // Close previous reader (if any)
220  if (reader) {
221  // Close and delete existing reader (if any)
222  reader->Close();
223  delete reader;
224  reader = NULL;
225  }
226 
227  // Create new reader (and load properties)
228  string type = root["reader"]["type"].asString();
229 
230  if (type == "FFmpegReader") {
231 
232  // Create new reader
233  reader = new FFmpegReader(root["reader"]["path"].asString());
234  reader->SetJsonValue(root["reader"]);
235 
236  #ifdef USE_IMAGEMAGICK
237  } else if (type == "ImageReader") {
238 
239  // Create new reader
240  reader = new ImageReader(root["reader"]["path"].asString());
241  reader->SetJsonValue(root["reader"]);
242  #endif
243 
244  } else if (type == "QtImageReader") {
245 
246  // Create new reader
247  reader = new QtImageReader(root["reader"]["path"].asString());
248  reader->SetJsonValue(root["reader"]);
249 
250  } else if (type == "ChunkReader") {
251 
252  // Create new reader
253  reader = new ChunkReader(root["reader"]["path"].asString(), (ChunkVersion) root["reader"]["chunk_version"].asInt());
254  reader->SetJsonValue(root["reader"]);
255 
256  }
257  }
258 
259  }
260  }
261 
262 }
263 
264 // Get all properties for a specific frame
265 string Mask::PropertiesJSON(int64_t requested_frame) {
266 
267  // Generate JSON properties list
268  Json::Value root;
269  root["id"] = add_property_json("ID", 0.0, "string", Id(), NULL, -1, -1, true, requested_frame);
270  root["position"] = add_property_json("Position", Position(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
271  root["layer"] = add_property_json("Track", Layer(), "int", "", NULL, 0, 20, false, requested_frame);
272  root["start"] = add_property_json("Start", Start(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
273  root["end"] = add_property_json("End", End(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
274  root["duration"] = add_property_json("Duration", Duration(), "float", "", NULL, 0, 30 * 60 * 60 * 48, true, requested_frame);