Merge branch '1.0' of git.carlh.net:git/libdcp into 1.0
[libdcp.git] / src / dcp.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file  src/dcp.cc
21  *  @brief DCP class.
22  */
23
24 #include "raw_convert.h"
25 #include "dcp.h"
26 #include "sound_asset.h"
27 #include "picture_asset.h"
28 #include "interop_subtitle_asset.h"
29 #include "smpte_subtitle_asset.h"
30 #include "mono_picture_asset.h"
31 #include "stereo_picture_asset.h"
32 #include "reel_subtitle_asset.h"
33 #include "util.h"
34 #include "metadata.h"
35 #include "exceptions.h"
36 #include "cpl.h"
37 #include "certificate_chain.h"
38 #include "compose.hpp"
39 #include "AS_DCP.h"
40 #include "decrypted_kdm.h"
41 #include "decrypted_kdm_key.h"
42 #include "dcp_assert.h"
43 #include "reel_asset.h"
44 #include "font_asset.h"
45 #include <xmlsec/xmldsig.h>
46 #include <xmlsec/app.h>
47 #include <libxml++/libxml++.h>
48 #include <boost/filesystem.hpp>
49 #include <boost/algorithm/string.hpp>
50 #include <boost/foreach.hpp>
51 #include <iostream>
52
53 using std::string;
54 using std::list;
55 using std::cout;
56 using std::ostream;
57 using std::make_pair;
58 using std::map;
59 using std::cout;
60 using std::cerr;
61 using std::exception;
62 using boost::shared_ptr;
63 using boost::dynamic_pointer_cast;
64 using boost::algorithm::starts_with;
65 using namespace dcp;
66
67 static string const assetmap_interop_ns = "http://www.digicine.com/PROTO-ASDCP-AM-20040311#";
68 static string const assetmap_smpte_ns   = "http://www.smpte-ra.org/schemas/429-9/2007/AM";
69 static string const pkl_interop_ns      = "http://www.digicine.com/PROTO-ASDCP-PKL-20040311#";
70 static string const pkl_smpte_ns        = "http://www.smpte-ra.org/schemas/429-8/2007/PKL";
71 static string const volindex_interop_ns = "http://www.digicine.com/PROTO-ASDCP-AM-20040311#";
72 static string const volindex_smpte_ns   = "http://www.smpte-ra.org/schemas/429-9/2007/AM";
73
74 DCP::DCP (boost::filesystem::path directory)
75         : _directory (directory)
76 {
77         if (!boost::filesystem::exists (directory)) {
78                 boost::filesystem::create_directories (directory);
79         }
80
81         _directory = boost::filesystem::canonical (_directory);
82 }
83
84 /** Call this instead of throwing an exception if the error can be tolerated */
85 template<class T> void
86 survivable_error (bool keep_going, dcp::DCP::ReadErrors* errors, T const & e)
87 {
88         if (keep_going) {
89                 if (errors) {
90                         errors->push_back (shared_ptr<T> (new T (e)));
91                 }
92         } else {
93                 throw e;
94         }
95 }
96
97 void
98 DCP::read (bool keep_going, ReadErrors* errors, bool ignore_incorrect_picture_mxf_type)
99 {
100         /* Read the ASSETMAP */
101
102         boost::filesystem::path asset_map_file;
103         if (boost::filesystem::exists (_directory / "ASSETMAP")) {
104                 asset_map_file = _directory / "ASSETMAP";
105         } else if (boost::filesystem::exists (_directory / "ASSETMAP.xml")) {
106                 asset_map_file = _directory / "ASSETMAP.xml";
107         } else {
108                 boost::throw_exception (DCPReadError (String::compose ("could not find AssetMap file in `%1'", _directory.string())));
109         }
110
111         cxml::Document asset_map ("AssetMap");
112
113         asset_map.read_file (asset_map_file);
114         if (asset_map.namespace_uri() == assetmap_interop_ns) {
115                 _standard = INTEROP;
116         } else if (asset_map.namespace_uri() == assetmap_smpte_ns) {
117                 _standard = SMPTE;
118         } else {
119                 boost::throw_exception (XMLError ("Unrecognised Assetmap namespace " + asset_map.namespace_uri()));
120         }
121
122         list<shared_ptr<cxml::Node> > asset_nodes = asset_map.node_child("AssetList")->node_children ("Asset");
123         map<string, boost::filesystem::path> paths;
124         BOOST_FOREACH (shared_ptr<cxml::Node> i, asset_nodes) {
125                 if (i->node_child("ChunkList")->node_children("Chunk").size() != 1) {
126                         boost::throw_exception (XMLError ("unsupported asset chunk count"));
127                 }
128                 string p = i->node_child("ChunkList")->node_child("Chunk")->string_child ("Path");
129                 if (starts_with (p, "file://")) {
130                         p = p.substr (7);
131                 }
132                 paths.insert (make_pair (remove_urn_uuid (i->string_child ("Id")), p));
133         }
134
135         /* Read all the assets from the asset map */
136         /* XXX: I think we should be looking at the PKL here to decide type, not
137            the extension of the file.
138         */
139
140         /* Make a list of non-CPL assets so that we can resolve the references
141            from the CPLs.
142         */
143         list<shared_ptr<Asset> > other_assets;
144
145         for (map<string, boost::filesystem::path>::const_iterator i = paths.begin(); i != paths.end(); ++i) {
146                 boost::filesystem::path path = _directory / i->second;
147
148                 if (!boost::filesystem::exists (path)) {
149                         survivable_error (keep_going, errors, MissingAssetError (path));
150                         continue;
151                 }
152
153                 if (boost::filesystem::extension (path) == ".xml") {
154                         xmlpp::DomParser* p = new xmlpp::DomParser;
155                         try {
156                                 p->parse_file (path.string());
157                         } catch (std::exception& e) {
158                                 delete p;
159                                 continue;
160                         }
161
162                         string const root = p->get_document()->get_root_node()->get_name ();
163                         delete p;
164
165                         if (root == "CompositionPlaylist") {
166                                 shared_ptr<CPL> cpl (new CPL (path));
167                                 if (_standard && cpl->standard() && cpl->standard().get() != _standard.get()) {
168                                         survivable_error (keep_going, errors, MismatchedStandardError ());
169                                 }
170                                 _cpls.push_back (cpl);
171                         } else if (root == "DCSubtitle") {
172                                 if (_standard && _standard.get() == SMPTE) {
173                                         survivable_error (keep_going, errors, MismatchedStandardError ());
174                                 }
175                                 other_assets.push_back (shared_ptr<InteropSubtitleAsset> (new InteropSubtitleAsset (path)));
176                         }
177                 } else if (boost::filesystem::extension (path) == ".mxf") {
178
179                         /* XXX: asdcplib does not appear to support discovery of read MXFs standard
180                            (Interop / SMPTE)
181                         */
182
183                         ASDCP::EssenceType_t type;
184                         if (ASDCP::EssenceType (path.string().c_str(), type) != ASDCP::RESULT_OK) {
185                                 throw DCPReadError ("Could not find essence type");
186                         }
187                         switch (type) {
188                                 case ASDCP::ESS_UNKNOWN:
189                                 case ASDCP::ESS_MPEG2_VES:
190                                         throw DCPReadError ("MPEG2 video essences are not supported");
191                                 case ASDCP::ESS_JPEG_2000:
192                                         try {
193                                                 other_assets.push_back (shared_ptr<MonoPictureAsset> (new MonoPictureAsset (path)));
194                                         } catch (dcp::MXFFileError& e) {
195                                                 if (ignore_incorrect_picture_mxf_type && e.number() == ASDCP::RESULT_SFORMAT) {
196                                                         /* Tried to load it as mono but the error says it's stereo; try that instead */
197                                                         other_assets.push_back (shared_ptr<StereoPictureAsset> (new StereoPictureAsset (path)));
198                                                 } else {
199                                                         throw;
200                                                 }
201                                         }
202                                         break;
203                                 case ASDCP::ESS_PCM_24b_48k:
204                                 case ASDCP::ESS_PCM_24b_96k:
205                                         other_assets.push_back (shared_ptr<SoundAsset> (new SoundAsset (path)));
206                                         break;
207                                 case ASDCP::ESS_JPEG_2000_S:
208                                         other_assets.push_back (shared_ptr<StereoPictureAsset> (new StereoPictureAsset (path)));
209                                         break;
210                                 case ASDCP::ESS_TIMED_TEXT:
211                                         other_assets.push_back (shared_ptr<SMPTESubtitleAsset> (new SMPTESubtitleAsset (path)));
212                                         break;
213                                 default:
214                                         throw DCPReadError ("Unknown MXF essence type");
215                         }
216                 } else if (boost::filesystem::extension (path) == ".ttf") {
217                         other_assets.push_back (shared_ptr<FontAsset> (new FontAsset (i->first, path)));
218                 }
219         }
220
221         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
222                 i->resolve_refs (other_assets);
223         }
224 }
225
226 void
227 DCP::resolve_refs (list<shared_ptr<Asset> > assets)
228 {
229         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
230                 i->resolve_refs (assets);
231         }
232 }
233
234 bool
235 DCP::equals (DCP const & other, EqualityOptions opt, NoteHandler note) const
236 {
237         list<shared_ptr<CPL> > a = cpls ();
238         list<shared_ptr<CPL> > b = other.cpls ();
239
240         if (a.size() != b.size()) {
241                 note (DCP_ERROR, String::compose ("CPL counts differ: %1 vs %2", a.size(), b.size()));
242                 return false;
243         }
244
245         bool r = true;
246
247         BOOST_FOREACH (shared_ptr<CPL> i, a) {
248                 list<shared_ptr<CPL> >::const_iterator j = b.begin ();
249                 while (j != b.end() && !(*j)->equals (i, opt, note)) {
250                         ++j;
251                 }
252
253                 if (j == b.end ()) {
254                         r = false;
255                 }
256         }
257
258         return r;
259 }
260
261 void
262 DCP::add (boost::shared_ptr<CPL> cpl)
263 {
264         _cpls.push_back (cpl);
265 }
266
267 bool
268 DCP::encrypted () const
269 {
270         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
271                 if (i->encrypted ()) {
272                         return true;
273                 }
274         }
275
276         return false;
277 }
278
279 void
280 DCP::add (DecryptedKDM const & kdm)
281 {
282         list<DecryptedKDMKey> keys = kdm.keys ();
283
284         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
285                 BOOST_FOREACH (DecryptedKDMKey const & j, kdm.keys ()) {
286                         if (j.cpl_id() == i->id()) {
287                                 i->add (kdm);
288                         }
289                 }
290         }
291 }
292
293 boost::filesystem::path
294 DCP::write_pkl (Standard standard, string pkl_uuid, XMLMetadata metadata, shared_ptr<const CertificateChain> signer) const
295 {
296         boost::filesystem::path p = _directory;
297         p /= String::compose ("pkl_%1.xml", pkl_uuid);
298
299         xmlpp::Document doc;
300         xmlpp::Element* pkl;
301         if (standard == INTEROP) {
302                 pkl = doc.create_root_node("PackingList", pkl_interop_ns);
303         } else {
304                 pkl = doc.create_root_node("PackingList", pkl_smpte_ns);
305         }
306
307         if (signer) {
308                 pkl->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
309         }
310
311         pkl->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
312
313         /* XXX: this is a bit of a hack */
314         DCP_ASSERT (cpls().size() > 0);
315         pkl->add_child("AnnotationText")->add_child_text (cpls().front()->annotation_text ());
316
317         pkl->add_child("IssueDate")->add_child_text (metadata.issue_date);
318         pkl->add_child("Issuer")->add_child_text (metadata.issuer);
319         pkl->add_child("Creator")->add_child_text (metadata.creator);
320
321         xmlpp::Element* asset_list = pkl->add_child("AssetList");
322         BOOST_FOREACH (shared_ptr<Asset> i, assets ()) {
323                 i->write_to_pkl (asset_list, _directory, standard);
324         }
325
326         if (signer) {
327                 signer->sign (pkl, standard);
328         }
329
330         doc.write_to_file (p.string (), "UTF-8");
331         return p.string ();
332 }
333
334 /** Write the VOLINDEX file.
335  *  @param standard DCP standard to use (INTEROP or SMPTE)
336  */
337 void
338 DCP::write_volindex (Standard standard) const
339 {
340         boost::filesystem::path p = _directory;
341         switch (standard) {
342         case INTEROP:
343                 p /= "VOLINDEX";
344                 break;
345         case SMPTE:
346                 p /= "VOLINDEX.xml";
347                 break;
348         default:
349                 DCP_ASSERT (false);
350         }
351
352         xmlpp::Document doc;
353         xmlpp::Element* root;
354
355         switch (standard) {
356         case INTEROP:
357                 root = doc.create_root_node ("VolumeIndex", volindex_interop_ns);
358                 break;
359         case SMPTE:
360                 root = doc.create_root_node ("VolumeIndex", volindex_smpte_ns);
361                 break;
362         default:
363                 DCP_ASSERT (false);
364         }
365
366         root->add_child("Index")->add_child_text ("1");
367         doc.write_to_file (p.string (), "UTF-8");
368 }
369
370 void
371 DCP::write_assetmap (Standard standard, string pkl_uuid, int pkl_length, XMLMetadata metadata) const
372 {
373         boost::filesystem::path p = _directory;
374
375         switch (standard) {
376         case INTEROP:
377                 p /= "ASSETMAP";
378                 break;
379         case SMPTE:
380                 p /= "ASSETMAP.xml";
381                 break;
382         default:
383                 DCP_ASSERT (false);
384         }
385
386         xmlpp::Document doc;
387         xmlpp::Element* root;
388
389         switch (standard) {
390         case INTEROP:
391                 root = doc.create_root_node ("AssetMap", assetmap_interop_ns);
392                 break;
393         case SMPTE:
394                 root = doc.create_root_node ("AssetMap", assetmap_smpte_ns);
395                 break;
396         default:
397                 DCP_ASSERT (false);
398         }
399
400         root->add_child("Id")->add_child_text ("urn:uuid:" + make_uuid());
401         root->add_child("AnnotationText")->add_child_text ("Created by " + metadata.creator);
402
403         switch (standard) {
404         case INTEROP:
405                 root->add_child("VolumeCount")->add_child_text ("1");
406                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
407                 root->add_child("Issuer")->add_child_text (metadata.issuer);
408                 root->add_child("Creator")->add_child_text (metadata.creator);
409                 break;
410         case SMPTE:
411                 root->add_child("Creator")->add_child_text (metadata.creator);
412                 root->add_child("VolumeCount")->add_child_text ("1");
413                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
414                 root->add_child("Issuer")->add_child_text (metadata.issuer);
415                 break;
416         default:
417                 DCP_ASSERT (false);
418         }
419
420         xmlpp::Node* asset_list = root->add_child ("AssetList");
421
422         xmlpp::Node* asset = asset_list->add_child ("Asset");
423         asset->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
424         asset->add_child("PackingList")->add_child_text ("true");
425         xmlpp::Node* chunk_list = asset->add_child ("ChunkList");
426         xmlpp::Node* chunk = chunk_list->add_child ("Chunk");
427         chunk->add_child("Path")->add_child_text ("pkl_" + pkl_uuid + ".xml");
428         chunk->add_child("VolumeIndex")->add_child_text ("1");
429         chunk->add_child("Offset")->add_child_text ("0");
430         chunk->add_child("Length")->add_child_text (raw_convert<string> (pkl_length));
431
432         BOOST_FOREACH (shared_ptr<Asset> i, assets ()) {
433                 i->write_to_assetmap (asset_list, _directory);
434         }
435
436         /* This must not be the _formatted version otherwise signature digests will be wrong */
437         doc.write_to_file (p.string (), "UTF-8");
438 }
439
440 /** Write all the XML files for this DCP.
441  *  @param standand INTEROP or SMPTE.
442  *  @param metadata Metadata to use for PKL and asset map files.
443  *  @param signer Signer to use, or 0.
444  */
445 void
446 DCP::write_xml (
447         Standard standard,
448         XMLMetadata metadata,
449         shared_ptr<const CertificateChain> signer
450         )
451 {
452         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
453                 string const filename = "cpl_" + i->id() + ".xml";
454                 i->write_xml (_directory / filename, standard, signer);
455         }
456
457         string const pkl_uuid = make_uuid ();
458         boost::filesystem::path const pkl_path = write_pkl (standard, pkl_uuid, metadata, signer);
459
460         write_volindex (standard);
461         write_assetmap (standard, pkl_uuid, boost::filesystem::file_size (pkl_path), metadata);
462 }
463
464 list<shared_ptr<CPL> >
465 DCP::cpls () const
466 {
467         return _cpls;
468 }
469
470 /** @return All assets (including CPLs) */
471 list<shared_ptr<Asset> >
472 DCP::assets () const
473 {
474         list<shared_ptr<Asset> > assets;
475         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
476                 assets.push_back (i);
477                 BOOST_FOREACH (shared_ptr<const ReelAsset> j, i->reel_assets ()) {
478                         shared_ptr<Asset> o = j->asset_ref().asset ();
479                         assets.push_back (o);
480                         /* More Interop special-casing */
481                         shared_ptr<InteropSubtitleAsset> sub = dynamic_pointer_cast<InteropSubtitleAsset> (o);
482                         if (sub) {
483                                 sub->add_font_assets (assets);
484                         }
485                 }
486         }
487
488         return assets;
489 }