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