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