Put Image in dcpomatic:: to avoid Fastvideo name clash.
[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 }
34 DCPOMATIC_DISABLE_WARNINGS
35 #include <libxml++/libxml++.h>
36 DCPOMATIC_ENABLE_WARNINGS
37 #include <iostream>
38
39 #include "i18n.h"
40
41 using std::string;
42 using std::cout;
43 using std::pair;
44 using std::min;
45 using std::make_pair;
46 using boost::shared_ptr;
47 using boost::optional;
48 using boost::dynamic_pointer_cast;
49 using dcp::raw_convert;
50 using namespace dcpomatic;
51
52
53 FFmpegImageProxy::FFmpegImageProxy (boost::filesystem::path path)
54         : _data (path)
55         , _pos (0)
56         , _path (path)
57 {
58
59 }
60
61 FFmpegImageProxy::FFmpegImageProxy (dcp::Data data)
62         : _data (data)
63         , _pos (0)
64 {
65
66 }
67
68 FFmpegImageProxy::FFmpegImageProxy (shared_ptr<cxml::Node>, shared_ptr<Socket> socket)
69         : _pos (0)
70 {
71         uint32_t const size = socket->read_uint32 ();
72         _data = dcp::Data (size);
73         socket->read (_data.data().get(), size);
74 }
75
76 static int
77 avio_read_wrapper (void* data, uint8_t* buffer, int amount)
78 {
79         return reinterpret_cast<FFmpegImageProxy*>(data)->avio_read (buffer, amount);
80 }
81
82 static int64_t
83 avio_seek_wrapper (void* data, int64_t offset, int whence)
84 {
85         return reinterpret_cast<FFmpegImageProxy*>(data)->avio_seek (offset, whence);
86 }
87
88 int
89 FFmpegImageProxy::avio_read (uint8_t* buffer, int const amount)
90 {
91         int const to_do = min(static_cast<int64_t>(amount), static_cast<int64_t>(_data.size()) - _pos);
92         if (to_do == 0) {
93                 return AVERROR_EOF;
94         }
95         memcpy (buffer, _data.data().get() + _pos, to_do);
96         _pos += to_do;
97         return to_do;
98 }
99
100 int64_t
101 FFmpegImageProxy::avio_seek (int64_t const pos, int whence)
102 {
103         switch (whence) {
104         case AVSEEK_SIZE:
105                 return _data.size();
106         case SEEK_CUR:
107                 _pos += pos;
108                 break;
109         case SEEK_SET:
110                 _pos = pos;
111                 break;
112         case SEEK_END:
113                 _pos = _data.size() - pos;
114                 break;
115         }
116
117         return _pos;
118 }
119
120 DCPOMATIC_DISABLE_WARNINGS
121
122 ImageProxy::Result
123 FFmpegImageProxy::image (optional<dcp::Size>) const
124 {
125         boost::mutex::scoped_lock lm (_mutex);
126
127         if (_image) {
128                 return Result (_image, 0);
129         }
130
131         uint8_t* avio_buffer = static_cast<uint8_t*> (wrapped_av_malloc(4096));
132         AVIOContext* avio_context = avio_alloc_context (avio_buffer, 4096, 0, const_cast<FFmpegImageProxy*>(this), avio_read_wrapper, 0, avio_seek_wrapper);
133         AVFormatContext* format_context = avformat_alloc_context ();
134         format_context->pb = avio_context;
135
136         AVDictionary* options = 0;
137         /* These durations are in microseconds, and represent how far into the content file
138            we will look for streams.
139         */
140         av_dict_set (&options, "analyzeduration", raw_convert<string>(5 * 60 * 1000000).c_str(), 0);
141         av_dict_set (&options, "probesize", raw_convert<string>(5 * 60 * 1000000).c_str(), 0);
142
143         int e = avformat_open_input (&format_context, 0, 0, &options);
144         if ((e < 0 && e == AVERROR_INVALIDDATA) || (e >= 0 && format_context->probe_score <= 25)) {
145                 /* Hack to fix loading of .tga files through AVIOContexts (rather then
146                    directly from the file).  This code just does enough to allow the
147                    probe code to take a hint from "foo.tga" and so try targa format.
148                 */
149                 AVInputFormat* f = av_find_input_format ("image2");
150                 format_context = avformat_alloc_context ();
151                 format_context->pb = avio_context;
152                 format_context->iformat = f;
153                 e = avformat_open_input (&format_context, "foo.tga", f, &options);
154         }
155         if (e < 0) {
156                 if (_path) {
157                         throw OpenFileError (_path->string(), e, OpenFileError::READ);
158                 } else {
159                         boost::throw_exception(DecodeError(String::compose(_("Could not decode image (%1)"), e)));
160                 }
161         }
162
163         if (avformat_find_stream_info(format_context, 0) < 0) {
164                 throw DecodeError (_("could not find stream information"));
165         }
166
167         DCPOMATIC_ASSERT (format_context->nb_streams == 1);
168
169         AVFrame* frame = av_frame_alloc ();
170         if (!frame) {
171                 throw DecodeError (N_("could not allocate frame"));
172         }
173
174         AVCodecContext* codec_context = format_context->streams[0]->codec;
175         AVCodec* codec = avcodec_find_decoder (codec_context->codec_id);
176         DCPOMATIC_ASSERT (codec);
177
178         if (avcodec_open2 (codec_context, codec, 0) < 0) {
179                 throw DecodeError (N_("could not open decoder"));
180         }
181
182         AVPacket packet;
183         int r = av_read_frame (format_context, &packet);
184         if (r < 0) {
185                 throw DecodeError (N_("could not read frame"));
186         }
187
188         int frame_finished;
189         if (avcodec_decode_video2(codec_context, frame, &frame_finished, &packet) < 0 || !frame_finished) {
190                 throw DecodeError (N_("could not decode video"));
191         }
192
193         _image.reset (new Image (frame));
194
195         av_packet_unref (&packet);
196         av_frame_free (&frame);
197         avcodec_close (codec_context);
198         avformat_close_input (&format_context);
199         av_free (avio_context->buffer);
200         av_free (avio_context);
201
202         return Result (_image, 0);
203 }
204
205 DCPOMATIC_ENABLE_WARNINGS
206
207 void
208 FFmpegImageProxy::add_metadata (xmlpp::Node* node) const
209 {
210         node->add_child("Type")->add_child_text (N_("FFmpeg"));
211 }
212
213 void
214 FFmpegImageProxy::write_to_socket (shared_ptr<Socket> socket) const
215 {
216         socket->write (_data.size());
217         socket->write (_data.data().get(), _data.size());
218 }
219
220 bool
221 FFmpegImageProxy::same (shared_ptr<const ImageProxy> other) const
222 {
223         shared_ptr<const FFmpegImageProxy> mp = dynamic_pointer_cast<const FFmpegImageProxy> (other);
224         if (!mp) {
225                 return false;
226         }
227
228         if (_data.size() != mp->_data.size()) {
229                 return false;
230         }
231
232         return memcmp (_data.data().get(), mp->_data.data().get(), _data.size()) == 0;
233 }
234
235 size_t
236 FFmpegImageProxy::memory_used () const
237 {
238         size_t m = _data.size();
239         if (_image) {
240                 m += _image->memory_used();
241         }
242         return m;
243 }