12aaee4786625e95b8e352d0eb809aa97754b164
[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 "signer.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.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 DCP::DCP (boost::filesystem::path directory)
68         : _directory (directory)
69 {
70         if (!boost::filesystem::exists (directory)) {
71                 boost::filesystem::create_directories (directory);
72         }
73         
74         _directory = boost::filesystem::canonical (_directory);
75 }
76
77 template<class T> void
78 survivable_error (bool keep_going, dcp::DCP::ReadErrors* errors, T const & e)
79 {
80         if (keep_going) {
81                 if (errors) {
82                         errors->push_back (shared_ptr<T> (new T (e)));
83                 }
84         } else {
85                 throw e;
86         }
87 }
88
89 void
90 DCP::read (bool keep_going, ReadErrors* errors)
91 {
92         /* Read the ASSETMAP */
93         
94         boost::filesystem::path asset_map_file;
95         if (boost::filesystem::exists (_directory / "ASSETMAP")) {
96                 asset_map_file = _directory / "ASSETMAP";
97         } else if (boost::filesystem::exists (_directory / "ASSETMAP.xml")) {
98                 asset_map_file = _directory / "ASSETMAP.xml";
99         } else {
100                 boost::throw_exception (DCPReadError (String::compose ("could not find AssetMap file in `%1'", _directory.string())));
101         }
102
103         cxml::Document asset_map ("AssetMap");
104         asset_map.read_file (asset_map_file);
105         list<shared_ptr<cxml::Node> > asset_nodes = asset_map.node_child("AssetList")->node_children ("Asset");
106         map<string, boost::filesystem::path> paths;
107         BOOST_FOREACH (shared_ptr<cxml::Node> i, asset_nodes) {
108                 if (i->node_child("ChunkList")->node_children("Chunk").size() != 1) {
109                         boost::throw_exception (XMLError ("unsupported asset chunk count"));
110                 }
111                 string p = i->node_child("ChunkList")->node_child("Chunk")->string_child ("Path");
112                 if (starts_with (p, "file://")) {
113                         p = p.substr (7);
114                 }
115                 paths.insert (make_pair (i->string_child ("Id"), p));
116         }
117
118         /* Read all the assets from the asset map */
119         /* XXX: I think we should be looking at the PKL here to decide type, not
120            the extension of the file.
121         */
122
123         /* Make a list of non-CPL assets so that we can resolve the references
124            from the CPLs.
125         */
126         list<shared_ptr<Asset> > other_assets;
127         
128         for (map<string, boost::filesystem::path>::const_iterator i = paths.begin(); i != paths.end(); ++i) {
129                 boost::filesystem::path path = _directory / i->second;
130
131                 if (!boost::filesystem::exists (path)) {
132                         survivable_error (keep_going, errors, MissingAssetError (path));
133                         continue;
134                 }
135                 
136                 if (boost::filesystem::extension (path) == ".xml") {
137                         xmlpp::DomParser* p = new xmlpp::DomParser;
138                         try {
139                                 p->parse_file (path.string());
140                         } catch (std::exception& e) {
141                                 delete p;
142                                 continue;
143                         }
144                         
145                         string const root = p->get_document()->get_root_node()->get_name ();
146                         delete p;
147                         
148                         if (root == "CompositionPlaylist") {
149                                 _cpls.push_back (shared_ptr<CPL> (new CPL (path)));
150                         } else if (root == "DCSubtitle") {
151                                 other_assets.push_back (shared_ptr<InteropSubtitleAsset> (new InteropSubtitleAsset (path)));
152                         }
153                 } else if (boost::filesystem::extension (path) == ".mxf") {
154                         ASDCP::EssenceType_t type;
155                         if (ASDCP::EssenceType (path.string().c_str(), type) != ASDCP::RESULT_OK) {
156                                 throw DCPReadError ("Could not find essence type");
157                         }
158                         switch (type) {
159                                 case ASDCP::ESS_UNKNOWN:
160                                 case ASDCP::ESS_MPEG2_VES:
161                                         throw DCPReadError ("MPEG2 video essences are not supported");
162                                 case ASDCP::ESS_JPEG_2000:
163                                         other_assets.push_back (shared_ptr<MonoPictureAsset> (new MonoPictureAsset (path)));
164                                         break;
165                                 case ASDCP::ESS_PCM_24b_48k:
166                                 case ASDCP::ESS_PCM_24b_96k:
167                                         other_assets.push_back (shared_ptr<SoundAsset> (new SoundAsset (path)));
168                                         break;
169                                 case ASDCP::ESS_JPEG_2000_S:
170                                         other_assets.push_back (shared_ptr<StereoPictureAsset> (new StereoPictureAsset (path)));
171                                         break;
172                                 case ASDCP::ESS_TIMED_TEXT:
173                                         other_assets.push_back (shared_ptr<SMPTESubtitleAsset> (new SMPTESubtitleAsset (path)));
174                                         break;
175                                 default:
176                                         throw DCPReadError ("Unknown MXF essence type");
177                         }
178                 } else if (boost::filesystem::extension (path) == ".ttf") {
179                         other_assets.push_back (shared_ptr<Font> (new Font (path)));
180                 }
181         }
182
183         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
184                 i->resolve_refs (list_of_type<Asset, Object> (other_assets));
185         }
186 }
187
188 bool
189 DCP::equals (DCP const & other, EqualityOptions opt, NoteHandler note) const
190 {
191         list<shared_ptr<CPL> > a = cpls ();
192         list<shared_ptr<CPL> > b = other.cpls ();
193         
194         if (a.size() != b.size()) {
195                 note (DCP_ERROR, String::compose ("CPL counts differ: %1 vs %2", a.size(), b.size()));
196                 return false;
197         }
198
199         bool r = true;
200
201         BOOST_FOREACH (shared_ptr<CPL> i, a) {
202                 list<shared_ptr<CPL> >::const_iterator j = b.begin ();
203                 while (j != b.end() && !(*j)->equals (i, opt, note)) {
204                         ++j;
205                 }
206
207                 if (j == b.end ()) {
208                         r = false;
209                 }
210         }
211
212         return r;
213 }
214
215 void
216 DCP::add (boost::shared_ptr<CPL> cpl)
217 {
218         _cpls.push_back (cpl);
219 }
220
221 bool
222 DCP::encrypted () const
223 {
224         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
225                 if (i->encrypted ()) {
226                         return true;
227                 }
228         }
229
230         return false;
231 }
232
233 void
234 DCP::add (DecryptedKDM const & kdm)
235 {
236         list<DecryptedKDMKey> keys = kdm.keys ();
237
238         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
239                 BOOST_FOREACH (DecryptedKDMKey const & j, kdm.keys ()) {
240                         if (j.cpl_id() == i->id()) {
241                                 i->add (kdm);
242                         }                               
243                 }
244         }
245 }
246
247 boost::filesystem::path
248 DCP::write_pkl (Standard standard, string pkl_uuid, XMLMetadata metadata, shared_ptr<const Signer> signer) const
249 {
250         boost::filesystem::path p = _directory;
251         p /= String::compose ("pkl_%1.xml", pkl_uuid);
252
253         xmlpp::Document doc;
254         xmlpp::Element* pkl;
255         if (standard == INTEROP) {
256                 pkl = doc.create_root_node("PackingList", "http://www.digicine.com/PROTO-ASDCP-PKL-20040311#");
257         } else {
258                 pkl = doc.create_root_node("PackingList", "http://www.smpte-ra.org/schemas/429-8/2007/PKL");
259         }
260         
261         if (signer) {
262                 pkl->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
263         }
264
265         pkl->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
266
267         /* XXX: this is a bit of a hack */
268         DCP_ASSERT (cpls().size() > 0);
269         pkl->add_child("AnnotationText")->add_child_text (cpls().front()->annotation_text ());
270         
271         pkl->add_child("IssueDate")->add_child_text (metadata.issue_date);
272         pkl->add_child("Issuer")->add_child_text (metadata.issuer);
273         pkl->add_child("Creator")->add_child_text (metadata.creator);
274
275         xmlpp::Element* asset_list = pkl->add_child("AssetList");
276         BOOST_FOREACH (shared_ptr<Asset> i, assets ()) {
277                 i->write_to_pkl (asset_list, standard);
278         }
279
280         if (signer) {
281                 signer->sign (pkl, standard);
282         }
283                 
284         doc.write_to_file (p.string (), "UTF-8");
285         return p.string ();
286 }
287
288 /** Write the VOLINDEX file.
289  *  @param standard DCP standard to use (INTEROP or SMPTE)
290  */
291 void
292 DCP::write_volindex (Standard standard) const
293 {
294         boost::filesystem::path p = _directory;
295         switch (standard) {
296         case INTEROP:
297                 p /= "VOLINDEX";
298                 break;
299         case SMPTE:
300                 p /= "VOLINDEX.xml";
301                 break;
302         default:
303                 DCP_ASSERT (false);
304         }
305
306         xmlpp::Document doc;
307         xmlpp::Element* root;
308
309         switch (standard) {
310         case INTEROP:
311                 root = doc.create_root_node ("VolumeIndex", "http://www.digicine.com/PROTO-ASDCP-AM-20040311#");
312                 break;
313         case SMPTE:
314                 root = doc.create_root_node ("VolumeIndex", "http://www.smpte-ra.org/schemas/429-9/2007/AM");
315                 break;
316         default:
317                 DCP_ASSERT (false);
318         }
319         
320         root->add_child("Index")->add_child_text ("1");
321         doc.write_to_file (p.string (), "UTF-8");
322 }
323
324 void
325 DCP::write_assetmap (Standard standard, string pkl_uuid, int pkl_length, XMLMetadata metadata) const
326 {
327         boost::filesystem::path p = _directory;
328         
329         switch (standard) {
330         case INTEROP:
331                 p /= "ASSETMAP";
332                 break;
333         case SMPTE:
334                 p /= "ASSETMAP.xml";
335                 break;
336         default:
337                 DCP_ASSERT (false);
338         }
339
340         xmlpp::Document doc;
341         xmlpp::Element* root;
342
343         switch (standard) {
344         case INTEROP:
345                 root = doc.create_root_node ("AssetMap", "http://www.digicine.com/PROTO-ASDCP-AM-20040311#");
346                 break;
347         case SMPTE:
348                 root = doc.create_root_node ("AssetMap", "http://www.smpte-ra.org/schemas/429-9/2007/AM");
349                 break;
350         default:
351                 DCP_ASSERT (false);
352         }
353
354         root->add_child("Id")->add_child_text ("urn:uuid:" + make_uuid());
355         root->add_child("AnnotationText")->add_child_text ("Created by " + metadata.creator);
356
357         switch (standard) {
358         case INTEROP:
359                 root->add_child("VolumeCount")->add_child_text ("1");
360                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
361                 root->add_child("Issuer")->add_child_text (metadata.issuer);
362                 root->add_child("Creator")->add_child_text (metadata.creator);
363                 break;
364         case SMPTE:
365                 root->add_child("Creator")->add_child_text (metadata.creator);
366                 root->add_child("VolumeCount")->add_child_text ("1");
367                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
368                 root->add_child("Issuer")->add_child_text (metadata.issuer);
369                 break;
370         default:
371                 DCP_ASSERT (false);
372         }
373                 
374         xmlpp::Node* asset_list = root->add_child ("AssetList");
375
376         xmlpp::Node* asset = asset_list->add_child ("Asset");
377         asset->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
378         asset->add_child("PackingList")->add_child_text ("true");
379         xmlpp::Node* chunk_list = asset->add_child ("ChunkList");
380         xmlpp::Node* chunk = chunk_list->add_child ("Chunk");
381         chunk->add_child("Path")->add_child_text ("pkl_" + pkl_uuid + ".xml");
382         chunk->add_child("VolumeIndex")->add_child_text ("1");
383         chunk->add_child("Offset")->add_child_text ("0");
384         chunk->add_child("Length")->add_child_text (raw_convert<string> (pkl_length));
385
386         BOOST_FOREACH (shared_ptr<Asset> i, assets ()) {
387                 i->write_to_assetmap (asset_list, _directory);
388         }
389
390         /* This must not be the _formatted version otherwise signature digests will be wrong */
391         doc.write_to_file (p.string (), "UTF-8");
392 }
393
394 /** Write all the XML files for this DCP.
395  *  @param standand INTEROP or SMPTE.
396  *  @param metadata Metadata to use for PKL and asset map files.
397  *  @param signer Signer to use, or 0.
398  */
399 void
400 DCP::write_xml (
401         Standard standard,
402         XMLMetadata metadata,
403         shared_ptr<const Signer> signer
404         )
405 {
406         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
407                 string const filename = "cpl_" + i->id() + ".xml";
408                 i->write_xml (_directory / filename, standard, signer);
409         }
410
411         string const pkl_uuid = make_uuid ();
412         boost::filesystem::path const pkl_path = write_pkl (standard, pkl_uuid, metadata, signer);
413         
414         write_volindex (standard);
415         write_assetmap (standard, pkl_uuid, boost::filesystem::file_size (pkl_path), metadata);
416 }
417
418 list<shared_ptr<CPL> >
419 DCP::cpls () const
420 {
421         return _cpls;
422 }
423
424 /** @return All assest (including CPLs) */
425 list<shared_ptr<Asset> >
426 DCP::assets () const
427 {
428         list<shared_ptr<Asset> > assets;
429         BOOST_FOREACH (shared_ptr<CPL> i, cpls ()) {
430                 assets.push_back (i);
431                 BOOST_FOREACH (shared_ptr<const ReelAsset> j, i->reel_assets ()) {
432                         shared_ptr<Asset> o = j->asset_ref().object ();
433                         assets.push_back (o);
434                         /* More Interop special-casing */
435                         shared_ptr<InteropSubtitleAsset> sub = dynamic_pointer_cast<InteropSubtitleAsset> (o);
436                         if (sub) {
437                                 sub->add_font_assets (assets);
438                         }
439                 }
440         }
441
442         return assets;
443 }