OpenShot Library | libopenshot  0.1.9
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  AVPicture *pFrame;
103  bool is_open;
104  bool is_duration_known;
105  bool check_interlace;
106  bool check_fps;
107  bool has_missing_frames;
108 
109  CacheMemory working_cache;
110  CacheMemory missing_frames;
111  map<int64_t, int64_t> processing_video_frames;
112  multimap<int64_t, int64_t> processing_audio_frames;
113  map<int64_t, int64_t> processed_video_frames;
114  map<int64_t, int64_t> processed_audio_frames;
115  multimap<int64_t, int64_t> missing_video_frames;
116  multimap<int64_t, int64_t> missing_video_frames_source;
117  multimap<int64_t, int64_t> missing_audio_frames;
118  multimap<int64_t, int64_t> missing_audio_frames_source;
119  map<int64_t, int> checked_frames;
120  AudioLocation previous_packet_location;
121 
122  // DEBUG VARIABLES (FOR AUDIO ISSUES)
123  int prev_samples;
124  int64_t prev_pts;
125  int64_t pts_total;
126  int64_t pts_counter;
127  int64_t num_packets_since_video_frame;
128  int64_t num_checks_since_final;
129  std::shared_ptr<Frame> last_video_frame;
130 
131  bool is_seeking;
132  int64_t seeking_pts;
133  int64_t seeking_frame;
134  bool is_video_seek;
135  int seek_count;
136  int64_t seek_audio_frame_found;
137  int64_t seek_video_frame_found;
138 
139  int64_t audio_pts_offset;
140  int64_t video_pts_offset;
141  int64_t last_frame;
142  int64_t largest_frame_processed;
143  int64_t current_video_frame; // can't reliably use PTS of video to determine this
144 
145  /// Check for the correct frames per second value by scanning the 1st few seconds of video packets.
146  void CheckFPS();
147 
148  /// Check the current seek position and determine if we need to seek again
149  bool CheckSeek(bool is_video);
150 
151  /// Check if a frame is missing and attempt to replace it's frame image (and
152  bool CheckMissingFrame(int64_t requested_frame);
153 
154  /// Check the working queue, and move finished frames to the finished queue
155  void CheckWorkingFrames(bool end_of_stream, int64_t requested_frame);
156 
157  /// Convert image to RGB format
158  void convert_image(int64_t current_frame, AVPicture *copyFrame, int width, int height, PixelFormat pix_fmt);
159 
160  /// Convert Frame Number into Audio PTS
161  int64_t ConvertFrameToAudioPTS(int64_t frame_number);
162 
163  /// Convert Frame Number into Video PTS
164  int64_t ConvertFrameToVideoPTS(int64_t frame_number);
165 
166  /// Convert Video PTS into Frame Number
167  int64_t ConvertVideoPTStoFrame(int64_t pts);
168 
169  /// Create a new Frame (or return an existing one) and add it to the working queue.
170  std::shared_ptr<Frame> CreateFrame(int64_t requested_frame);
171 
172  /// Calculate Starting video frame and sample # for an audio PTS
173  AudioLocation GetAudioPTSLocation(int64_t pts);
174 
175  /// Get an AVFrame (if any)
176  bool GetAVFrame();
177 
178  /// Get the next packet (if any)
179  int GetNextPacket();
180 
181  /// Get the smallest video frame that is still being processed
182  int64_t GetSmallestVideoFrame();
183 
184  /// Get the smallest audio frame that is still being processed
185  int64_t GetSmallestAudioFrame();
186 
187  /// Get the PTS for the current video packet
188  int64_t GetVideoPTS();
189 
190  /// Remove partial frames due to seek
191  bool IsPartialFrame(int64_t requested_frame);
192 
193  /// Process a video packet
194  void ProcessVideoPacket(int64_t requested_frame);
195 
196  /// Process an audio packet
197  void ProcessAudioPacket(int64_t requested_frame, int64_t target_frame, int starting_sample);
198 
199  /// Read the stream until we find the requested Frame
200  std::shared_ptr<Frame> ReadStream(int64_t requested_frame);
201 
202  /// Remove AVFrame from cache (and deallocate it's memory)
203  void RemoveAVFrame(AVPicture*);
204 
205  /// Remove AVPacket from cache (and deallocate it's memory)
206  void RemoveAVPacket(AVPacket*);
207 
208  /// Seek to a specific Frame. This is not always frame accurate, it's more of an estimation on many codecs.
209  void Seek(int64_t requested_frame);
210 
211  /// Update PTS Offset (if any)
212  void UpdatePTSOffset(bool is_video);
213 
214  /// Update File Info for audio streams
215  void UpdateAudioInfo();
216 
217  /// Update File Info for video streams
218  void UpdateVideoInfo();
219 
220  public:
221  /// Final cache object used to hold final frames
223 
224  /// Enable or disable seeking. Seeking can more quickly locate the requested frame, but some
225  /// codecs have trouble seeking, and can introduce artifacts or blank images into the video.
227 
228  /// Constructor for FFmpegReader. This automatically opens the media file and loads
229  /// frame 1, or it throws one of the following exceptions.
230  FFmpegReader(string path);
231 
232  /// Constructor for FFmpegReader. This only opens the media file to inspect it's properties
233  /// if inspect_reader=true. When not inspecting the media file, it's much faster, and useful
234  /// when you are inflating the object using JSON after instantiating it.
235  FFmpegReader(string path, bool inspect_reader);
236 
237  /// Destructor
238  ~FFmpegReader();
239 
240  /// Close File
241  void Close();
242 
243  /// Get the cache object used by this reader
244  CacheMemory* GetCache() { return &final_cache; };
245 
246  /// Get a shared pointer to a openshot::Frame object for a specific frame number of this reader.
247  ///
248  /// @returns The requested frame of video
249  /// @param requested_frame The frame number that is requested.
250  std::shared_ptr<Frame> GetFrame(int64_t requested_frame);
251 
252  /// Determine if reader is open or closed
253  bool IsOpen() { return is_open; };
254 
255  /// Return the type name of the class
256  string Name() { return "FFmpegReader"; };
257 
258  /// Get and Set JSON methods
259  string Json(); ///< Generate JSON string of this object
260  void SetJson(string value); ///< Load JSON string into this object
261  Json::Value JsonValue(); ///< Generate Json::JsonValue for this object
262  void SetJsonValue(Json::Value root); ///< Load Json::JsonValue into this object
263 
264  /// Open File - which is called by the constructor automatically
265  void Open();
266  };
267 
268 }
269 
270 #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:244
This abstract class is the base class, used by all readers in libopenshot.
Definition: ReaderBase.h:95
Header file for CacheMemory class.
bool IsOpen()
Determine if reader is open or closed.
Definition: FFmpegReader.h:253
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
#define PixelFormat
This namespace is the default namespace for all code in the openshot library.
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:222
string Name()
Return the type name of the class.
Definition: FFmpegReader.h:256
Header file for FFmpegUtilities.
This class is a memory-based cache manager for Frame objects.
Definition: CacheMemory.h:48