d082a8ef7143b58c12b5b8ca381d2adf13a7e8d0
[dcpomatic.git] / src / lib / ffmpeg_image_proxy.cc
1 /*
2     Copyright (C) 2014-2018 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "ffmpeg_image_proxy.h"
22 #include "cross.h"
23 #include "exceptions.h"
24 #include "dcpomatic_socket.h"
25 #include "image.h"
26 #include "compose.hpp"
27 #include "util.h"
28 #include "warnings.h"
29 #include <dcp/raw_convert.h>
30 extern "C" {
31 #include <libavcodec/avcodec.h>
32 #include <libavformat/avformat.h>
33 #include <libavutil/pixdesc.h>
34 }
35 DCPOMATIC_DISABLE_WARNINGS
36 #include <libxml++/libxml++.h>
37 DCPOMATIC_ENABLE_WARNINGS
38 #include <iostream>
39
40 #include "i18n.h"
41
42 using std::string;
43 using std::cout;
44 using std::pair;
45 using std::min;
46 using std::make_pair;
47 using std::shared_ptr;
48 using boost::optional;
49 using std::dynamic_pointer_cast;
50 using dcp::raw_convert;
51
52 FFmpegImageProxy::FFmpegImageProxy (boost::filesystem::path path, VideoRange video_range)
53         : _data (path)
54         , _video_range (video_range)
55         , _pos (0)
56         , _path (path)
57 {
58
59 }
60
61 FFmpegImageProxy::FFmpegImageProxy (dcp::ArrayData data, VideoRange video_range)
62         : _data (data)
63         , _video_range (video_range)
64         , _pos (0)
65 {
66
67 }
68
69 FFmpegImageProxy::FFmpegImageProxy (shared_ptr<cxml::Node> node, shared_ptr<Socket> socket)
70         : _video_range (string_to_video_range(node->string_child("VideoRange")))
71         , _pos (0)
72 {
73         uint32_t const size = socket->read_uint32 ();
74         _data = dcp::ArrayData (size);
75         socket->read (_data.data(), size);
76 }
77
78 static int
79 avio_read_wrapper (void* data, uint8_t* buffer, int amount)
80 {
81         return reinterpret_cast<FFmpegImageProxy*>(data)->avio_read (buffer, amount);
82 }
83
84 static int64_t
85 avio_seek_wrapper (void* data, int64_t offset, int whence)
86 {
87         return reinterpret_cast<FFmpegImageProxy*>(data)->avio_seek (offset, whence);
88 }
89
90 int
91 FFmpegImageProxy::avio_read (uint8_t* buffer, int const amount)
92 {
93         int const to_do = min(static_cast<int64_t>(amount), static_cast<int64_t>(_data.size()) - _pos);
94         if (to_do == 0) {
95                 return AVERROR_EOF;
96         }
97         memcpy (buffer, _data.data() + _pos, to_do);
98         _pos += to_do;
99         return to_do;
100 }
101
102 int64_t
103 FFmpegImageProxy::avio_seek (int64_t const pos, int whence)
104 {
105         switch (whence) {
106         case AVSEEK_SIZE:
107                 return _data.size();
108         case SEEK_CUR:
109                 _pos += pos;
110                 break;
111         case SEEK_SET:
112                 _pos = pos;
113                 break;
114         case SEEK_END:
115                 _pos = _data.size() - pos;
116                 break;
117         }
118
119         return _pos;
120 }
121
122 DCPOMATIC_DISABLE_WARNINGS
123
124 ImageProxy::Result
125 FFmpegImageProxy::image (optional<dcp::Size>) const
126 {
127         boost::mutex::scoped_lock lm (_mutex);
128
129         if (_image) {
130                 return Result (_image, 0);
131         }
132
133         uint8_t* avio_buffer = static_cast<uint8_t*> (wrapped_av_malloc(4096));
134         AVIOContext* avio_context = avio_alloc_context (avio_buffer, 4096, 0, const_cast<FFmpegImageProxy*>(this), avio_read_wrapper, 0, avio_seek_wrapper);
135         AVFormatContext* format_context = avformat_alloc_context ();
136         format_context->pb = avio_context;
137
138         AVDictionary* options = 0;
139         /* These durations are in microseconds, and represent how far into the content file
140            we will look for streams.
141         */
142         av_dict_set (&options, "analyzeduration", raw_convert<string>(5 * 60 * 1000000).c_str(), 0);
143         av_dict_set (&options, "probesize", raw_convert<string>(5 * 60 * 1000000).c_str(), 0);
144
145         int e = avformat_open_input (&format_context, 0, 0, &options);
146         if ((e < 0 && e == AVERROR_INVALIDDATA) || (e >= 0 && format_context->probe_score <= 25)) {
147                 /* Hack to fix loading of .tga files through AVIOContexts (rather then
148                    directly from the file).  This code just does enough to allow the
149                    probe code to take a hint from "foo.tga" and so try targa format.
150                 */
151                 AVInputFormat* f = av_find_input_format ("image2");
152                 format_context = avformat_alloc_context ();
153                 format_context->pb = avio_context;
154                 format_context->iformat = f;
155                 e = avformat_open_input (&format_context, "foo.tga", f, &options);
156         }
157         if (e < 0) {
158                 if (_path) {
159                         throw OpenFileError (_path->string(), e, OpenFileError::READ);
160                 } else {
161                         boost::throw_exception(DecodeError(String::compose(_("Could not decode image (%1)"), e)));
162                 }
163         }
164
165         if (avformat_find_stream_info(format_context, 0) < 0) {
166                 throw DecodeError (_("could not find stream information"));
167         }
168
169         DCPOMATIC_ASSERT (format_context->nb_streams == 1);
170
171         AVFrame* frame = av_frame_alloc ();
172         if (!frame) {
173                 throw DecodeError (N_("could not allocate frame"));
174         }
175
176         AVCodecContext* codec_context = format_context->streams[0]->codec;
177         AVCodec* codec = avcodec_find_decoder (codec_context->codec_id);
178         DCPOMATIC_ASSERT (codec);
179
180         if (avcodec_open2 (codec_context, codec, 0) < 0) {
181                 throw DecodeError (N_("could not open decoder"));
182         }
183
184         AVPacket packet;
185         int r = av_read_frame (format_context, &packet);
186         if (r < 0) {
187                 throw DecodeError (N_("could not read frame"));
188         }
189
190         int frame_finished;
191         if (avcodec_decode_video2(codec_context, frame, &frame_finished, &packet) < 0 || !frame_finished) {
192                 throw DecodeError (N_("could not decode video"));
193         }
194
195         AVPixelFormat const pix_fmt = static_cast<AVPixelFormat>(frame->format);
196
197         _image.reset (new Image(frame));
198         if (_video_range == VideoRange::VIDEO && av_pix_fmt_desc_get(pix_fmt)->flags & AV_PIX_FMT_FLAG_RGB) {
199                 /* Asking for the video range to be converted by libswscale (in Image) will not work for
200                  * RGB sources since that method only processes video range in YUV and greyscale.  So we have
201                  * to do it ourselves here.
202                  */
203                 _image->video_range_to_full_range();
204         }
205
206         av_packet_unref (&packet);
207         av_frame_free (&frame);
208         avcodec_close (codec_context);
209         avformat_close_input (&format_context);
210         av_free (avio_context->buffer);
211         av_free (avio_context);
212
213         return Result (_image, 0);
214 }
215
216 DCPOMATIC_ENABLE_WARNINGS
217
218 void
219 FFmpegImageProxy::add_metadata (xmlpp::Node* node) const
220 {
221         node->add_child("Type")->add_child_text (N_("FFmpeg"));
222         node->add_child("VideoRange")->add_child_text(video_range_to_string(_video_range));
223 }
224
225 void
226 FFmpegImageProxy::write_to_socket (shared_ptr<Socket> socket) const
227 {
228         socket->write (_data.size());
229         socket->write (_data.data(), _data.size());
230 }
231
232 bool
233 FFmpegImageProxy::same (shared_ptr<const ImageProxy> other) const
234 {
235         shared_ptr<const FFmpegImageProxy> mp = dynamic_pointer_cast<const FFmpegImageProxy> (other);
236         if (!mp) {
237                 return false;
238         }
239
240         return _data == mp->_data;
241 }
242
243 size_t
244 FFmpegImageProxy::memory_used () const
245 {
246         size_t m = _data.size();
247         if (_image) {
248                 m += _image->memory_used();
249         }
250         return m;
251 }