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