Switch decoding to ffmpeg send/receive API.
[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
22 #include "compose.hpp"
23 #include "cross.h"
24 #include "dcpomatic_socket.h"
25 #include "exceptions.h"
26 #include "ffmpeg_image_proxy.h"
27 #include "image.h"
28 #include "util.h"
29 #include "warnings.h"
30 #include <dcp/raw_convert.h>
31 extern "C" {
32 #include <libavcodec/avcodec.h>
33 #include <libavformat/avformat.h>
34 #include <libavutil/pixdesc.h>
35 }
36 DCPOMATIC_DISABLE_WARNINGS
37 #include <libxml++/libxml++.h>
38 DCPOMATIC_ENABLE_WARNINGS
39 #include <iostream>
40
41 #include "i18n.h"
42
43
44 using std::cout;
45 using std::make_pair;
46 using std::make_shared;
47 using std::min;
48 using std::pair;
49 using std::shared_ptr;
50 using std::string;
51 using boost::optional;
52 using std::dynamic_pointer_cast;
53 using dcp::raw_convert;
54
55
56 FFmpegImageProxy::FFmpegImageProxy (boost::filesystem::path path, VideoRange video_range)
57         : _data (path)
58         , _video_range (video_range)
59         , _pos (0)
60         , _path (path)
61 {
62
63 }
64
65 FFmpegImageProxy::FFmpegImageProxy (dcp::ArrayData data, VideoRange video_range)
66         : _data (data)
67         , _video_range (video_range)
68         , _pos (0)
69 {
70
71 }
72
73 FFmpegImageProxy::FFmpegImageProxy (shared_ptr<cxml::Node> node, shared_ptr<Socket> socket)
74         : _video_range (string_to_video_range(node->string_child("VideoRange")))
75         , _pos (0)
76 {
77         uint32_t const size = socket->read_uint32 ();
78         _data = dcp::ArrayData (size);
79         socket->read (_data.data(), size);
80 }
81
82 static int
83 avio_read_wrapper (void* data, uint8_t* buffer, int amount)
84 {
85         return reinterpret_cast<FFmpegImageProxy*>(data)->avio_read (buffer, amount);
86 }
87
88 static int64_t
89 avio_seek_wrapper (void* data, int64_t offset, int whence)
90 {
91         return reinterpret_cast<FFmpegImageProxy*>(data)->avio_seek (offset, whence);
92 }
93
94 int
95 FFmpegImageProxy::avio_read (uint8_t* buffer, int const amount)
96 {
97         int const to_do = min(static_cast<int64_t>(amount), static_cast<int64_t>(_data.size()) - _pos);
98         if (to_do == 0) {
99                 return AVERROR_EOF;
100         }
101         memcpy (buffer, _data.data() + _pos, to_do);
102         _pos += to_do;
103         return to_do;
104 }
105
106 int64_t
107 FFmpegImageProxy::avio_seek (int64_t const pos, int whence)
108 {
109         switch (whence) {
110         case AVSEEK_SIZE:
111                 return _data.size();
112         case SEEK_CUR:
113                 _pos += pos;
114                 break;
115         case SEEK_SET:
116                 _pos = pos;
117                 break;
118         case SEEK_END:
119                 _pos = _data.size() - pos;
120                 break;
121         }
122
123         return _pos;
124 }
125
126
127 ImageProxy::Result
128 FFmpegImageProxy::image (optional<dcp::Size>) const
129 {
130         auto constexpr name_for_errors = "FFmpegImageProxy::image";
131
132         boost::mutex::scoped_lock lm (_mutex);
133
134         if (_image) {
135                 return Result (_image, 0);
136         }
137
138         uint8_t* avio_buffer = static_cast<uint8_t*> (wrapped_av_malloc(4096));
139         AVIOContext* avio_context = avio_alloc_context (avio_buffer, 4096, 0, const_cast<FFmpegImageProxy*>(this), avio_read_wrapper, 0, avio_seek_wrapper);
140         AVFormatContext* format_context = avformat_alloc_context ();
141         format_context->pb = avio_context;
142
143         AVDictionary* options = 0;
144         /* These durations are in microseconds, and represent how far into the content file
145            we will look for streams.
146         */
147         av_dict_set (&options, "analyzeduration", raw_convert<string>(5 * 60 * 1000000).c_str(), 0);
148         av_dict_set (&options, "probesize", raw_convert<string>(5 * 60 * 1000000).c_str(), 0);
149
150         int e = avformat_open_input (&format_context, 0, 0, &options);
151         if ((e < 0 && e == AVERROR_INVALIDDATA) || (e >= 0 && format_context->probe_score <= 25)) {
152                 /* Hack to fix loading of .tga files through AVIOContexts (rather then
153                    directly from the file).  This code just does enough to allow the
154                    probe code to take a hint from "foo.tga" and so try targa format.
155                 */
156                 AVInputFormat* f = av_find_input_format ("image2");
157                 format_context = avformat_alloc_context ();
158                 format_context->pb = avio_context;
159                 format_context->iformat = f;
160                 e = avformat_open_input (&format_context, "foo.tga", f, &options);
161         }
162         if (e < 0) {
163                 if (_path) {
164                         throw OpenFileError (_path->string(), e, OpenFileError::READ);
165                 } else {
166                         boost::throw_exception(DecodeError(String::compose(_("Could not decode image (%1)"), e)));
167                 }
168         }
169
170         int r = avformat_find_stream_info(format_context, 0);
171         if (r < 0) {
172                 throw DecodeError (N_("avcodec_find_stream_info"), name_for_errors, r);
173         }
174
175         DCPOMATIC_ASSERT (format_context->nb_streams == 1);
176
177         AVFrame* frame = av_frame_alloc ();
178         if (!frame) {
179                 std::bad_alloc ();
180         }
181
182         auto codec = avcodec_find_decoder (format_context->streams[0]->codecpar->codec_id);
183         DCPOMATIC_ASSERT (codec);
184
185         auto context = avcodec_alloc_context3 (codec);
186         if (!context) {
187                 throw DecodeError (N_("avcodec_alloc_context3"), name_for_errors);
188         }
189
190         r = avcodec_open2 (context, codec, 0);
191         if (r < 0) {
192                 throw DecodeError (N_("avcodec_open2"), name_for_errors, r);
193         }
194
195         AVPacket packet;
196         r = av_read_frame (format_context, &packet);
197         if (r < 0) {
198                 throw DecodeError (N_("av_read_frame"), name_for_errors, r);
199         }
200
201         r = avcodec_send_packet (context, &packet);
202         if (r < 0) {
203                 throw DecodeError (N_("avcodec_send_packet"), name_for_errors, r);
204         }
205
206         r = avcodec_receive_frame (context, frame);
207         if (r < 0) {
208                 throw DecodeError (N_("avcodec_receive_frame"), name_for_errors, r);
209         }
210
211         auto const pix_fmt = static_cast<AVPixelFormat>(frame->format);
212
213         _image = make_shared<Image>(frame);
214         if (_video_range == VideoRange::VIDEO && av_pix_fmt_desc_get(pix_fmt)->flags & AV_PIX_FMT_FLAG_RGB) {
215                 /* Asking for the video range to be converted by libswscale (in Image) will not work for
216                  * RGB sources since that method only processes video range in YUV and greyscale.  So we have
217                  * to do it ourselves here.
218                  */
219                 _image->video_range_to_full_range();
220         }
221
222         av_packet_unref (&packet);
223         av_frame_free (&frame);
224         avcodec_free_context (&context);
225         avformat_close_input (&format_context);
226         av_free (avio_context->buffer);
227         av_free (avio_context);
228
229         return Result (_image, 0);
230 }
231
232
233 void
234 FFmpegImageProxy::add_metadata (xmlpp::Node* node) const
235 {
236         node->add_child("Type")->add_child_text (N_("FFmpeg"));
237         node->add_child("VideoRange")->add_child_text(video_range_to_string(_video_range));
238 }
239
240 void
241 FFmpegImageProxy::write_to_socket (shared_ptr<Socket> socket) const
242 {
243         socket->write (_data.size());
244         socket->write (_data.data(), _data.size());
245 }
246
247 bool
248 FFmpegImageProxy::same (shared_ptr<const ImageProxy> other) const
249 {
250         shared_ptr<const FFmpegImageProxy> mp = dynamic_pointer_cast<const FFmpegImageProxy> (other);
251         if (!mp) {
252                 return false;
253         }
254
255         return _data == mp->_data;
256 }
257
258 size_t
259 FFmpegImageProxy::memory_used () const
260 {
261         size_t m = _data.size();
262         if (_image) {
263                 m += _image->memory_used();
264         }
265         return m;
266 }