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