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