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