OpenShot Library | libopenshot  0.1.9
ChunkReader.cpp
Go to the documentation of this file.
1 /**
2  * @file
3  * @brief Source file for ChunkReader 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/ChunkReader.h"
29 
30 using namespace openshot;
31 
32 ChunkReader::ChunkReader(string path, ChunkVersion chunk_version)
33  : path(path), chunk_size(24 * 3), is_open(false), version(chunk_version), local_reader(NULL)
34 {
35  // Check if folder exists?
36  if (!does_folder_exist(path))
37  // Raise exception
38  throw InvalidFile("Chunk folder could not be opened.", path);
39 
40  // Init previous location
41  previous_location.number = 0;
42  previous_location.frame = 0;
43 
44  // Open and Close the reader, to populate it's attributes (such as height, width, etc...)
45  Open();
46  Close();
47 }
48 
49 // Check if folder path existing
50 bool ChunkReader::does_folder_exist(string path)
51 {
52  QDir dir(path.c_str());
53  return dir.exists();
54 }
55 
56 // Load JSON meta data about this chunk folder
57 void ChunkReader::load_json()
58 {
59  // Load path of chunk folder
60  string json_path = QDir::cleanPath(QString(path.c_str()) + QDir::separator() + "info.json").toStdString();
61  stringstream json_string;
62 
63  // Read the JSON file
64  ifstream myfile (json_path.c_str());
65  string line = "";
66  if (myfile.is_open())
67  {
68  while (myfile.good())
69  {
70  getline (myfile, line);
71  json_string << line;
72  }
73  myfile.close();
74  }
75 
76  // Parse JSON string into JSON objects
77  Json::Value root;
78  Json::Reader reader;
79  bool success = reader.parse( json_string.str(), root );
80  if (!success)
81  // Raise exception
82  throw InvalidJSON("Chunk folder could not be opened.", path);
83 
84 
85  // Set info from the JSON objects
86  try
87  {
88  info.has_video = root["has_video"].asBool();
89  info.has_audio = root["has_audio"].asBool();
90  info.duration = root["duration"].asDouble();
91  info.file_size = atoll(root["file_size"].asString().c_str());
92  info.height = root["height"].asInt();
93  info.width = root["width"].asInt();
94  info.pixel_format = root["pixel_format"].asInt();
95  info.fps.num = root["fps"]["num"].asInt();
96  info.fps.den = root["fps"]["den"].asInt();
97  info.video_bit_rate = root["video_bit_rate"].asUInt();
98  info.pixel_ratio.num = root["pixel_ratio"]["num"].asInt();
99  info.pixel_ratio.den = root["pixel_ratio"]["den"].asInt();
100  info.display_ratio.num = root["display_ratio"]["num"].asInt();
101  info.display_ratio.den = root["display_ratio"]["den"].asInt();
102  info.vcodec = root["vcodec"].asString();
103  info.video_length = atoll(root["video_length"].asString().c_str());
104  info.video_stream_index = root["video_stream_index"].asInt();
105  info.video_timebase.num = root["video_timebase"]["num"].asInt();
106  info.video_timebase.den = root["video_timebase"]["den"].asInt();
107  info.interlaced_frame = root["interlaced_frame"].asBool();
108  info.top_field_first = root["top_field_first"].asBool();
109  info.acodec = root["acodec"].asString();
110  info.audio_bit_rate = root["audio_bit_rate"].asUInt();
111  info.sample_rate = root["sample_rate"].asUInt();
112  info.channels = root["channels"].asInt();
113  info.audio_stream_index = root["audio_stream_index"].asInt();
114  info.audio_timebase.num = root["audio_timebase"]["num"].asInt();
115  info.audio_timebase.den = root["audio_timebase"]["den"].asInt();
116 
117  }
118  catch (exception e)
119  {
120  // Error parsing JSON (or missing keys)
121  throw InvalidJSON("JSON could not be parsed (or is invalid).", path);
122  }
123 }
124 
125 // Find the location of a frame in a chunk
126 ChunkLocation ChunkReader::find_chunk_frame(int64_t requested_frame)
127 {
128  // Determine which chunk contains this frame.
129  int64_t chunk_number = (requested_frame / chunk_size) + 1;
130 
131  // Determine which frame in this chunk
132  int64_t start_frame_of_chunk = (chunk_number - 1) * chunk_size;
133  int64_t chunk_frame_number = (requested_frame - start_frame_of_chunk) + 1; // Add 1 to adjust for the 1st frame of every chunk is just there to "stoke" the audio samples from the previous chunk.
134 
135  // Prepare chunk location struct
136  ChunkLocation location = {chunk_number, chunk_frame_number};
137 
138  return location;
139 }
140 
141 // Open chunk folder or file
143 {
144  // Open reader if not already open
145  if (!is_open)
146  {
147  // parse JSON and load info.json file
148  load_json();
149 
150  // Mark as "open"
151  is_open = true;
152  }
153 }
154 
155 // Close image file
157 {
158  // Close all objects, if reader is 'open'
159  if (is_open)
160  {
161  // Mark as "closed"
162  is_open = false;
163  }
164 }
165 
166 // get a formatted path of a specific chunk
167 string ChunkReader::get_chunk_path(int64_t chunk_number, string folder, string extension)
168 {
169  // Create path of new chunk video
170  stringstream chunk_count_string;
171  chunk_count_string << chunk_number;
172  QString padded_count = "%1"; //chunk_count_string.str().c_str();
173  padded_count = padded_count.arg(chunk_count_string.str().c_str(), 6, '0');
174  if (folder.length() != 0 && extension.length() != 0)
175  // Return path with FOLDER and EXTENSION name
176  return QDir::cleanPath(QString(path.c_str()) + QDir::separator() + folder.c_str() + QDir::separator() + padded_count + extension.c_str()).toStdString();
177 
178  else if (folder.length() == 0 && extension.length() != 0)
179  // Return path with NO FOLDER and EXTENSION name
180  return QDir::cleanPath(QString(path.c_str()) + QDir::separator() + padded_count + extension.c_str()).toStdString();
181 
182  else if (folder.length() != 0 && extension.length() == 0)
183  // Return path with FOLDER and NO EXTENSION
184  return QDir::cleanPath(QString(path.c_str()) + QDir::separator() + folder.c_str()).toStdString();
185  else
186  return "";
187 }
188 
189 // Get an openshot::Frame object for a specific frame number of this reader.
190 std::shared_ptr<Frame> ChunkReader::GetFrame(int64_t requested_frame)
191 {
192  // Determine what chunk contains this frame
193  ChunkLocation location = find_chunk_frame(requested_frame);
194 
195  // New Chunk (Close the old reader, and open the new one)
196  if (previous_location.number != location.number)
197  {
198  // Determine version of chunk
199  string folder_name = "";
200  switch (version)
201  {
202  case THUMBNAIL:
203  folder_name = "thumb";
204  break;
205  case PREVIEW:
206  folder_name = "preview";
207  break;
208  case FINAL:
209  folder_name = "final";
210  break;
211  }
212 
213  // Load path of chunk video
214  string chunk_video_path = get_chunk_path(location.number, folder_name, ".webm");
215 
216  // Close existing reader (if needed)
217  if (local_reader)
218  {
219  cout << "Close READER" << endl;
220  // Close and delete old reader
221  local_reader->Close();
222  delete local_reader;
223  }
224 
225  try
226  {
227  cout << "Load READER: " << chunk_video_path << endl;
228  // Load new FFmpegReader
229  local_reader = new FFmpegReader(chunk_video_path);
230  local_reader->enable_seek = false; // disable seeking
231  local_reader->Open(); // open reader
232 
233  } catch (InvalidFile)
234  {
235  // Invalid Chunk (possibly it is not found)
236  throw ChunkNotFound(path, requested_frame, location.number, location.frame);
237  }
238 
239  // Set the new location
240  previous_location = location;
241  }
242 
243  // Get the frame (from the current reader)
244  last_frame = local_reader->GetFrame(location.frame);
245 
246  // Update the frame number property
247  last_frame->number = requested_frame;
248 
249  // Return the frame
250  return last_frame;
251 }
252 
253 // Generate JSON string of this object
255 
256  // Return formatted string
257  return JsonValue().toStyledString();
258 }
259 
260 // Generate Json::JsonValue for this object
261 Json::Value ChunkReader::JsonValue() {
262 
263  // Create root json object
264  Json::Value root = ReaderBase::JsonValue(); // get parent properties
265  root["type"] = "ChunkReader";
266  root["path"] = path;
267  stringstream chunk_size_stream;
268  chunk_size_stream << chunk_size;
269  root["chunk_size"] = chunk_size_stream.str();
270  root["chunk_version"] = version;
271 
272  // return JsonValue
273  return root;
274 }
275 
276 // Load JSON string into this object
277 void ChunkReader::SetJson(string value) {
278 
279  // Parse JSON string into JSON objects
280  Json::Value root;
281  Json::Reader reader;
282  bool success = reader.parse( value, root );
283  if (!success)
284  // Raise exception
285  throw InvalidJSON("JSON could not be parsed (or is invalid)", "");
286 
287  try
288  {
289  // Set all values that match
290  SetJsonValue(root);
291  }
292  catch (exception e)
293  {
294  // Error parsing JSON (or missing keys)
295  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)", "");
296  }
297 }
298 
299 // Load Json::JsonValue into this object
300 void ChunkReader::SetJsonValue(Json::Value root) {
301 
302  // Set parent data
304 
305  // Set data from Json (if key is found)
306  if (!root["path"].isNull())
307  path = root["path"].asString();
308  if (!root["chunk_size"].isNull())
309  chunk_size = atoll(root["chunk_size"].asString().c_str());
310  if (!root["chunk_version"].isNull())
311  version = (ChunkVersion) root["chunk_version"].asInt();
312 
313  // Re-Open path, and re-init everything (if needed)
314  if (is_open)
315  {
316  Close();
317  Open();
318  }
319 }
string Json()
Get and Set JSON methods.
int num
Numerator for the fraction.
Definition: Fraction.h:44
void SetJsonValue(Json::Value root)
Load Json::JsonValue into this object.
void Open()
Open the reader. This is required before you can access frames or data from the reader.
Exception when a required chunk is missing.
Definition: Exceptions.h:56
void SetJson(string value)
Load JSON string into this object.
int width
The width of the video (in pixesl)
Definition: ReaderBase.h:67
std::shared_ptr< Frame > GetFrame(int64_t requested_frame)
void Close()
Close the reader.
float duration
Length of time (in seconds)
Definition: ReaderBase.h:64
The lowest quality stream contained in this chunk file.
Definition: ChunkReader.h:77
string acodec
The name of the audio codec used to encode / decode the video stream.
Definition: ReaderBase.h:79
bool has_video
Determines if this file has a video stream.
Definition: ReaderBase.h:61
void Close()
Close File.
Json::Value JsonValue()
Generate Json::JsonValue for this object.
Fraction display_ratio
The ratio of width to height of the video stream (i.e. 640x480 has a ratio of 4/3) ...
Definition: ReaderBase.h:72
int64_t file_size
Size of file (in bytes)
Definition: ReaderBase.h:65
int audio_bit_rate
The bit rate of the audio stream (in bytes)
Definition: ReaderBase.h:80
bool has_audio
Determines if this file has an audio stream.
Definition: ReaderBase.h:62
This class uses the FFmpeg libraries, to open video files and audio files, and return openshot::Frame...
Definition: FFmpegReader.h:92
The highest quality stream contained in this chunk file.
Definition: ChunkReader.h:79
int audio_stream_index
The index of the audio stream.
Definition: ReaderBase.h:84
The medium quality stream contained in this chunk file.
Definition: ChunkReader.h:78
int64_t video_length
The number of frames in the video stream.
Definition: ReaderBase.h:74
int height
The height of the video (in pixels)
Definition: ReaderBase.h:66
Exception for files that can not be found or opened.
Definition: Exceptions.h:132
std::shared_ptr< Frame > GetFrame(int64_t requested_frame)
Get an openshot::Frame object for a specific frame number of this reader.
virtual Json::Value JsonValue()=0
Generate Json::JsonValue for this object.
Definition: ReaderBase.cpp:106
int64_t number
The chunk number.
Definition: ChunkReader.h:61
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
ReaderInfo info
Information about the current media file.
Definition: ReaderBase.h:111
Fraction fps
Frames per second, as a fraction (i.e. 24/1 = 24 fps)
Definition: ReaderBase.h:69
Fraction video_timebase
The video timebase determines how long each frame stays on the screen.
Definition: ReaderBase.h:76
Fraction pixel_ratio
The pixel ratio of the video stream as a fraction (i.e. some pixels are not square) ...
Definition: ReaderBase.h:71
This namespace is the default namespace for all code in the openshot library.
Exception for invalid JSON.
Definition: Exceptions.h:152
int pixel_format
The pixel format (i.e. YUV420P, RGB24, etc...)
Definition: ReaderBase.h:68
void Open()
Open File - which is called by the constructor automatically.
int video_bit_rate
The bit rate of the video stream (in bytes)
Definition: ReaderBase.h:70
int64_t frame
The frame number.
Definition: ChunkReader.h:62
Fraction audio_timebase
The audio timebase determines how long each audio packet should be played.
Definition: ReaderBase.h:85
string vcodec
The name of the video codec used to encode / decode the video stream.
Definition: ReaderBase.h:73
int den
Denominator for the fraction.
Definition: Fraction.h:45
int channels
The number of audio channels used in the audio stream.
Definition: ReaderBase.h:82
This struct holds the location of a frame within a chunk.
Definition: ChunkReader.h:59
int video_stream_index
The index of the video stream.
Definition: ReaderBase.h:75
ChunkReader(string path, ChunkVersion chunk_version)
Constructor for ChunkReader. This automatically opens the chunk file or folder and loads frame 1...
Definition: ChunkReader.cpp:32
int sample_rate
The number of audio samples per second (44100 is a common sample rate)
Definition: ReaderBase.h:81