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