OpenShot Library | libopenshot  0.1.1
FFmpegWriter.h
Go to the documentation of this file.
1 /**
2  * @file
3  * @brief Header file for FFmpegWriter 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 is free software: you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation, either version 3 of the License, or
20  * (at your option) any later version.
21  * * OpenShot Library (libopenshot) is free software: you can redistribute it
22  * and/or modify it under the terms of the GNU Lesser General Public License
23  * as published by the Free Software Foundation, either version 3 of the
24  * License, or (at your option) any later version.
25  *
26  * OpenShot Library (libopenshot) is distributed in the hope that it will be
27  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29  * GNU Lesser General Public License for more details.
30  *
31  * You should have received a copy of the GNU Lesser General Public License
32  * along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
33  */
34 
35 
36 #ifndef OPENSHOT_FFMPEG_WRITER_H
37 #define OPENSHOT_FFMPEG_WRITER_H
38 
39 #include "ReaderBase.h"
40 #include "WriterBase.h"
41 
42 // Include FFmpeg headers and macros
43 #include "FFmpegUtilities.h"
44 
45 #include <cmath>
46 #include <ctime>
47 #include <iostream>
48 #include <stdio.h>
49 #include <unistd.h>
50 #include "Cache.h"
51 #include "Exceptions.h"
52 #include "OpenMPUtilities.h"
53 
54 
55 using namespace std;
56 
57 namespace openshot
58 {
59 
60  /// This enumeration designates the type of stream when encoding (video or audio)
62  {
63  VIDEO_STREAM, ///< A video stream (used to determine which type of stream)
64  AUDIO_STREAM ///< An audio stream (used to determine which type of stream)
65  };
66 
67  /**
68  * @brief This class uses the FFmpeg libraries, to write and encode video files and audio files.
69  *
70  * All FFmpeg options can be set using the SetOption() method, and any Reader may be used
71  * to generate openshot::Frame objects needed for writing. Be sure to use valid bit rates, frame
72  * rates, and sample rates (each format / codec has a limited # of valid options).
73  *
74  * @code SIMPLE EXAMPLE
75  *
76  * // Create a reader for a video
77  * FFmpegReader r("MyAwesomeVideo.webm");
78  * r.Open(); // Open thetarget_ reader
79  *
80  * // Create a writer (which will create a WebM video)
81  * FFmpegWriter w("/home/jonathan/NewVideo.webm");
82  *
83  * // Set options
84  * w.SetAudioOptions(true, "libvorbis", 44100, 2, 128000); // Sample Rate: 44100, Channels: 2, Bitrate: 128000
85  * w.SetVideoOptions(true, "libvpx", openshot::Fraction(24,1), 720, 480, openshot::Fraction(1,1), false, false, 300000); // FPS: 24, Size: 720x480, Pixel Ratio: 1/1, Bitrate: 300000
86  *
87  * // Open the writer
88  * w.Open();
89  *
90  * // Write all frames from the reader
91  * w.WriteFrame(&r, 1, r.info.video_length);
92  *
93  * // Close the reader & writer
94  * w.Close();
95  * r.Close();
96  * @endcode
97  *
98  * Here is a more advanced example, which sets some additional (and optional) encoding
99  * options.
100  *
101  * @code ADVANCED WRITER EXAMPLE
102  *
103  * // Create a reader for a video
104  * FFmpegReader r("MyAwesomeVideo.webm");
105  * r.Open(); // Open the reader
106  *
107  * // Create a writer (which will create a WebM video)
108  * FFmpegWriter w("/home/jonathan/NewVideo.webm");
109  *
110  * // Set options
111  * w.SetAudioOptions(true, "libvorbis", 44100, 2, 128000); // Sample Rate: 44100, Channels: 2, Bitrate: 128000
112  * w.SetVideoOptions(true, "libvpx", openshot::Fraction(24,1), 720, 480, openshot::Fraction(1,1), false, false, 300000); // FPS: 24, Size: 720x480, Pixel Ratio: 1/1, Bitrate: 300000
113  *
114  * // Prepare Streams (Optional method that must be called before any SetOption calls)
115  * w.PrepareStreams();
116  *
117  * // Set some specific encoding options (Optional methods)
118  * w.SetOption(VIDEO_STREAM, "qmin", "2" );
119  * w.SetOption(VIDEO_STREAM, "qmax", "30" );
120  * w.SetOption(VIDEO_STREAM, "crf", "10" );
121  * w.SetOption(VIDEO_STREAM, "rc_min_rate", "2000000" );
122  * w.SetOption(VIDEO_STREAM, "rc_max_rate", "4000000" );
123  * w.SetOption(VIDEO_STREAM, "max_b_frames", "10" );
124  *
125  * // Write the header of the video file
126  * w.WriteHeader();
127  *
128  * // Open the writer
129  * w.Open();
130  *
131  * // Write all frames from the reader
132  * w.WriteFrame(&r, 1, r.info.video_length);
133  *
134  * // Write the trailer of the video file
135  * w.WriteTrailer();
136  *
137  * // Close the reader & writer
138  * w.Close();
139  * r.Close();
140  * @endcode
141  */
142  class FFmpegWriter : public WriterBase
143  {
144  private:
145  string path;
146  int cache_size;
147  bool is_writing;
148  bool is_open;
149  int64 write_video_count;
150  int64 write_audio_count;
151 
152  bool prepare_streams;
153  bool write_header;
154  bool write_trailer;
155 
156  AVOutputFormat *fmt;
157  AVFormatContext *oc;
158  AVStream *audio_st, *video_st;
159  AVCodecContext *video_codec;
160  AVCodecContext *audio_codec;
161  SwsContext *img_convert_ctx;
162  double audio_pts, video_pts;
163  int16_t *samples;
164  uint8_t *audio_outbuf;
165  uint8_t *audio_encoder_buffer;
166 
167  int num_of_rescalers;
168  int rescaler_position;
169  vector<SwsContext*> image_rescalers;
170 
171  int audio_outbuf_size;
172  int audio_input_frame_size;
173  int initial_audio_input_frame_size;
174  int audio_input_position;
175  int audio_encoder_buffer_size;
176  AVAudioResampleContext *avr;
177  AVAudioResampleContext *avr_planar;
178 
179  /* Resample options */
180  int original_sample_rate;
181  int original_channels;
182 
183  tr1::shared_ptr<Frame> last_frame;
184  deque<tr1::shared_ptr<Frame> > spooled_audio_frames;
185  deque<tr1::shared_ptr<Frame> > spooled_video_frames;
186 
187  deque<tr1::shared_ptr<Frame> > queued_audio_frames;
188  deque<tr1::shared_ptr<Frame> > queued_video_frames;
189 
190  deque<tr1::shared_ptr<Frame> > processed_frames;
191  deque<tr1::shared_ptr<Frame> > deallocate_frames;
192 
193  map<tr1::shared_ptr<Frame>, AVFrame*> av_frames;
194 
195  /// Add an AVFrame to the cache
196  void add_avframe(tr1::shared_ptr<Frame> frame, AVFrame* av_frame);
197 
198  /// Add an audio output stream
199  AVStream* add_audio_stream();
200 
201  /// Add a video output stream
202  AVStream* add_video_stream();
203 
204  /// Allocate an AVFrame object
205  AVFrame* allocate_avframe(PixelFormat pix_fmt, int width, int height, int *buffer_size, uint8_t *new_buffer);
206 
207  /// Auto detect format (from path)
208  void auto_detect_format();
209 
210  /// Close the audio codec
211  void close_audio(AVFormatContext *oc, AVStream *st);
212 
213  /// Close the video codec
214  void close_video(AVFormatContext *oc, AVStream *st);
215 
216  /// Flush encoders
217  void flush_encoders();
218 
219  /// initialize streams
220  void initialize_streams();
221 
222  /// @brief Init a collection of software rescalers (thread safe)
223  /// @param source_width The source width of the image scalers (used to cache a bunch of scalers)
224  /// @param source_height The source height of the image scalers (used to cache a bunch of scalers)
225  void InitScalers(int source_width, int source_height);
226 
227  /// open audio codec
228  void open_audio(AVFormatContext *oc, AVStream *st);
229 
230  /// open video codec
231  void open_video(AVFormatContext *oc, AVStream *st);
232 
233  /// process video frame
234  void process_video_packet(tr1::shared_ptr<Frame> frame);
235 
236  /// write all queued frames' audio to the video file
237  void write_audio_packets(bool final);
238 
239  /// write video frame
240  bool write_video_packet(tr1::shared_ptr<Frame> frame, AVFrame* frame_final);
241 
242  /// write all queued frames
243  void write_queued_frames() throw (ErrorEncodingVideo);
244 
245  public:
246 
247  /// @brief Constructor for FFmpegWriter. Throws one of the following exceptions.
248  /// @param path The file path of the video file you want to open and read
250 
251  /// Close the writer
252  void Close();
253 
254  /// Get the cache size (number of frames to queue before writing)
255  int GetCacheSize() { return cache_size; };
256 
257  /// Determine if writer is open or closed
258  bool IsOpen() { return is_open; };
259 
260  /// Open writer
262 
263  /// Output the ffmpeg info about this format, streams, and codecs (i.e. dump format)
264  void OutputStreamInfo();
265 
266  /// @brief Prepare & initialize streams and open codecs. This method is called automatically
267  /// by the Open() method if this method has not yet been called.
268  void PrepareStreams();
269 
270  /// Remove & deallocate all software scalers
271  void RemoveScalers();
272 
273  /// @brief Set audio resample options
274  /// @param sample_rate The number of samples per second of the audio
275  /// @param channels The number of audio channels
276  void ResampleAudio(int sample_rate, int channels);
277 
278  /// @brief Set audio export options
279  /// @param has_audio Does this file need an audio stream?
280  /// @param codec The codec used to encode the audio for this file
281  /// @param sample_rate The number of audio samples needed in this file
282  /// @param channels The number of audio channels needed in this file
283  /// @param channel_layout The 'layout' of audio channels (i.e. mono, stereo, surround, etc...)
284  /// @param bit_rate The audio bit rate used during encoding
285  void SetAudioOptions(bool has_audio, string codec, int sample_rate, int channels, ChannelLayout channel_layout, int bit_rate)
286  throw(InvalidFile, InvalidFormat, InvalidCodec, InvalidOptions, OutOfMemory, InvalidChannels);
287 
288  /// @brief Set the cache size
289  /// @param new_size The number of frames to queue before writing to the file
290  void SetCacheSize(int new_size) { cache_size = new_size; };
291 
292  /// @brief Set video export options
293  /// @param has_video Does this file need a video stream
294  /// @param codec The codec used to encode the images in this video
295  /// @param fps The number of frames per second
296  /// @param width The width in pixels of this video
297  /// @param height The height in pixels of this video
298  /// @param pixel_ratio The shape of the pixels represented as a openshot::Fraction (1x1 is most common / square pixels)
299  /// @param interlaced Does this video need to be interlaced?
300  /// @param top_field_first Which frame should be used as the top field?
301  /// @param bit_rate The video bit rate used during encoding
302  void SetVideoOptions(bool has_video, string codec, Fraction fps, int width, int height,Fraction pixel_ratio, bool interlaced, bool top_field_first, int bit_rate)
304 
305  /// @brief Set custom options (some codecs accept additional params). This must be called after the
306  /// PrepareStreams() method, otherwise the streams have not been initialized yet.
307  /// @param stream The stream (openshot::StreamType) this option should apply to
308  /// @param name The name of the option you want to set (i.e. qmin, qmax, etc...)
309  /// @param value The new value of this option
310  void SetOption(StreamType stream, string name, string value) throw(NoStreamsFound, InvalidOptions);
311 
312  /// @brief Write the file header (after the options are set). This method is called automatically
313  /// by the Open() method if this method has not yet been called.
314  void WriteHeader();
315 
316  /// @brief Add a frame to the stack waiting to be encoded.
317  /// @param frame The openshot::Frame object to write to this image
318  void WriteFrame(tr1::shared_ptr<Frame> frame) throw(ErrorEncodingVideo, WriterClosed);
319 
320  /// @brief Write a block of frames from a reader
321  /// @param reader A openshot::ReaderBase object which will provide frames to be written
322  /// @param start The starting frame number of the reader
323  /// @param length The number of frames to write
324  void WriteFrame(ReaderBase* reader, long int start, long int length) throw(ErrorEncodingVideo, WriterClosed);
325 
326  /// @brief Write the file trailer (after all frames are written). This is called automatically
327  /// by the Close() method if this method has not yet been called.
328  void WriteTrailer();
329 
330  };
331 
332 }
333 
334 #endif
A video stream (used to determine which type of stream)
Definition: FFmpegWriter.h:63
int GetCacheSize()
Get the cache size (number of frames to queue before writing)
Definition: FFmpegWriter.h:255
An audio stream (used to determine which type of stream)
Definition: FFmpegWriter.h:64
Header file for ReaderBase class.
Exception when an invalid # of audio channels are detected.
Definition: Exceptions.h:112
Header file for OpenMPUtilities (set some common macros)
This class uses the FFmpeg libraries, to write and encode video files and audio files.
Definition: FFmpegWriter.h:142
This abstract class is the base class, used by all readers in libopenshot.
Definition: ReaderBase.h:95
bool IsOpen()
Determine if writer is open or closed.
Definition: FFmpegWriter.h:258
Exception when encoding audio packet.
Definition: Exceptions.h:101
Exception when invalid sample rate is detected during encoding.
Definition: Exceptions.h:172
Header file for all Exception classes.
Exception when no valid codec is found for a file.
Definition: Exceptions.h:122
Exception when memory could not be allocated.
Definition: Exceptions.h:224
Exception when invalid encoding options are used.
Definition: Exceptions.h:162
Exception when no streams are found in the file.
Definition: Exceptions.h:192
Exception for files that can not be found or opened.
Definition: Exceptions.h:132
Header file for WriterBase class.
This abstract class is the base class, used by writers. Writers are types of classes that encode vide...
Definition: WriterBase.h:85
Header file for Cache class.
This class represents a fraction.
Definition: Fraction.h:42
ChannelLayout
This enumeration determines the audio channel layout (such as stereo, mono, 5 point surround...
#define PixelFormat
Exception when a writer is closed, and a frame is requested.
Definition: Exceptions.h:264
Header file for FFmpegUtilities.
Exception when no valid format is found for a file.
Definition: Exceptions.h:142
StreamType
This enumeration designates the type of stream when encoding (video or audio)
Definition: FFmpegWriter.h:61