Use ImageMagick for test stuff.
[dcpomatic.git] / test / test.cc
1 /*
2     Copyright (C) 2012-2018 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file  test/test.cc
22  *  @brief Overall test stuff and useful methods for tests.
23  */
24
25 #include "lib/config.h"
26 #include "lib/util.h"
27 #include "lib/signal_manager.h"
28 #include "lib/film.h"
29 #include "lib/job_manager.h"
30 #include "lib/job.h"
31 #include "lib/cross.h"
32 #include "lib/encode_server_finder.h"
33 #include "lib/image.h"
34 #include "lib/ratio.h"
35 #include "lib/dcp_content_type.h"
36 #include "lib/log_entry.h"
37 #include "lib/compose.hpp"
38 #include "test.h"
39 #include <dcp/dcp.h>
40 #include <dcp/cpl.h>
41 #include <dcp/reel.h>
42 #include <dcp/reel_picture_asset.h>
43 #include <dcp/mono_picture_frame.h>
44 #include <dcp/mono_picture_asset.h>
45 #include <dcp/openjpeg_image.h>
46 #include <asdcp/AS_DCP.h>
47 #include <sndfile.h>
48 #include <libxml++/libxml++.h>
49 #include <Magick++.h>
50 extern "C" {
51 #include <libavformat/avformat.h>
52 }
53 #define BOOST_TEST_DYN_LINK
54 #define BOOST_TEST_MODULE dcpomatic_test
55 #include <boost/test/unit_test.hpp>
56 #include <boost/algorithm/string.hpp>
57 #include <list>
58 #include <vector>
59 #include <iostream>
60
61 using std::string;
62 using std::vector;
63 using std::min;
64 using std::cout;
65 using std::cerr;
66 using std::list;
67 using std::abs;
68 using boost::shared_ptr;
69 using boost::scoped_array;
70 using boost::dynamic_pointer_cast;
71
72 boost::filesystem::path private_data = boost::filesystem::canonical(boost::filesystem::path ("..") / boost::filesystem::path ("dcpomatic-test-private"));
73
74 void
75 setup_test_config ()
76 {
77         Config::instance()->set_master_encoding_threads (1);
78         Config::instance()->set_server_encoding_threads (1);
79         Config::instance()->set_server_port_base (61921);
80         Config::instance()->set_default_isdcf_metadata (ISDCFMetadata ());
81         Config::instance()->set_default_container (Ratio::from_id ("185"));
82         Config::instance()->set_default_dcp_content_type (static_cast<DCPContentType*> (0));
83         Config::instance()->set_default_audio_delay (0);
84         Config::instance()->set_default_j2k_bandwidth (100000000);
85         Config::instance()->set_default_interop (false);
86         Config::instance()->set_default_still_length (10);
87         Config::instance()->set_log_types (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR);
88         Config::instance()->set_automatic_audio_analysis (false);
89 }
90
91 class TestSignalManager : public SignalManager
92 {
93 public:
94         /* No wakes in tests: we call ui_idle ourselves */
95         void wake_ui ()
96         {
97
98         }
99 };
100
101 struct TestConfig
102 {
103         TestConfig ()
104         {
105                 dcpomatic_setup ();
106                 setup_test_config ();
107
108                 EncodeServerFinder::instance()->stop ();
109
110                 signal_manager = new TestSignalManager ();
111
112                 char* env_private = getenv("DCPOMATIC_TEST_PRIVATE");
113                 if (env_private) {
114                         private_data = env_private;
115                 }
116         }
117
118         ~TestConfig ()
119         {
120                 JobManager::drop ();
121         }
122 };
123
124 BOOST_GLOBAL_FIXTURE (TestConfig);
125
126 boost::filesystem::path
127 test_film_dir (string name)
128 {
129         boost::filesystem::path p;
130         p /= "build";
131         p /= "test";
132         p /= name;
133         return p;
134 }
135
136 shared_ptr<Film>
137 new_test_film (string name)
138 {
139         boost::filesystem::path p = test_film_dir (name);
140         if (boost::filesystem::exists (p)) {
141                 boost::filesystem::remove_all (p);
142         }
143
144         shared_ptr<Film> film = shared_ptr<Film> (new Film (p));
145         film->write_metadata ();
146         return film;
147 }
148
149 shared_ptr<Film>
150 new_test_film2 (string name)
151 {
152         boost::filesystem::path p = test_film_dir (name);
153         if (boost::filesystem::exists (p)) {
154                 boost::filesystem::remove_all (p);
155         }
156
157         shared_ptr<Film> film = shared_ptr<Film> (new Film (p));
158         film->set_dcp_content_type (DCPContentType::from_isdcf_name ("TST"));
159         film->set_container (Ratio::from_id ("185"));
160         film->write_metadata ();
161         return film;
162 }
163
164 void
165 check_wav_file (boost::filesystem::path ref, boost::filesystem::path check)
166 {
167         SF_INFO ref_info;
168         ref_info.format = 0;
169         SNDFILE* ref_file = sf_open (ref.string().c_str(), SFM_READ, &ref_info);
170         BOOST_CHECK (ref_file);
171
172         SF_INFO check_info;
173         check_info.format = 0;
174         SNDFILE* check_file = sf_open (check.string().c_str(), SFM_READ, &check_info);
175         BOOST_CHECK (check_file);
176
177         BOOST_CHECK_EQUAL (ref_info.frames, check_info.frames);
178         BOOST_CHECK_EQUAL (ref_info.samplerate, check_info.samplerate);
179         BOOST_CHECK_EQUAL (ref_info.channels, check_info.channels);
180         BOOST_CHECK_EQUAL (ref_info.format, check_info.format);
181
182         /* buffer_size is in frames */
183         sf_count_t const buffer_size = 65536 * ref_info.channels;
184         scoped_array<int32_t> ref_buffer (new int32_t[buffer_size]);
185         scoped_array<int32_t> check_buffer (new int32_t[buffer_size]);
186
187         sf_count_t N = ref_info.frames;
188         while (N) {
189                 sf_count_t this_time = min (buffer_size, N);
190                 sf_count_t r = sf_readf_int (ref_file, ref_buffer.get(), this_time);
191                 BOOST_CHECK_EQUAL (r, this_time);
192                 r = sf_readf_int (check_file, check_buffer.get(), this_time);
193                 BOOST_CHECK_EQUAL (r, this_time);
194
195                 for (sf_count_t i = 0; i < this_time; ++i) {
196                         BOOST_REQUIRE_MESSAGE (
197                                 abs (ref_buffer[i] - check_buffer[i]) <= 65536,
198                                 ref << " differs from " << check << " at " << (ref_info.frames - N + i) << " of " << ref_info.frames
199                                 << "(" << ref_buffer[i] << " vs " << check_buffer[i] << ")"
200                                 );
201                 }
202
203                 N -= this_time;
204         }
205 }
206
207 void
208 check_mxf_audio_file (boost::filesystem::path ref, boost::filesystem::path check)
209 {
210         ASDCP::PCM::MXFReader ref_reader;
211         BOOST_REQUIRE (!ASDCP_FAILURE (ref_reader.OpenRead (ref.string().c_str())));
212
213         ASDCP::PCM::AudioDescriptor ref_desc;
214         BOOST_REQUIRE (!ASDCP_FAILURE (ref_reader.FillAudioDescriptor (ref_desc)));
215
216         ASDCP::PCM::MXFReader check_reader;
217         BOOST_REQUIRE (!ASDCP_FAILURE (check_reader.OpenRead (check.string().c_str())));
218
219         ASDCP::PCM::AudioDescriptor check_desc;
220         BOOST_REQUIRE (!ASDCP_FAILURE (check_reader.FillAudioDescriptor (check_desc)));
221
222         BOOST_REQUIRE_EQUAL (ref_desc.ContainerDuration, check_desc.ContainerDuration);
223
224         ASDCP::PCM::FrameBuffer ref_buffer (Kumu::Megabyte);
225         ASDCP::PCM::FrameBuffer check_buffer (Kumu::Megabyte);
226         for (size_t i = 0; i < ref_desc.ContainerDuration; ++i) {
227                 ref_reader.ReadFrame (i, ref_buffer, 0);
228                 check_reader.ReadFrame (i, check_buffer, 0);
229                 BOOST_REQUIRE (memcmp(ref_buffer.RoData(), check_buffer.RoData(), ref_buffer.Size()) == 0);
230         }
231 }
232
233 void
234 check_image (boost::filesystem::path ref, boost::filesystem::path check, double threshold)
235 {
236         using namespace MagickCore;
237
238         Magick::Image ref_image;
239         ref_image.read (ref.string ());
240         Magick::Image check_image;
241         check_image.read (check.string ());
242         /* XXX: this is a hack; we really want the ImageMagick call but GraphicsMagick doesn't have it;
243            this may cause random test failures on platforms that use GraphicsMagick.
244         */
245         double const dist = ref_image.compare(check_image, Magick::RootMeanSquaredErrorMetric);
246         BOOST_CHECK_MESSAGE (dist < threshold, ref << " differs from " << check << " " << dist);
247 }
248
249 void
250 check_file (boost::filesystem::path ref, boost::filesystem::path check)
251 {
252         uintmax_t N = boost::filesystem::file_size (ref);
253         BOOST_CHECK_EQUAL (N, boost::filesystem::file_size (check));
254         FILE* ref_file = fopen_boost (ref, "rb");
255         BOOST_CHECK (ref_file);
256         FILE* check_file = fopen_boost (check, "rb");
257         BOOST_CHECK (check_file);
258
259         int const buffer_size = 65536;
260         uint8_t* ref_buffer = new uint8_t[buffer_size];
261         uint8_t* check_buffer = new uint8_t[buffer_size];
262
263         string error = "File " + check.string() + " differs from reference " + ref.string();
264
265         while (N) {
266                 uintmax_t this_time = min (uintmax_t (buffer_size), N);
267                 size_t r = fread (ref_buffer, 1, this_time, ref_file);
268                 BOOST_CHECK_EQUAL (r, this_time);
269                 r = fread (check_buffer, 1, this_time, check_file);
270                 BOOST_CHECK_EQUAL (r, this_time);
271
272                 BOOST_CHECK_MESSAGE (memcmp (ref_buffer, check_buffer, this_time) == 0, error);
273                 if (memcmp (ref_buffer, check_buffer, this_time)) {
274                         break;
275                 }
276
277                 N -= this_time;
278         }
279
280         delete[] ref_buffer;
281         delete[] check_buffer;
282
283         fclose (ref_file);
284         fclose (check_file);
285 }
286
287 static void
288 note (dcp::NoteType t, string n)
289 {
290         if (t == dcp::DCP_ERROR) {
291                 cerr << n << "\n";
292         }
293 }
294
295 void
296 check_dcp (boost::filesystem::path ref, boost::filesystem::path check)
297 {
298         dcp::DCP ref_dcp (ref);
299         ref_dcp.read ();
300         dcp::DCP check_dcp (check);
301         check_dcp.read ();
302
303         dcp::EqualityOptions options;
304         options.max_mean_pixel_error = 5;
305         options.max_std_dev_pixel_error = 5;
306         options.max_audio_sample_error = 255;
307         options.cpl_annotation_texts_can_differ = true;
308         options.reel_annotation_texts_can_differ = true;
309         options.reel_hashes_can_differ = true;
310         options.issue_dates_can_differ = true;
311
312         BOOST_CHECK (ref_dcp.equals (check_dcp, options, boost::bind (note, _1, _2)));
313 }
314
315 void
316 check_xml (xmlpp::Element* ref, xmlpp::Element* test, list<string> ignore)
317 {
318         BOOST_CHECK_EQUAL (ref->get_name (), test->get_name ());
319         BOOST_CHECK_EQUAL (ref->get_namespace_prefix (), test->get_namespace_prefix ());
320
321         if (find (ignore.begin(), ignore.end(), ref->get_name()) != ignore.end ()) {
322                 return;
323         }
324
325         xmlpp::Element::NodeList ref_children = ref->get_children ();
326         xmlpp::Element::NodeList test_children = test->get_children ();
327         BOOST_REQUIRE_MESSAGE (
328                 ref_children.size() == test_children.size(),
329                 ref->get_name() << " has " << ref_children.size() << " or " << test_children.size() << " children"
330                 );
331
332         xmlpp::Element::NodeList::iterator k = ref_children.begin ();
333         xmlpp::Element::NodeList::iterator l = test_children.begin ();
334         while (k != ref_children.end ()) {
335
336                 /* XXX: should be doing xmlpp::EntityReference, xmlpp::XIncludeEnd, xmlpp::XIncludeStart */
337
338                 xmlpp::Element* ref_el = dynamic_cast<xmlpp::Element*> (*k);
339                 xmlpp::Element* test_el = dynamic_cast<xmlpp::Element*> (*l);
340                 BOOST_CHECK ((ref_el && test_el) || (!ref_el && !test_el));
341                 if (ref_el && test_el) {
342                         check_xml (ref_el, test_el, ignore);
343                 }
344
345                 xmlpp::ContentNode* ref_cn = dynamic_cast<xmlpp::ContentNode*> (*k);
346                 xmlpp::ContentNode* test_cn = dynamic_cast<xmlpp::ContentNode*> (*l);
347                 BOOST_CHECK ((ref_cn && test_cn) || (!ref_cn && !test_cn));
348                 if (ref_cn && test_cn) {
349                         BOOST_CHECK_EQUAL (ref_cn->get_content(), test_cn->get_content ());
350                 }
351
352                 ++k;
353                 ++l;
354         }
355
356         xmlpp::Element::AttributeList ref_attributes = ref->get_attributes ();
357         xmlpp::Element::AttributeList test_attributes = test->get_attributes ();
358         BOOST_CHECK_EQUAL (ref_attributes.size(), test_attributes.size ());
359
360         xmlpp::Element::AttributeList::const_iterator m = ref_attributes.begin();
361         xmlpp::Element::AttributeList::const_iterator n = test_attributes.begin();
362         while (m != ref_attributes.end ()) {
363                 BOOST_CHECK_EQUAL ((*m)->get_name(), (*n)->get_name());
364                 BOOST_CHECK_EQUAL ((*m)->get_value(), (*n)->get_value());
365
366                 ++m;
367                 ++n;
368         }
369 }
370
371 void
372 check_xml (boost::filesystem::path ref, boost::filesystem::path test, list<string> ignore)
373 {
374         xmlpp::DomParser* ref_parser = new xmlpp::DomParser (ref.string ());
375         xmlpp::Element* ref_root = ref_parser->get_document()->get_root_node ();
376         xmlpp::DomParser* test_parser = new xmlpp::DomParser (test.string ());
377         xmlpp::Element* test_root = test_parser->get_document()->get_root_node ();
378
379         check_xml (ref_root, test_root, ignore);
380 }
381
382 bool
383 wait_for_jobs ()
384 {
385         JobManager* jm = JobManager::instance ();
386         while (jm->work_to_do ()) {
387                 while (signal_manager->ui_idle ()) {}
388                 dcpomatic_sleep (1);
389         }
390
391         if (jm->errors ()) {
392                 int N = 0;
393                 for (list<shared_ptr<Job> >::iterator i = jm->_jobs.begin(); i != jm->_jobs.end(); ++i) {
394                         if ((*i)->finished_in_error ()) {
395                                 ++N;
396                         }
397                 }
398                 cerr << N << " errors.\n";
399
400                 for (list<shared_ptr<Job> >::iterator i = jm->_jobs.begin(); i != jm->_jobs.end(); ++i) {
401                         if ((*i)->finished_in_error ()) {
402                                 cerr << (*i)->name() << ":\n"
403                                      << "\tsummary: " << (*i)->error_summary () << "\n"
404                                      << "\tdetails: " << (*i)->error_details () << "\n";
405                         }
406                 }
407         }
408
409         while (signal_manager->ui_idle ()) {}
410
411         if (jm->errors ()) {
412                 JobManager::drop ();
413                 return true;
414         }
415
416         return false;
417 }
418
419 void
420 write_image (shared_ptr<const Image> image, boost::filesystem::path file, string format)
421 {
422         using namespace MagickCore;
423
424         Magick::Image m (image->size().width, image->size().height, format.c_str(), CharPixel, (void *) image->data()[0]);
425         m.write (file.string ());
426 }
427
428 void
429 check_ffmpeg (boost::filesystem::path ref, boost::filesystem::path check, int audio_tolerance)
430 {
431         int const r = system (String::compose("ffcmp -t %1 %2 %3", audio_tolerance, ref.string(), check.string()).c_str());
432         BOOST_REQUIRE_EQUAL (WEXITSTATUS(r), 0);
433 }
434
435 void
436 check_one_frame (boost::filesystem::path dcp_dir, int64_t index, boost::filesystem::path ref)
437 {
438         dcp::DCP dcp (dcp_dir);
439         dcp.read ();
440         shared_ptr<dcp::MonoPictureAsset> asset = dynamic_pointer_cast<dcp::MonoPictureAsset> (dcp.cpls().front()->reels().front()->main_picture()->asset());
441         BOOST_REQUIRE (asset);
442         shared_ptr<const dcp::MonoPictureFrame> frame = asset->start_read()->get_frame(index);
443         shared_ptr<const dcp::MonoPictureFrame> ref_frame (new dcp::MonoPictureFrame (ref));
444
445         shared_ptr<dcp::OpenJPEGImage> image = frame->xyz_image ();
446         shared_ptr<dcp::OpenJPEGImage> ref_image = ref_frame->xyz_image ();
447
448         BOOST_REQUIRE (image->size() == ref_image->size());
449
450         int off = 0;
451         for (int y = 0; y < ref_image->size().height; ++y) {
452                 for (int x = 0; x < ref_image->size().width; ++x) {
453                         BOOST_REQUIRE_EQUAL (ref_image->data(0)[off], image->data(0)[off]);
454                         BOOST_REQUIRE_EQUAL (ref_image->data(1)[off], image->data(1)[off]);
455                         BOOST_REQUIRE_EQUAL (ref_image->data(2)[off], image->data(2)[off]);
456                         ++off;
457                 }
458         }
459 }
460
461 boost::filesystem::path
462 dcp_file (shared_ptr<const Film> film, string prefix)
463 {
464         boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (film->dir(film->dcp_name()));
465         while (i != boost::filesystem::directory_iterator() && !boost::algorithm::starts_with (i->path().leaf().string(), prefix)) {
466                 ++i;
467         }
468
469         BOOST_REQUIRE (i != boost::filesystem::directory_iterator());
470         return i->path();
471 }
472
473 boost::filesystem::path
474 subtitle_file (shared_ptr<Film> film)
475 {
476         for (
477                 boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (film->directory().get() / film->dcp_name (false));
478                 i != boost::filesystem::directory_iterator ();
479                 ++i) {
480
481                 if (boost::filesystem::is_directory (i->path ())) {
482                         for (
483                                 boost::filesystem::directory_iterator j = boost::filesystem::directory_iterator (i->path ());
484                                 j != boost::filesystem::directory_iterator ();
485                                 ++j) {
486
487                                 if (boost::algorithm::starts_with (j->path().leaf().string(), "sub_")) {
488                                         return j->path();
489                                 }
490                         }
491                 }
492         }
493
494         BOOST_REQUIRE (false);
495         /* Remove warning */
496         return boost::filesystem::path("/");
497 }