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