Add some new check methods.
[dcpomatic.git] / test / test.cc
1 /*
2     Copyright (C) 2012-2021 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
23 /** @file  test/test.cc
24  *  @brief Overall test stuff and useful methods for tests.
25  */
26
27
28 #include "lib/compose.hpp"
29 #include "lib/config.h"
30 #include "lib/cross.h"
31 #include "lib/dcp_content_type.h"
32 #include "lib/dcpomatic_log.h"
33 #include "lib/encode_server_finder.h"
34 #include "lib/ffmpeg_image_proxy.h"
35 #include "lib/file_log.h"
36 #include "lib/film.h"
37 #include "lib/image.h"
38 #include "lib/job.h"
39 #include "lib/job_manager.h"
40 #include "lib/log_entry.h"
41 #include "lib/ratio.h"
42 #include "lib/signal_manager.h"
43 #include "lib/util.h"
44 #include "test.h"
45 #include <dcp/cpl.h>
46 #include <dcp/dcp.h>
47 #include <dcp/mono_picture_asset.h>
48 #include <dcp/mono_picture_frame.h>
49 #include <dcp/openjpeg_image.h>
50 #include <dcp/reel.h>
51 #include <dcp/reel_picture_asset.h>
52 #include <asdcp/AS_DCP.h>
53 #include <png.h>
54 #include <sndfile.h>
55 #include <libxml++/libxml++.h>
56 extern "C" {
57 #include <libavformat/avformat.h>
58 }
59 #define BOOST_TEST_DYN_LINK
60 #define BOOST_TEST_MODULE dcpomatic_test
61 #include <boost/test/unit_test.hpp>
62 #include <boost/algorithm/string.hpp>
63 #include <iostream>
64 #include <list>
65 #include <vector>
66
67
68 using std::abs;
69 using std::cerr;
70 using std::cout;
71 using std::list;
72 using std::make_shared;
73 using std::min;
74 using std::shared_ptr;
75 using std::string;
76 using std::vector;
77 using boost::scoped_array;
78 using std::dynamic_pointer_cast;
79 #if BOOST_VERSION >= 106100
80 using namespace boost::placeholders;
81 #endif
82
83
84 boost::filesystem::path
85 TestPaths::TestPaths::private_data ()
86 {
87         char* env = getenv("DCPOMATIC_TEST_PRIVATE");
88         if (env) {
89                 return boost::filesystem::path(env);
90         }
91
92         return boost::filesystem::canonical(boost::filesystem::path ("..") / boost::filesystem::path ("dcpomatic-test-private"));
93 }
94
95
96 boost::filesystem::path TestPaths::xsd ()
97 {
98         return boost::filesystem::canonical(boost::filesystem::path("..") / boost::filesystem::path("libdcp") / boost::filesystem::path("xsd"));
99 }
100
101
102 void
103 setup_test_config ()
104 {
105         Config::instance()->set_master_encoding_threads (boost::thread::hardware_concurrency());
106         Config::instance()->set_server_encoding_threads (1);
107         Config::instance()->set_server_port_base (61921);
108         Config::instance()->set_default_container (Ratio::from_id ("185"));
109         Config::instance()->set_default_dcp_content_type (static_cast<DCPContentType*> (0));
110         Config::instance()->set_default_audio_delay (0);
111         Config::instance()->set_default_j2k_bandwidth (100000000);
112         Config::instance()->set_default_interop (false);
113         Config::instance()->set_default_still_length (10);
114         Config::instance()->set_log_types (
115                 LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING |
116                 LogEntry::TYPE_ERROR | LogEntry::TYPE_DEBUG_THREE_D |
117                 LogEntry::TYPE_DEBUG_ENCODE | LogEntry::TYPE_DEBUG_PLAYER |
118                 LogEntry::TYPE_DISK
119                 );
120         Config::instance()->set_automatic_audio_analysis (false);
121         auto signer = make_shared<dcp::CertificateChain>(dcp::file_to_string("test/data/signer_chain"));
122         signer->set_key(dcp::file_to_string("test/data/signer_key"));
123         Config::instance()->set_signer_chain (signer);
124         auto decryption = make_shared<dcp::CertificateChain>(dcp::file_to_string("test/data/decryption_chain"));
125         decryption->set_key(dcp::file_to_string("test/data/decryption_key"));
126         Config::instance()->set_decryption_chain (decryption);
127 }
128
129
130 class TestSignalManager : public SignalManager
131 {
132 public:
133         /* No wakes in tests: we call ui_idle ourselves */
134         void wake_ui ()
135         {
136
137         }
138 };
139
140 struct TestConfig
141 {
142         TestConfig ()
143         {
144                 State::override_path = "build/test/state";
145                 boost::filesystem::remove_all (*State::override_path);
146
147                 dcpomatic_setup ();
148                 setup_test_config ();
149
150                 EncodeServerFinder::instance()->stop ();
151
152                 signal_manager = new TestSignalManager ();
153
154                 dcpomatic_log.reset (new FileLog("build/test/log"));
155         }
156
157         ~TestConfig ()
158         {
159                 JobManager::drop ();
160         }
161 };
162
163
164 BOOST_GLOBAL_FIXTURE (TestConfig);
165
166
167 boost::filesystem::path
168 test_film_dir (string name)
169 {
170         boost::filesystem::path p;
171         p /= "build";
172         p /= "test";
173         p /= name;
174         return p;
175 }
176
177
178 shared_ptr<Film>
179 new_test_film (string name)
180 {
181         auto p = test_film_dir (name);
182         if (boost::filesystem::exists (p)) {
183                 boost::filesystem::remove_all (p);
184         }
185
186         auto film = make_shared<Film>(p);
187         film->write_metadata ();
188         return film;
189 }
190
191
192 shared_ptr<Film>
193 new_test_film2 (string name, vector<shared_ptr<Content>> content, Cleanup* cleanup)
194 {
195         auto p = test_film_dir (name);
196         if (boost::filesystem::exists (p)) {
197                 boost::filesystem::remove_all (p);
198         }
199         if (cleanup) {
200                 cleanup->add (p);
201         }
202
203         auto film = make_shared<Film>(p);
204         film->set_dcp_content_type (DCPContentType::from_isdcf_name ("TST"));
205         film->set_container (Ratio::from_id ("185"));
206         film->write_metadata ();
207
208         for (auto i: content) {
209                 film->examine_and_add_content (i);
210                 BOOST_REQUIRE (!wait_for_jobs());
211         }
212
213         return film;
214 }
215
216
217 void
218 check_wav_file (boost::filesystem::path ref, boost::filesystem::path check)
219 {
220         SF_INFO ref_info;
221         ref_info.format = 0;
222         auto ref_file = sf_open (ref.string().c_str(), SFM_READ, &ref_info);
223         BOOST_CHECK (ref_file);
224
225         SF_INFO check_info;
226         check_info.format = 0;
227         auto check_file = sf_open (check.string().c_str(), SFM_READ, &check_info);
228         BOOST_CHECK (check_file);
229
230         BOOST_CHECK_EQUAL (ref_info.frames, check_info.frames);
231         BOOST_CHECK_EQUAL (ref_info.samplerate, check_info.samplerate);
232         BOOST_CHECK_EQUAL (ref_info.channels, check_info.channels);
233         BOOST_CHECK_EQUAL (ref_info.format, check_info.format);
234
235         /* buffer_size is in frames */
236         sf_count_t const buffer_size = 65536 * ref_info.channels;
237         scoped_array<int32_t> ref_buffer (new int32_t[buffer_size]);
238         scoped_array<int32_t> check_buffer (new int32_t[buffer_size]);
239
240         sf_count_t N = ref_info.frames;
241         while (N) {
242                 sf_count_t this_time = min (buffer_size, N);
243                 sf_count_t r = sf_readf_int (ref_file, ref_buffer.get(), this_time);
244                 BOOST_CHECK_EQUAL (r, this_time);
245                 r = sf_readf_int (check_file, check_buffer.get(), this_time);
246                 BOOST_CHECK_EQUAL (r, this_time);
247
248                 for (sf_count_t i = 0; i < this_time; ++i) {
249                         BOOST_REQUIRE_MESSAGE (
250                                 abs (ref_buffer[i] - check_buffer[i]) <= 65536,
251                                 ref << " differs from " << check << " at " << (ref_info.frames - N + i) << " of " << ref_info.frames
252                                 << "(" << ref_buffer[i] << " vs " << check_buffer[i] << ")"
253                                 );
254                 }
255
256                 N -= this_time;
257         }
258 }
259
260
261 void
262 check_mxf_audio_file (boost::filesystem::path ref, boost::filesystem::path check)
263 {
264         ASDCP::PCM::MXFReader ref_reader;
265         BOOST_REQUIRE (!ASDCP_FAILURE (ref_reader.OpenRead (ref.string().c_str())));
266
267         ASDCP::PCM::AudioDescriptor ref_desc;
268         BOOST_REQUIRE (!ASDCP_FAILURE (ref_reader.FillAudioDescriptor (ref_desc)));
269
270         ASDCP::PCM::MXFReader check_reader;
271         BOOST_REQUIRE (!ASDCP_FAILURE (check_reader.OpenRead (check.string().c_str())));
272
273         ASDCP::PCM::AudioDescriptor check_desc;
274         BOOST_REQUIRE (!ASDCP_FAILURE (check_reader.FillAudioDescriptor (check_desc)));
275
276         BOOST_REQUIRE_EQUAL (ref_desc.ContainerDuration, check_desc.ContainerDuration);
277
278         ASDCP::PCM::FrameBuffer ref_buffer (Kumu::Megabyte);
279         ASDCP::PCM::FrameBuffer check_buffer (Kumu::Megabyte);
280         for (size_t i = 0; i < ref_desc.ContainerDuration; ++i) {
281                 ref_reader.ReadFrame (i, ref_buffer, 0);
282                 check_reader.ReadFrame (i, check_buffer, 0);
283                 BOOST_REQUIRE (memcmp(ref_buffer.RoData(), check_buffer.RoData(), ref_buffer.Size()) == 0);
284         }
285 }
286
287
288 /** @return true if the files are the same, otherwise false */
289 bool
290 mxf_atmos_files_same (boost::filesystem::path ref, boost::filesystem::path check, bool verbose)
291 {
292         ASDCP::ATMOS::MXFReader ref_reader;
293         BOOST_REQUIRE (!ASDCP_FAILURE(ref_reader.OpenRead(ref.string().c_str())));
294
295         ASDCP::ATMOS::AtmosDescriptor ref_desc;
296         BOOST_REQUIRE (!ASDCP_FAILURE(ref_reader.FillAtmosDescriptor(ref_desc)));
297
298         ASDCP::ATMOS::MXFReader check_reader;
299         BOOST_REQUIRE (!ASDCP_FAILURE(check_reader.OpenRead(check.string().c_str())));
300
301         ASDCP::ATMOS::AtmosDescriptor check_desc;
302         BOOST_REQUIRE (!ASDCP_FAILURE(check_reader.FillAtmosDescriptor(check_desc)));
303
304         if (ref_desc.EditRate.Numerator != check_desc.EditRate.Numerator) {
305                 if (verbose) {
306                         std::cout << "EditRate.Numerator differs.\n";
307                 }
308                 return false;
309         }
310         if (ref_desc.EditRate.Denominator != check_desc.EditRate.Denominator) {
311                 if (verbose) {
312                         std::cout << "EditRate.Denominator differs.\n";
313                 }
314                 return false;
315         }
316         if (ref_desc.ContainerDuration != check_desc.ContainerDuration) {
317                 if (verbose) {
318                         std::cout << "EditRate.ContainerDuration differs.\n";
319                 }
320                 return false;
321         }
322         if (ref_desc.FirstFrame != check_desc.FirstFrame) {
323                 if (verbose) {
324                         std::cout << "EditRate.FirstFrame differs.\n";
325                 }
326                 return false;
327         }
328         if (ref_desc.MaxChannelCount != check_desc.MaxChannelCount) {
329                 if (verbose) {
330                         std::cout << "EditRate.MaxChannelCount differs.\n";
331                 }
332                 return false;
333         }
334         if (ref_desc.MaxObjectCount != check_desc.MaxObjectCount) {
335                 if (verbose) {
336                         std::cout << "EditRate.MaxObjectCount differs.\n";
337                 }
338                 return false;
339         }
340         if (ref_desc.AtmosVersion != check_desc.AtmosVersion) {
341                 if (verbose) {
342                         std::cout << "EditRate.AtmosVersion differs.\n";
343                 }
344                 return false;
345         }
346
347         ASDCP::DCData::FrameBuffer ref_buffer (Kumu::Megabyte);
348         ASDCP::DCData::FrameBuffer check_buffer (Kumu::Megabyte);
349         for (size_t i = 0; i < ref_desc.ContainerDuration; ++i) {
350                 ref_reader.ReadFrame (i, ref_buffer, 0);
351                 check_reader.ReadFrame (i, check_buffer, 0);
352                 if (memcmp(ref_buffer.RoData(), check_buffer.RoData(), ref_buffer.Size())) {
353                         if (verbose) {
354                                 std::cout << "data differs.\n";
355                         }
356                         return false;
357                 }
358         }
359
360         return true;
361 }
362
363
364 static
365 double
366 rms_error (boost::filesystem::path ref, boost::filesystem::path check)
367 {
368         FFmpegImageProxy ref_proxy (ref, VideoRange::FULL);
369         auto ref_image = ref_proxy.image().image;
370         FFmpegImageProxy check_proxy (check, VideoRange::FULL);
371         auto check_image = check_proxy.image().image;
372
373         BOOST_REQUIRE_EQUAL (ref_image->pixel_format(), check_image->pixel_format());
374         AVPixelFormat const format = ref_image->pixel_format();
375
376         BOOST_REQUIRE (ref_image->size() == check_image->size());
377         int const width = ref_image->size().width;
378         int const height = ref_image->size().height;
379
380         double sum_square = 0;
381         switch (format) {
382                 case AV_PIX_FMT_RGBA:
383                 {
384                         for (int y = 0; y < height; ++y) {
385                                 uint8_t* p = ref_image->data()[0] + y * ref_image->stride()[0];
386                                 uint8_t* q = check_image->data()[0] + y * check_image->stride()[0];
387                                 for (int x = 0; x < width; ++x) {
388                                         for (int c = 0; c < 4; ++c) {
389                                                 sum_square += pow((*p++ - *q++), 2);
390                                         }
391                                 }
392                         }
393                         break;
394                 }
395                 case AV_PIX_FMT_RGB24:
396                 {
397                         for (int y = 0; y < height; ++y) {
398                                 uint8_t* p = ref_image->data()[0] + y * ref_image->stride()[0];
399                                 uint8_t* q = check_image->data()[0] + y * check_image->stride()[0];
400                                 for (int x = 0; x < width; ++x) {
401                                         for (int c = 0; c < 3; ++c) {
402                                                 sum_square += pow((*p++ - *q++), 2);
403                                         }
404                                 }
405                         }
406                         break;
407                 }
408                 case AV_PIX_FMT_RGB48BE:
409                 {
410                         for (int y = 0; y < height; ++y) {
411                                 uint16_t* p = reinterpret_cast<uint16_t*>(ref_image->data()[0] + y * ref_image->stride()[0]);
412                                 uint16_t* q = reinterpret_cast<uint16_t*>(check_image->data()[0] + y * check_image->stride()[0]);
413                                 for (int x = 0; x < width; ++x) {
414                                         for (int c = 0; c < 3; ++c) {
415                                                 sum_square += pow((*p++ - *q++), 2);
416                                         }
417                                 }
418                         }
419                         break;
420                 }
421                 default:
422                         BOOST_REQUIRE_MESSAGE (false, "unrecognised pixel format " << format);
423         }
424
425         return sqrt(sum_square / (height * width));
426 }
427
428
429 BOOST_AUTO_TEST_CASE (rms_error_test)
430 {
431         BOOST_CHECK_CLOSE (rms_error("test/data/check_image0.png", "test/data/check_image0.png"), 0, 0.001);
432         BOOST_CHECK_CLOSE (rms_error("test/data/check_image0.png", "test/data/check_image1.png"), 2.2778, 0.001);
433         BOOST_CHECK_CLOSE (rms_error("test/data/check_image0.png", "test/data/check_image2.png"), 59.8896, 0.001);
434         BOOST_CHECK_CLOSE (rms_error("test/data/check_image0.png", "test/data/check_image3.png"), 0.89164, 0.001);
435 }
436
437
438 void
439 check_image (boost::filesystem::path ref, boost::filesystem::path check, double threshold)
440 {
441         double const e = rms_error (ref, check);
442         BOOST_CHECK_MESSAGE (e < threshold, ref << " differs from " << check << " " << e);
443 }
444
445
446 void
447 check_file (boost::filesystem::path ref, boost::filesystem::path check)
448 {
449         auto N = boost::filesystem::file_size (ref);
450         BOOST_CHECK_EQUAL (N, boost::filesystem::file_size (check));
451         auto ref_file = fopen_boost (ref, "rb");
452         BOOST_CHECK (ref_file);
453         auto check_file = fopen_boost (check, "rb");
454         BOOST_CHECK (check_file);
455
456         int const buffer_size = 65536;
457         uint8_t* ref_buffer = new uint8_t[buffer_size];
458         uint8_t* check_buffer = new uint8_t[buffer_size];
459
460         string error = "File " + check.string() + " differs from reference " + ref.string();
461
462         while (N) {
463                 uintmax_t this_time = min (uintmax_t (buffer_size), N);
464                 size_t r = fread (ref_buffer, 1, this_time, ref_file);
465                 BOOST_CHECK_EQUAL (r, this_time);
466                 r = fread (check_buffer, 1, this_time, check_file);
467                 BOOST_CHECK_EQUAL (r, this_time);
468
469                 BOOST_CHECK_MESSAGE (memcmp (ref_buffer, check_buffer, this_time) == 0, error);
470                 if (memcmp (ref_buffer, check_buffer, this_time)) {
471                         break;
472                 }
473
474                 N -= this_time;
475         }
476
477         delete[] ref_buffer;
478         delete[] check_buffer;
479
480         fclose (ref_file);
481         fclose (check_file);
482 }
483
484
485 void
486 check_text_file (boost::filesystem::path ref, boost::filesystem::path check)
487 {
488         auto ref_file = fopen_boost (ref, "r");
489         BOOST_CHECK (ref_file);
490         auto check_file = fopen_boost (check, "r");
491         BOOST_CHECK (check_file);
492
493         int const buffer_size = std::max(
494                 boost::filesystem::file_size(ref),
495                 boost::filesystem::file_size(check)
496                 );
497
498         DCPOMATIC_ASSERT (buffer_size < 1024 * 1024);
499
500         auto ref_buffer = new uint8_t[buffer_size];
501         auto ref_read = fread(ref_buffer, 1, buffer_size, ref_file);
502         auto check_buffer = new uint8_t[buffer_size];
503         auto check_read = fread(check_buffer, 1, buffer_size, check_file);
504         BOOST_CHECK_EQUAL (ref_read, check_read);
505
506         string const error = "File " + check.string() + " differs from reference " + ref.string();
507         BOOST_CHECK_MESSAGE(memcmp(ref_buffer, check_buffer, ref_read) == 0, error);
508
509         delete[] ref_buffer;
510         delete[] check_buffer;
511
512         fclose (ref_file);
513         fclose (check_file);
514 }
515
516
517 static void
518 note (dcp::NoteType t, string n)
519 {
520         if (t == dcp::NoteType::ERROR) {
521                 cerr << n << "\n";
522         }
523 }
524
525
526 void
527 check_dcp (boost::filesystem::path ref, shared_ptr<const Film> film)
528 {
529         check_dcp (ref, film->dir(film->dcp_name()));
530 }
531
532
533 void
534 check_dcp (boost::filesystem::path ref, boost::filesystem::path check)
535 {
536         dcp::DCP ref_dcp (ref);
537         ref_dcp.read ();
538         dcp::DCP check_dcp (check);
539         check_dcp.read ();
540
541         dcp::EqualityOptions options;
542         options.max_mean_pixel_error = 5;
543         options.max_std_dev_pixel_error = 5;
544         options.max_audio_sample_error = 255;
545         options.cpl_annotation_texts_can_differ = true;
546         options.reel_annotation_texts_can_differ = true;
547         options.reel_hashes_can_differ = true;
548         options.issue_dates_can_differ = true;
549
550         BOOST_CHECK (ref_dcp.equals (check_dcp, options, boost::bind (note, _1, _2)));
551 }
552
553 void
554 check_xml (xmlpp::Element* ref, xmlpp::Element* test, list<string> ignore)
555 {
556         BOOST_CHECK_EQUAL (ref->get_name (), test->get_name ());
557         BOOST_CHECK_EQUAL (ref->get_namespace_prefix (), test->get_namespace_prefix ());
558
559         if (find (ignore.begin(), ignore.end(), ref->get_name()) != ignore.end ()) {
560                 return;
561         }
562
563         auto ref_children = ref->get_children ();
564         auto test_children = test->get_children ();
565         BOOST_REQUIRE_MESSAGE (
566                 ref_children.size() == test_children.size(),
567                 ref->get_name() << " has " << ref_children.size() << " or " << test_children.size() << " children"
568                 );
569
570         auto k = ref_children.begin ();
571         auto l = test_children.begin ();
572         while (k != ref_children.end ()) {
573
574                 /* XXX: should be doing xmlpp::EntityReference, xmlpp::XIncludeEnd, xmlpp::XIncludeStart */
575
576                 auto ref_el = dynamic_cast<xmlpp::Element*>(*k);
577                 auto test_el = dynamic_cast<xmlpp::Element*>(*l);
578                 BOOST_CHECK ((ref_el && test_el) || (!ref_el && !test_el));
579                 if (ref_el && test_el) {
580                         check_xml (ref_el, test_el, ignore);
581                 }
582
583                 auto ref_cn = dynamic_cast<xmlpp::ContentNode*>(*k);
584                 auto test_cn = dynamic_cast<xmlpp::ContentNode*>(*l);
585                 BOOST_CHECK ((ref_cn && test_cn) || (!ref_cn && !test_cn));
586                 if (ref_cn && test_cn) {
587                         BOOST_CHECK_EQUAL (ref_cn->get_content(), test_cn->get_content ());
588                 }
589
590                 ++k;
591                 ++l;
592         }
593
594         auto ref_attributes = ref->get_attributes ();
595         auto test_attributes = test->get_attributes ();
596         BOOST_CHECK_EQUAL (ref_attributes.size(), test_attributes.size ());
597
598         auto m = ref_attributes.begin();
599         auto n = test_attributes.begin();
600         while (m != ref_attributes.end ()) {
601                 BOOST_CHECK_EQUAL ((*m)->get_name(), (*n)->get_name());
602                 BOOST_CHECK_EQUAL ((*m)->get_value(), (*n)->get_value());
603
604                 ++m;
605                 ++n;
606         }
607 }
608
609 void
610 check_xml (boost::filesystem::path ref, boost::filesystem::path test, list<string> ignore)
611 {
612         auto ref_parser = new xmlpp::DomParser(ref.string());
613         auto ref_root = ref_parser->get_document()->get_root_node();
614         auto test_parser = new xmlpp::DomParser(test.string());
615         auto test_root = test_parser->get_document()->get_root_node();
616
617         check_xml (ref_root, test_root, ignore);
618 }
619
620 bool
621 wait_for_jobs ()
622 {
623         auto jm = JobManager::instance ();
624         while (jm->work_to_do()) {
625                 while (signal_manager->ui_idle()) {}
626                 dcpomatic_sleep_seconds (1);
627         }
628
629         if (jm->errors ()) {
630                 int N = 0;
631                 for (auto i: jm->_jobs) {
632                         if (i->finished_in_error()) {
633                                 ++N;
634                         }
635                 }
636                 cerr << N << " errors.\n";
637
638                 for (auto i: jm->_jobs) {
639                         if (i->finished_in_error()) {
640                                 cerr << i->name() << ":\n"
641                                      << "\tsummary: " << i->error_summary() << "\n"
642                                      << "\tdetails: " << i->error_details() << "\n";
643                         }
644                 }
645         }
646
647         while (signal_manager->ui_idle ()) {}
648
649         if (jm->errors ()) {
650                 JobManager::drop ();
651                 return true;
652         }
653
654         return false;
655 }
656
657
658 class Memory
659 {
660 public:
661         Memory () {}
662
663         ~Memory ()
664         {
665                 free (data);
666         }
667
668         Memory (Memory const&) = delete;
669         Memory& operator= (Memory const&) = delete;
670
671         uint8_t* data = nullptr;
672         size_t size = 0;
673 };
674
675
676 static void
677 png_write_data (png_structp png_ptr, png_bytep data, png_size_t length)
678 {
679         auto mem = reinterpret_cast<Memory*>(png_get_io_ptr(png_ptr));
680         size_t size = mem->size + length;
681
682         if (mem->data) {
683                 mem->data = reinterpret_cast<uint8_t*>(realloc(mem->data, size));
684         } else {
685                 mem->data = reinterpret_cast<uint8_t*>(malloc(size));
686         }
687
688         BOOST_REQUIRE (mem->data);
689
690         memcpy (mem->data + mem->size, data, length);
691         mem->size += length;
692 }
693
694
695 static void
696 png_flush (png_structp)
697 {
698
699 }
700
701
702 static void
703 png_error_fn (png_structp png_ptr, char const * message)
704 {
705         reinterpret_cast<Image*>(png_get_error_ptr(png_ptr))->png_error (message);
706 }
707
708
709 void
710 write_image (shared_ptr<const Image> image, boost::filesystem::path file)
711 {
712         int png_color_type = 0;
713         int bits_per_pixel = 0;
714         switch (image->pixel_format()) {
715         case AV_PIX_FMT_RGB24:
716                 png_color_type = PNG_COLOR_TYPE_RGB;
717                 bits_per_pixel = 8;
718                 break;
719         case AV_PIX_FMT_XYZ12LE:
720                 png_color_type = PNG_COLOR_TYPE_RGB;
721                 bits_per_pixel = 16;
722                 break;
723         default:
724                 BOOST_REQUIRE_MESSAGE (false, "unexpected pixel format " << image->pixel_format());
725         }
726
727         /* error handling? */
728         png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, reinterpret_cast<void*>(const_cast<Image*>(image.get())), png_error_fn, 0);
729         BOOST_REQUIRE (png_ptr);
730
731         Memory state;
732
733         png_set_write_fn (png_ptr, &state, png_write_data, png_flush);
734
735         png_infop info_ptr = png_create_info_struct(png_ptr);
736         BOOST_REQUIRE (info_ptr);
737
738         png_set_IHDR (png_ptr, info_ptr, image->size().width, image->size().height, bits_per_pixel, png_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
739
740         png_byte ** row_pointers = reinterpret_cast<png_byte **>(png_malloc(png_ptr, image->size().height * sizeof(png_byte *)));
741         for (int i = 0; i < image->size().height; ++i) {
742                 row_pointers[i] = (png_byte *) (image->data()[0] + i * image->stride()[0]);
743         }
744
745         png_write_info (png_ptr, info_ptr);
746         png_write_image (png_ptr, row_pointers);
747         png_write_end (png_ptr, info_ptr);
748
749         png_destroy_write_struct (&png_ptr, &info_ptr);
750         png_free (png_ptr, row_pointers);
751
752         dcp::ArrayData(state.data, state.size).write(file);
753 }
754
755
756 void
757 check_ffmpeg (boost::filesystem::path ref, boost::filesystem::path check, int audio_tolerance)
758 {
759         int const r = system (String::compose("ffcmp -t %1 %2 %3", audio_tolerance, ref.string(), check.string()).c_str());
760         BOOST_REQUIRE_EQUAL (WEXITSTATUS(r), 0);
761 }
762
763 void
764 check_one_frame (boost::filesystem::path dcp_dir, int64_t index, boost::filesystem::path ref)
765 {
766         dcp::DCP dcp (dcp_dir);
767         dcp.read ();
768         auto asset = dynamic_pointer_cast<dcp::MonoPictureAsset> (dcp.cpls().front()->reels().front()->main_picture()->asset());
769         BOOST_REQUIRE (asset);
770         auto frame = asset->start_read()->get_frame(index);
771         auto ref_frame (new dcp::MonoPictureFrame (ref));
772
773         auto image = frame->xyz_image ();
774         auto ref_image = ref_frame->xyz_image ();
775
776         BOOST_REQUIRE (image->size() == ref_image->size());
777
778         int off = 0;
779         for (int y = 0; y < ref_image->size().height; ++y) {
780                 for (int x = 0; x < ref_image->size().width; ++x) {
781                         BOOST_REQUIRE_EQUAL (ref_image->data(0)[off], image->data(0)[off]);
782                         BOOST_REQUIRE_EQUAL (ref_image->data(1)[off], image->data(1)[off]);
783                         BOOST_REQUIRE_EQUAL (ref_image->data(2)[off], image->data(2)[off]);
784                         ++off;
785                 }
786         }
787 }
788
789 boost::filesystem::path
790 dcp_file (shared_ptr<const Film> film, string prefix)
791 {
792         auto i = boost::filesystem::directory_iterator (film->dir(film->dcp_name()));
793         while (i != boost::filesystem::directory_iterator() && !boost::algorithm::starts_with (i->path().leaf().string(), prefix)) {
794                 ++i;
795         }
796
797         BOOST_REQUIRE (i != boost::filesystem::directory_iterator());
798         return i->path();
799 }
800
801 boost::filesystem::path
802 subtitle_file (shared_ptr<Film> film)
803 {
804         for (auto i: boost::filesystem::directory_iterator(film->directory().get() / film->dcp_name (false))) {
805                 if (boost::filesystem::is_directory(i.path())) {
806                         for (auto j: boost::filesystem::directory_iterator(i.path())) {
807                                 if (boost::algorithm::starts_with(j.path().leaf().string(), "sub_")) {
808                                         return j.path();
809                                 }
810                         }
811                 }
812         }
813
814         BOOST_REQUIRE (false);
815         /* Remove warning */
816         return boost::filesystem::path("/");
817 }
818
819 void
820 make_random_file (boost::filesystem::path path, size_t size)
821 {
822         auto t = fopen_boost(path, "wb");
823         BOOST_REQUIRE (t);
824         for (size_t i = 0; i < size; ++i) {
825                 uint8_t r = rand() & 0xff;
826                 fwrite (&r, 1, 1, t);
827         }
828         fclose (t);
829 }
830
831
832 LogSwitcher::LogSwitcher (shared_ptr<Log> log)
833         : _old (dcpomatic_log)
834 {
835         dcpomatic_log = log;
836 }
837
838
839 LogSwitcher::~LogSwitcher ()
840 {
841         dcpomatic_log = _old;
842 }
843
844 std::ostream&
845 dcp::operator<< (std::ostream& s, dcp::Size i)
846 {
847         s << i.width << "x" << i.height;
848         return s;
849 }
850
851 std::ostream&
852 dcp::operator<< (std::ostream& s, dcp::Standard t)
853 {
854         switch (t) {
855         case Standard::INTEROP:
856                 s << "interop";
857                 break;
858         case Standard::SMPTE:
859                 s << "smpte";
860                 break;
861         }
862         return s;
863 }
864
865 std::ostream&
866 operator<< (std::ostream&s, VideoFrameType f)
867 {
868         s << video_frame_type_to_string(f);
869         return s;
870 }
871
872
873 void
874 Cleanup::add (boost::filesystem::path path)
875 {
876         _paths.push_back (path);
877 }
878
879
880 void
881 Cleanup::run ()
882 {
883         boost::system::error_code ec;
884         for (auto i: _paths) {
885                 boost::filesystem::remove_all (i, ec);
886         }
887 }
888
889
890 void stage (string, boost::optional<boost::filesystem::path>) {}
891 void progress (float) {}
892
893
894 void
895 make_and_verify_dcp (shared_ptr<Film> film, vector<dcp::VerificationNote::Code> ignore)
896 {
897         film->write_metadata ();
898         film->make_dcp ();
899         BOOST_REQUIRE (!wait_for_jobs());
900         auto notes = dcp::verify ({film->dir(film->dcp_name())}, &stage, &progress, TestPaths::xsd());
901         bool ok = true;
902         for (auto i: notes) {
903                 if (find(ignore.begin(), ignore.end(), i.code()) == ignore.end()) {
904                         std::cout << "\t" << dcp::note_to_string(i) << "\n";
905                         ok = false;
906                 }
907         }
908         BOOST_CHECK(ok);
909 }
910
911
912 void
913 check_int_close (int a, int b, int d)
914 {
915         BOOST_CHECK (std::abs(a - b) < d);
916 }
917
918
919 void
920 check_int_close (std::pair<int, int> a, std::pair<int, int> b, int d)
921 {
922         check_int_close (a.first, b.first, d);
923         check_int_close (a.second, b.second, d);
924 }