Assorted test fixes.
[libdcp.git] / src / dcp.cc
1 /*
2     Copyright (C) 2012-2014 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 "dcp.h"
25 #include "sound_mxf.h"
26 #include "picture_mxf.h"
27 #include "subtitle_content.h"
28 #include "mono_picture_mxf.h"
29 #include "stereo_picture_mxf.h"
30 #include "util.h"
31 #include "metadata.h"
32 #include "exceptions.h"
33 #include "reel.h"
34 #include "cpl.h"
35 #include "signer.h"
36 #include "compose.hpp"
37 #include "AS_DCP.h"
38 #include "decrypted_kdm.h"
39 #include "decrypted_kdm_key.h"
40 #include <xmlsec/xmldsig.h>
41 #include <xmlsec/app.h>
42 #include <libxml++/libxml++.h>
43 #include <boost/filesystem.hpp>
44 #include <boost/algorithm/string.hpp>
45 #include <boost/lexical_cast.hpp>
46 #include <sstream>
47 #include <iomanip>
48 #include <cassert>
49 #include <iostream>
50
51 using std::string;
52 using std::list;
53 using std::stringstream;
54 using std::ostream;
55 using std::make_pair;
56 using std::map;
57 using std::cout;
58 using std::exception;
59 using boost::shared_ptr;
60 using boost::lexical_cast;
61 using boost::algorithm::starts_with;
62 using namespace dcp;
63
64 DCP::DCP (boost::filesystem::path directory)
65         : _directory (directory)
66 {
67         boost::filesystem::create_directories (directory);
68         _directory = boost::filesystem::canonical (_directory);
69 }
70
71 template<class T> void
72 survivable_error (bool keep_going, dcp::DCP::ReadErrors* errors, T const & e)
73 {
74         if (keep_going) {
75                 if (errors) {
76                         errors->push_back (shared_ptr<T> (new T (e)));
77                 }
78         } else {
79                 throw e;
80         }
81 }
82
83 void
84 DCP::read (bool keep_going, ReadErrors* errors)
85 {
86         /* Read the ASSETMAP */
87         
88         boost::filesystem::path asset_map_file;
89         if (boost::filesystem::exists (_directory / "ASSETMAP")) {
90                 asset_map_file = _directory / "ASSETMAP";
91         } else if (boost::filesystem::exists (_directory / "ASSETMAP.xml")) {
92                 asset_map_file = _directory / "ASSETMAP.xml";
93         } else {
94                 boost::throw_exception (DCPReadError (String::compose ("could not find AssetMap file `%1'", asset_map_file.string())));
95         }
96
97         cxml::Document asset_map ("AssetMap");
98         asset_map.read_file (asset_map_file);
99         list<shared_ptr<cxml::Node> > asset_nodes = asset_map.node_child("AssetList")->node_children ("Asset");
100         map<string, boost::filesystem::path> paths;
101         for (list<shared_ptr<cxml::Node> >::const_iterator i = asset_nodes.begin(); i != asset_nodes.end(); ++i) {
102                 if ((*i)->node_child("ChunkList")->node_children("Chunk").size() != 1) {
103                         boost::throw_exception (XMLError ("unsupported asset chunk count"));
104                 }
105                 string p = (*i)->node_child("ChunkList")->node_child("Chunk")->string_child ("Path");
106                 if (starts_with (p, "file://")) {
107                         p = p.substr (7);
108                 }
109                 paths.insert (make_pair ((*i)->string_child ("Id"), p));
110         }
111
112         /* Read all the assets from the asset map */
113         for (map<string, boost::filesystem::path>::const_iterator i = paths.begin(); i != paths.end(); ++i) {
114                 boost::filesystem::path path = _directory / i->second;
115
116                 if (!boost::filesystem::exists (path)) {
117                         survivable_error (keep_going, errors, MissingAssetError (path));
118                         continue;
119                 }
120                 
121                 if (boost::algorithm::ends_with (path.string(), ".xml")) {
122                         xmlpp::DomParser* p = new xmlpp::DomParser;
123                         try {
124                                 p->parse_file (path.string());
125                         } catch (std::exception& e) {
126                                 delete p;
127                                 continue;
128                         }
129                         
130                         string const root = p->get_document()->get_root_node()->get_name ();
131                         delete p;
132                         
133                         if (root == "CompositionPlaylist") {
134                                 _assets.push_back (shared_ptr<CPL> (new CPL (path)));
135                         } else if (root == "DCSubtitle") {
136                                 _assets.push_back (shared_ptr<SubtitleContent> (new SubtitleContent (path)));
137                         }
138                 } else if (boost::algorithm::ends_with (path.string(), ".mxf")) {
139                         ASDCP::EssenceType_t type;
140                         if (ASDCP::EssenceType (path.string().c_str(), type) != ASDCP::RESULT_OK) {
141                                 throw DCPReadError ("Could not find essence type");
142                         }
143                         switch (type) {
144                                 case ASDCP::ESS_UNKNOWN:
145                                 case ASDCP::ESS_MPEG2_VES:
146                                         throw DCPReadError ("MPEG2 video essences are not supported");
147                                 case ASDCP::ESS_JPEG_2000:
148                                         _assets.push_back (shared_ptr<MonoPictureMXF> (new MonoPictureMXF (path)));
149                                         break;
150                                 case ASDCP::ESS_PCM_24b_48k:
151                                 case ASDCP::ESS_PCM_24b_96k:
152                                         _assets.push_back (shared_ptr<SoundMXF> (new SoundMXF (path)));
153                                         break;
154                                 case ASDCP::ESS_JPEG_2000_S:
155                                         _assets.push_back (shared_ptr<StereoPictureMXF> (new StereoPictureMXF (path)));
156                                         break;
157                                 default:
158                                         throw DCPReadError ("Unknown MXF essence type");
159                                 }
160                 }
161         }
162
163         list<shared_ptr<CPL> > cpl = cpls ();
164         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
165                 (*i)->resolve_refs (list_of_type<Asset, Object> (assets ()));
166         }
167 }
168
169 bool
170 DCP::equals (DCP const & other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
171 {
172         if (_assets.size() != other._assets.size()) {
173                 note (ERROR, String::compose ("Asset counts differ: %1 vs %2", _assets.size(), other._assets.size()));
174                 return false;
175         }
176
177         list<shared_ptr<Asset> >::const_iterator a = _assets.begin ();
178         list<shared_ptr<Asset> >::const_iterator b = other._assets.begin ();
179
180         while (a != _assets.end ()) {
181                 if (!(*a)->equals (*b, opt, note)) {
182                         return false;
183                 }
184                 ++a;
185                 ++b;
186         }
187
188         return true;
189 }
190
191 void
192 DCP::add (boost::shared_ptr<Asset> asset)
193 {
194         _assets.push_back (asset);
195 }
196
197 class AssetComparator
198 {
199 public:
200         bool operator() (shared_ptr<const Content> a, shared_ptr<const Content> b) {
201                 return a->id() < b->id();
202         }
203 };
204
205 bool
206 DCP::encrypted () const
207 {
208         list<shared_ptr<CPL> > cpl = cpls ();
209         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
210                 if ((*i)->encrypted ()) {
211                         return true;
212                 }
213         }
214
215         return false;
216 }
217
218 void
219 DCP::add (DecryptedKDM const & kdm)
220 {
221         list<DecryptedKDMKey> keys = kdm.keys ();
222         list<shared_ptr<CPL> > cpl = cpls ();
223         
224         for (list<shared_ptr<CPL> >::iterator i = cpl.begin(); i != cpl.end(); ++i) {
225                 for (list<DecryptedKDMKey>::iterator j = keys.begin(); j != keys.end(); ++j) {
226                         if (j->cpl_id() == (*i)->id()) {
227                                 (*i)->add (kdm);
228                         }                               
229                 }
230         }
231 }
232
233 boost::filesystem::path
234 DCP::write_pkl (Standard standard, string pkl_uuid, XMLMetadata metadata, shared_ptr<const Signer> signer) const
235 {
236         boost::filesystem::path p = _directory;
237         stringstream s;
238         s << pkl_uuid << "_pkl.xml";
239         p /= s.str();
240
241         xmlpp::Document doc;
242         xmlpp::Element* pkl;
243         if (standard == INTEROP) {
244                 pkl = doc.create_root_node("PackingList", "http://www.digicine.com/PROTO-ASDCP-PKL-20040311#");
245         } else {
246                 pkl = doc.create_root_node("PackingList", "http://www.smpte-ra.org/schemas/429-8/2007/PKL");
247         }
248         
249         if (signer) {
250                 pkl->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
251         }
252
253         pkl->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
254
255         /* XXX: this is a bit of a hack */
256         assert (cpls().size() > 0);
257         pkl->add_child("AnnotationText")->add_child_text (cpls().front()->annotation_text ());
258         
259         pkl->add_child("IssueDate")->add_child_text (metadata.issue_date);
260         pkl->add_child("Issuer")->add_child_text (metadata.issuer);
261         pkl->add_child("Creator")->add_child_text (metadata.creator);
262
263         xmlpp::Element* asset_list = pkl->add_child("AssetList");
264         for (list<shared_ptr<Asset> >::const_iterator i = _assets.begin(); i != _assets.end(); ++i) {
265                 (*i)->write_to_pkl (asset_list, standard);
266         }
267
268         if (signer) {
269                 signer->sign (pkl, standard);
270         }
271                 
272         doc.write_to_file (p.string (), "UTF-8");
273         return p.string ();
274 }
275
276 /** Write the VOLINDEX file.
277  *  @param standard DCP standard to use (INTEROP or SMPTE)
278  */
279 void
280 DCP::write_volindex (Standard standard) const
281 {
282         boost::filesystem::path p = _directory;
283         switch (standard) {
284         case INTEROP:
285                 p /= "VOLINDEX";
286                 break;
287         case SMPTE:
288                 p /= "VOLINDEX.xml";
289                 break;
290         default:
291                 assert (false);
292         }
293
294         xmlpp::Document doc;
295         xmlpp::Element* root;
296
297         switch (standard) {
298         case INTEROP:
299                 root = doc.create_root_node ("VolumeIndex", "http://www.digicine.com/PROTO-ASDCP-AM-20040311#");
300                 break;
301         case SMPTE:
302                 root = doc.create_root_node ("VolumeIndex", "http://www.smpte-ra.org/schemas/429-9/2007/AM");
303                 break;
304         default:
305                 assert (false);
306         }
307         
308         root->add_child("Index")->add_child_text ("1");
309         doc.write_to_file (p.string (), "UTF-8");
310 }
311
312 void
313 DCP::write_assetmap (Standard standard, string pkl_uuid, int pkl_length, XMLMetadata metadata) const
314 {
315         boost::filesystem::path p = _directory;
316         
317         switch (standard) {
318         case INTEROP:
319                 p /= "ASSETMAP";
320                 break;
321         case SMPTE:
322                 p /= "ASSETMAP.xml";
323                 break;
324         default:
325                 assert (false);
326         }
327
328         xmlpp::Document doc;
329         xmlpp::Element* root;
330
331         switch (standard) {
332         case INTEROP:
333                 root = doc.create_root_node ("AssetMap", "http://www.digicine.com/PROTO-ASDCP-AM-20040311#");
334                 break;
335         case SMPTE:
336                 root = doc.create_root_node ("AssetMap", "http://www.smpte-ra.org/schemas/429-9/2007/AM");
337                 break;
338         default:
339                 assert (false);
340         }
341
342         root->add_child("Id")->add_child_text ("urn:uuid:" + make_uuid());
343         root->add_child("AnnotationText")->add_child_text ("Created by " + metadata.creator);
344
345         switch (standard) {
346         case INTEROP:
347                 root->add_child("VolumeCount")->add_child_text ("1");
348                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
349                 root->add_child("Issuer")->add_child_text (metadata.issuer);
350                 root->add_child("Creator")->add_child_text (metadata.creator);
351                 break;
352         case SMPTE:
353                 root->add_child("Creator")->add_child_text (metadata.creator);
354                 root->add_child("VolumeCount")->add_child_text ("1");
355                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
356                 root->add_child("Issuer")->add_child_text (metadata.issuer);
357                 break;
358         default:
359                 assert (false);
360         }
361                 
362         xmlpp::Node* asset_list = root->add_child ("AssetList");
363
364         xmlpp::Node* asset = asset_list->add_child ("Asset");
365         asset->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
366         asset->add_child("PackingList")->add_child_text ("true");
367         xmlpp::Node* chunk_list = asset->add_child ("ChunkList");
368         xmlpp::Node* chunk = chunk_list->add_child ("Chunk");
369         chunk->add_child("Path")->add_child_text (pkl_uuid + "_pkl.xml");
370         chunk->add_child("VolumeIndex")->add_child_text ("1");
371         chunk->add_child("Offset")->add_child_text ("0");
372         chunk->add_child("Length")->add_child_text (lexical_cast<string> (pkl_length));
373         
374         for (list<shared_ptr<Asset> >::const_iterator i = _assets.begin(); i != _assets.end(); ++i) {
375                 (*i)->write_to_assetmap (asset_list, _directory);
376         }
377
378         /* This must not be the _formatted version otherwise signature digests will be wrong */
379         doc.write_to_file (p.string (), "UTF-8");
380 }
381
382 /** Write all the XML files for this DCP.
383  *  @param standand INTEROP or SMPTE.
384  *  @param metadata Metadata to use for PKL and asset map files.
385  *  @param signer Signer to use, or 0.
386  */
387 void
388 DCP::write_xml (
389         Standard standard,
390         XMLMetadata metadata,
391         shared_ptr<const Signer> signer
392         )
393 {
394         list<shared_ptr<CPL> > cpl = cpls ();
395         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
396                 string const filename = (*i)->id() + "_cpl.xml";
397                 (*i)->write_xml (_directory / filename, standard, signer);
398         }
399
400         string const pkl_uuid = make_uuid ();
401         boost::filesystem::path const pkl_path = write_pkl (standard, pkl_uuid, metadata, signer);
402         
403         write_volindex (standard);
404         write_assetmap (standard, pkl_uuid, boost::filesystem::file_size (pkl_path), metadata);
405 }
406
407 list<shared_ptr<CPL> >
408 DCP::cpls () const
409 {
410         return list_of_type<Asset, CPL> (_assets);
411 }