OpenShot Library | libopenshot  0.2.2
FFmpegReader.h
Go to the documentation of this file.
1 /**
2  * @file
3  * @brief Header file for FFmpegReader class
4  * @author Jonathan Thomas <jonathan@openshot.org>, Fabrice Bellard
5  *
6  * @section LICENSE
7  *
8  * Copyright (c) 2008-2013 OpenShot Studios, LLC, Fabrice Bellard
9  * (http://www.openshotstudios.com). This file is part of
10  * OpenShot Library (http://www.openshot.org), an open-source project
11  * dedicated to delivering high quality video editing and animation solutions
12  * to the world.
13  *
14  * This file is originally based on the Libavformat API example, and then modified
15  * by the libopenshot project.
16  *
17  * OpenShot Library (libopenshot) is free software: you can redistribute it
18  * and/or modify it under the terms of the GNU Lesser General Public License
19  * as published by the Free Software Foundation, either version 3 of the
20  * License, or (at your option) any later version.
21  *
22  * OpenShot Library (libopenshot) is distributed in the hope that it will be
23  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25  * GNU Lesser General Public License for more details.
26  *
27  * You should have received a copy of the GNU Lesser General Public License
28  * along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
29  */
30 
31 #ifndef OPENSHOT_FFMPEG_READER_H
32 #define OPENSHOT_FFMPEG_READER_H
33 
34 #include "ReaderBase.h"
35 
36 // Include FFmpeg headers and macros
37 #include "FFmpegUtilities.h"
38 
39 #include <cmath>
40 #include <ctime>
41 #include <iostream>
42 #include <stdio.h>
43 #include <memory>
44 #include "CacheMemory.h"
45 #include "Exceptions.h"
46 #include "OpenMPUtilities.h"
47 
48 
49 using namespace std;
50 
51 namespace openshot
52 {
53  /**
54  * @brief This struct holds the associated video frame and starting sample # for an audio packet.
55  *
56  * Because audio packets do not match up with video frames, this helps determine exactly
57  * where the audio packet's samples belong.
58  */
60  {
61  int64_t frame;
63  bool is_near(AudioLocation location, int samples_per_frame, int64_t amount);
64  };
65 
66  /**
67  * @brief This class uses the FFmpeg libraries, to open video files and audio files, and return
68  * openshot::Frame objects for any frame in the file.
69  *
70  * All seeking and caching is handled internally, and the primary public interface is the GetFrame()
71  * method. To use this reader, simply create an instance of this class, and call the GetFrame method
72  * to start retrieving frames. Use the <b>info</b> struct to obtain information on the file, such as the length
73  * (# of frames), height, width, bit rate, frames per second (fps), etc...
74  *
75  * @code
76  * // Create a reader for a video
77  * FFmpegReader r("MyAwesomeVideo.webm");
78  * r.Open(); // Open the reader
79  *
80  * // Get frame number 1 from the video
81  * std::shared_ptr<Frame> f = r.GetFrame(1);
82  *
83  * // Now that we have an openshot::Frame object, lets have some fun!
84  * f->Display(); // Display the frame on the screen
85  * f->DisplayWaveform(); // Display the audio waveform as an image
86  * f->Play(); // Play the audio through your speaker
87  *
88  * // Close the reader
89  * r.Close();
90  * @endcode
91  */
92  class FFmpegReader : public ReaderBase
93  {
94  private:
95  string path;
96 
97  AVFormatContext *pFormatCtx;
98  int i, videoStream, audioStream;
99  AVCodecContext *pCodecCtx, *aCodecCtx;
100  AVStream *pStream, *aStream;
101  AVPacket *packet;
102  AVFrame *pFrame;
103  bool is_open;
104  bool is_duration_known;
105  bool check_interlace;
106  bool check_fps;
107  bool has_missing_frames;
108  bool use_omp_threads;
109 
110  CacheMemory working_cache;
111  CacheMemory missing_frames;
112  map<int64_t, int64_t> processing_video_frames;
113  multimap<int64_t, int64_t> processing_audio_frames;
114  map<int64_t, int64_t> processed_video_frames;
115  map<int64_t, int64_t> processed_audio_frames;
116  multimap<int64_t, int64_t> missing_video_frames;
117  multimap<int64_t, int64_t> missing_video_frames_source;
118  multimap<int64_t, int64_t> missing_audio_frames;
119  multimap<int64_t, int64_t> missing_audio_frames_source;
120  map<int64_t, int> checked_frames;
121  AudioLocation previous_packet_location;
122 
123  // DEBUG VARIABLES (FOR AUDIO ISSUES)
124  int prev_samples;
125  int64_t prev_pts;
126  int64_t pts_total;
127  int64_t pts_counter;
128  int64_t num_packets_since_video_frame;
129  int64_t num_checks_since_final;
130  std::shared_ptr<Frame> last_video_frame;
131 
132  bool is_seeking;
133  int64_t seeking_pts;
134  int64_t seeking_frame;
135  bool is_video_seek;
136  int seek_count;
137  int64_t seek_audio_frame_found;
138  int64_t seek_video_frame_found;
139 
140  int64_t audio_pts_offset;
141  int64_t video_pts_offset;
142  int64_t last_frame;
143  int64_t largest_frame_processed;
144  int64_t current_video_frame; // can't reliably use PTS of video to determine this
145 
146  /// Check for the correct frames per second value by scanning the 1st few seconds of video packets.
147  void CheckFPS();
148 
149  /// Check the current seek position and determine if we need to seek again
150  bool CheckSeek(bool is_video);
151 
152  /// Check if a frame is missing and attempt to replace it's frame image (and
153  bool CheckMissingFrame(int64_t requested_frame);
154 
155  /// Check the working queue, and move finished frames to the finished queue
156  void CheckWorkingFrames(bool end_of_stream, int64_t requested_frame);
157 
158  /// Convert Frame Number into Audio PTS
159  int64_t ConvertFrameToAudioPTS(int64_t frame_number);
160 
161  /// Convert Frame Number into Video PTS
162  int64_t ConvertFrameToVideoPTS(int64_t frame_number);
163 
164  /// Convert Video PTS into Frame Number
165  int64_t ConvertVideoPTStoFrame(int64_t pts);
166 
167  /// Create a new Frame (or return an existing one) and add it to the working queue.
168  std::shared_ptr<Frame> CreateFrame(int64_t requested_frame);
169 
170  /// Calculate Starting video frame and sample # for an audio PTS
171  AudioLocation GetAudioPTSLocation(int64_t pts);
172 
173  /// Get an AVFrame (if any)
174  bool GetAVFrame();
175 
176  /// Get the next packet (if any)
177  int GetNextPacket();
178 
179  /// Get the smallest video frame that is still being processed
180  int64_t GetSmallestVideoFrame();
181 
182  /// Get the smallest audio frame that is still being processed
183  int64_t GetSmallestAudioFrame();
184 
185  /// Get the PTS for the current video packet
186  int64_t GetVideoPTS();
187 
188  /// Remove partial frames due to seek
189  bool IsPartialFrame(int64_t requested_frame);
190 
191  /// Process a video packet
192  void ProcessVideoPacket(int64_t requested_frame);
193 
194  /// Process an audio packet
195  void ProcessAudioPacket(int64_t requested_frame, int64_t target_frame, int starting_sample);
196 
197  /// Read the stream until we find the requested Frame
198  std::shared_ptr<Frame> ReadStream(int64_t requested_frame);
199 
200  /// Remove AVFrame from cache (and deallocate it's memory)
201  void RemoveAVFrame(AVFrame*);
202 
203  /// Remove AVPacket from cache (and deallocate it's memory)
204  void RemoveAVPacket(AVPacket*);
205 
206  /// Seek to a specific Frame. This is not always frame accurate, it's more of an estimation on many codecs.
207  void Seek(int64_t requested_frame);
208 
209  /// Update PTS Offset (if any)
210  void UpdatePTSOffset(bool is_video);
211 
212  /// Update File Info for audio streams
213  void UpdateAudioInfo();
214 
215  /// Update File Info for video streams
216  void UpdateVideoInfo();
217 
218  public:
219  /// Final cache object used to hold final frames
221 
222  /// Enable or disable seeking. Seeking can more quickly locate the requested frame, but some
223  /// codecs have trouble seeking, and can introduce artifacts or blank images into the video.
225 
226  /// Constructor for FFmpegReader. This automatically opens the media file and loads
227  /// frame 1, or it throws one of the following exceptions.
228  FFmpegReader(string path);
229 
230  /// Constructor for FFmpegReader. This only opens the media file to inspect it's properties
231  /// if inspect_reader=true. When not inspecting the media file, it's much faster, and useful
232  /// when you are inflating the object using JSON after instantiating it.
233  FFmpegReader(string path, bool inspect_reader);
234 
235  /// Destructor
236  ~FFmpegReader();
237 
238  /// Close File
239  void Close();
240 
241  /// Get the cache object used by this reader
242  CacheMemory* GetCache() { return &final_cache; };
243 
244  /// Get a shared pointer to a openshot::Frame object for a specific frame number of this reader.
245  ///
246  /// @returns The requested frame of video
247  /// @param requested_frame The frame number that is requested.
248  std::shared_ptr<Frame> GetFrame(int64_t requested_frame);
249 
250  /// Determine if reader is open or closed
251  bool IsOpen() { return is_open; };
252 
253  /// Return the type name of the class
254  string Name() { return "FFmpegReader"; };
255 
256  /// Get and Set JSON methods
257  string Json(); ///< Generate JSON string of this object
258  void SetJson(string value); ///< Load JSON string into this object
259  Json::Value JsonValue(); ///< Generate Json::JsonValue for this object
260  void SetJsonValue(Json::Value root); ///< Load Json::JsonValue into this object
261 
262  /// Open File - which is called by the constructor automatically
263  void Open();
264  };
265 
266 }
267 
268 #endif
Header file for ReaderBase class.
Header file for OpenMPUtilities (set some common macros)
CacheMemory * GetCache()
Get the cache object used by this reader.
Definition: FFmpegReader.h:242
This abstract class is the base class, used by all readers in libopenshot.
Definition: ReaderBase.h:96
Header file for CacheMemory class.
bool IsOpen()
Determine if reader is open or closed.
Definition: FFmpegReader.h:251
Header file for all Exception classes.
This class uses the FFmpeg libraries, to open video files and audio files, and return openshot::Frame...
Definition: FFmpegReader.h:92
This struct holds the associated video frame and starting sample # for an audio packet.
Definition: FFmpegReader.h:59
CacheMemory final_cache
Final cache object used to hold final frames.
Definition: FFmpegReader.h:220
string Name()
Return the type name of the class.
Definition: FFmpegReader.h:254
Header file for FFmpegUtilities.
This class is a memory-based cache manager for Frame objects.
Definition: CacheMemory.h:48