2 Copyright (C) 2012-2021 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
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.
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.
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/>.
22 /** @file src/j2k_encoder.cc
23 * @brief J2K encoder class.
27 #include "compose.hpp"
30 #include "dcp_video.h"
31 #include "dcpomatic_log.h"
32 #include "encode_server_description.h"
33 #include "encode_server_finder.h"
35 #include "cpu_j2k_encoder_thread.h"
37 #include "grok/context.h"
38 #include "grok_j2k_encoder_thread.h"
40 #include "remote_j2k_encoder_thread.h"
41 #include "j2k_encoder.h"
43 #include "player_video.h"
46 #include <libcxml/cxml.h>
53 using std::dynamic_pointer_cast;
56 using std::make_shared;
57 using std::shared_ptr;
59 using boost::optional;
61 using namespace dcpomatic;
65 namespace grk_plugin {
67 IMessengerLogger* sLogger = nullptr;
69 #if defined(__GNUC__) || defined(__clang__)
70 #pragma GCC diagnostic push
71 #pragma GCC diagnostic ignored "-Wunused-function"
73 void setMessengerLogger(grk_plugin::IMessengerLogger* logger)
78 #if defined(__GNUC__) || defined(__clang__)
79 #pragma GCC diagnostic pop
81 grk_plugin::IMessengerLogger* getMessengerLogger(void)
91 /** @param film Film that we are encoding.
92 * @param writer Writer that we are using.
94 J2KEncoder::J2KEncoder(shared_ptr<const Film> film, Writer& writer)
99 , _dcpomatic_context(new grk_plugin::DcpomaticContext(film, writer, _history, Config::instance()->gpu_binary_location()))
100 , _context(Config::instance()->enable_gpu() ? new grk_plugin::GrokContext(_dcpomatic_context) : nullptr)
103 servers_list_changed ();
107 J2KEncoder::~J2KEncoder ()
109 _server_found_connection.disconnect();
113 #ifdef DCPOMATIC_GROK
115 delete _dcpomatic_context;
121 J2KEncoder::servers_list_changed()
123 auto config = Config::instance();
125 auto const cpu = (config->enable_gpu() || config->only_servers_encode()) ? 0 : config->master_encoding_threads();
126 auto const gpu = config->enable_gpu() ? config->master_encoding_threads() : 0;
128 remake_threads(cpu, gpu, EncodeServerFinder::instance()->servers());
135 _server_found_connection = EncodeServerFinder::instance()->ServersListChanged.connect(
136 boost::bind(&J2KEncoder::servers_list_changed, this)
144 if (!Config::instance()->enable_gpu()) {
148 terminate_threads ();
150 /* Something might have been thrown during terminate_threads */
153 #ifdef DCPOMATIC_GROK
160 void J2KEncoder::resume()
162 if (!Config::instance()->enable_gpu()) {
166 #ifdef DCPOMATIC_GROK
167 _context = new grk_plugin::GrokContext(_dcpomatic_context);
169 servers_list_changed();
176 boost::mutex::scoped_lock lock (_queue_mutex);
178 LOG_GENERAL (N_("Clearing queue of %1"), _queue.size ());
180 /* Keep waking workers until the queue is empty */
181 while (!_queue.empty ()) {
183 _full_condition.wait (lock);
187 LOG_GENERAL_NC (N_("Terminating encoder threads"));
189 terminate_threads ();
191 /* Something might have been thrown during terminate_threads */
194 LOG_GENERAL (N_("Mopping up %1"), _queue.size());
196 /* The following sequence of events can occur in the above code:
197 1. a remote worker takes the last image off the queue
198 2. the loop above terminates
199 3. the remote worker fails to encode the image and puts it back on the queue
200 4. the remote worker is then terminated by terminate_threads
202 So just mop up anything left in the queue here.
204 for (auto & i: _queue) {
205 #ifdef DCPOMATIC_GROK
206 if (Config::instance()->enable_gpu ()) {
207 if (!_context->scheduleCompress(i)){
208 LOG_GENERAL (N_("[%1] J2KEncoder thread pushes frame %2 back onto queue after failure"), thread_id(), i.index());
215 LOG_GENERAL(N_("Encode left-over frame %1"), i.index());
218 make_shared<dcp::ArrayData>(i.encode_locally()),
223 } catch (std::exception& e) {
224 LOG_ERROR (N_("Local encode failed (%1)"), e.what ());
229 #ifdef DCPOMATIC_GROK
236 /** @return an estimate of the current number of frames we are encoding per second,
240 J2KEncoder::current_encoding_rate () const
242 return _history.rate ();
246 /** @return Number of video frames that have been queued for encoding */
248 J2KEncoder::video_frames_enqueued () const
250 if (!_last_player_video_time) {
254 return _last_player_video_time->frames_floor (_film->video_frame_rate ());
258 /** Should be called when a frame has been encoded successfully */
260 J2KEncoder::frame_done ()
266 /** Called to request encoding of the next video frame in the DCP. This is called in order,
267 * so each time the supplied frame is the one after the previous one.
268 * pv represents one video frame, and could be empty if there is nothing to encode
269 * for this DCP frame.
271 * @param pv PlayerVideo to encode.
272 * @param time Time of \p pv within the DCP.
275 J2KEncoder::encode (shared_ptr<PlayerVideo> pv, DCPTime time)
281 boost::mutex::scoped_lock lm (_threads_mutex);
282 threads = _threads.size();
285 boost::mutex::scoped_lock queue_lock (_queue_mutex);
287 /* Wait until the queue has gone down a bit. Allow one thing in the queue even
288 when there are no threads.
290 while (_queue.size() >= (threads * 2) + 1) {
291 LOG_TIMING ("decoder-sleep queue=%1 threads=%2", _queue.size(), threads);
292 _full_condition.wait (queue_lock);
293 LOG_TIMING ("decoder-wake queue=%1 threads=%2", _queue.size(), threads);
297 /* Re-throw any exception raised by one of our threads. If more
298 than one has thrown an exception, only one will be rethrown, I think;
299 but then, if that happens something has gone badly wrong.
303 auto const position = time.frames_floor(_film->video_frame_rate());
305 if (_writer.can_fake_write(position)) {
306 /* We can fake-write this frame */
307 LOG_DEBUG_ENCODE("Frame @ %1 FAKE", to_string(time));
308 _writer.fake_write(position, pv->eyes ());
310 } else if (pv->has_j2k() && !_film->reencode_j2k()) {
311 LOG_DEBUG_ENCODE("Frame @ %1 J2K", to_string(time));
312 /* This frame already has J2K data, so just write it */
313 _writer.write(pv->j2k(), position, pv->eyes ());
315 } else if (_last_player_video[pv->eyes()] && _writer.can_repeat(position) && pv->same(_last_player_video[pv->eyes()])) {
316 LOG_DEBUG_ENCODE("Frame @ %1 REPEAT", to_string(time));
317 _writer.repeat(position, pv->eyes());
319 LOG_DEBUG_ENCODE("Frame @ %1 ENCODE", to_string(time));
320 /* Queue this new frame for encoding */
321 LOG_TIMING ("add-frame-to-queue queue=%1", _queue.size ());
322 auto dcpv = DCPVideo(
325 _film->video_frame_rate(),
326 _film->j2k_bandwidth(),
329 _queue.push_back (dcpv);
331 /* The queue might not be empty any more, so notify anything which is
334 _empty_condition.notify_all ();
337 _last_player_video[pv->eyes()] = pv;
338 _last_player_video_time = time;
343 J2KEncoder::terminate_threads ()
345 boost::mutex::scoped_lock lm(_threads_mutex);
346 boost::this_thread::disable_interruption dis;
348 for (auto& thread: _threads) {
358 #ifdef DCPOMATIC_GROK
359 J2KEncoder::remake_threads(int cpu, int gpu, list<EncodeServerDescription> servers)
361 J2KEncoder::remake_threads(int cpu, int, list<EncodeServerDescription> servers)
364 boost::mutex::scoped_lock lm (_threads_mutex);
369 auto remove_threads = [this](int wanted, int current, std::function<bool (shared_ptr<J2KEncoderThread>)> predicate) {
370 for (auto i = wanted; i < current; ++i) {
371 auto iter = std::find_if(_threads.begin(), _threads.end(), predicate);
372 if (iter != _threads.end()) {
374 _threads.erase(iter);
382 auto const is_cpu_thread = [](shared_ptr<J2KEncoderThread> thread) {
383 return static_cast<bool>(dynamic_pointer_cast<CPUJ2KEncoderThread>(thread));
386 auto const current_cpu_threads = std::count_if(_threads.begin(), _threads.end(), is_cpu_thread);
388 for (auto i = current_cpu_threads; i < cpu; ++i) {
389 auto thread = make_shared<CPUJ2KEncoderThread>(*this);
391 _threads.push_back(thread);
394 remove_threads(cpu, current_cpu_threads, is_cpu_thread);
396 #ifdef DCPOMATIC_GROK
399 auto const is_grok_thread = [](shared_ptr<J2KEncoderThread> thread) {
400 return static_cast<bool>(dynamic_pointer_cast<GrokJ2KEncoderThread>(thread));
403 auto const current_gpu_threads = std::count_if(_threads.begin(), _threads.end(), is_grok_thread);
405 for (auto i = current_gpu_threads; i < gpu; ++i) {
406 auto thread = make_shared<GrokJ2KEncoderThread>(*this, _context);
408 _threads.push_back(thread);
411 remove_threads(gpu, current_gpu_threads, is_grok_thread);
416 for (auto const& server: servers) {
417 if (!server.current_link_version()) {
421 auto is_remote_thread = [server](shared_ptr<J2KEncoderThread> thread) {
422 auto remote = dynamic_pointer_cast<RemoteJ2KEncoderThread>(thread);
423 return remote && remote->server().host_name() == server.host_name();
426 auto const current_threads = std::count_if(_threads.begin(), _threads.end(), is_remote_thread);
428 auto const wanted_threads = server.threads();
430 if (wanted_threads > current_threads) {
431 LOG_GENERAL(N_("Adding %1 worker threads for remote %2"), wanted_threads - current_threads, server.host_name());
432 } else if (wanted_threads < current_threads) {
433 LOG_GENERAL(N_("Removing %1 worker threads for remote %2"), current_threads - wanted_threads, server.host_name());
436 for (auto i = current_threads; i < wanted_threads; ++i) {
437 auto thread = make_shared<RemoteJ2KEncoderThread>(*this, server);
439 _threads.push_back(thread);
442 remove_threads(wanted_threads, current_threads, is_remote_thread);
445 _writer.set_encoder_threads(_threads.size());
452 boost::mutex::scoped_lock lock(_queue_mutex);
453 while (_queue.empty()) {
454 _empty_condition.wait (lock);
457 LOG_TIMING("encoder-wake thread=%1 queue=%2", thread_id(), _queue.size());
459 auto vf = _queue.front();
462 _full_condition.notify_all();
468 J2KEncoder::retry(DCPVideo video)
470 boost::mutex::scoped_lock lock(_queue_mutex);
471 _queue.push_front(video);
472 _empty_condition.notify_all();
477 J2KEncoder::write(shared_ptr<const dcp::Data> data, int index, Eyes eyes)
479 _writer.write(data, index, eyes);