Remove create-by-files method for sound and picture assets.
[libdcp.git] / src / sound_asset.cc
1 /*
2     Copyright (C) 2012 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/sound_asset.cc
21  *  @brief An asset made up of WAV files
22  */
23
24 #include <iostream>
25 #include <stdexcept>
26 #include <boost/filesystem.hpp>
27 #include <boost/lexical_cast.hpp>
28 #include <libxml++/nodes/element.h>
29 #include "KM_fileio.h"
30 #include "AS_DCP.h"
31 #include "sound_asset.h"
32 #include "util.h"
33 #include "exceptions.h"
34 #include "sound_frame.h"
35
36 using std::string;
37 using std::stringstream;
38 using std::ostream;
39 using std::vector;
40 using std::list;
41 using boost::shared_ptr;
42 using boost::lexical_cast;
43 using namespace dcp;
44
45 SoundAsset::SoundAsset (boost::filesystem::path directory, boost::filesystem::path mxf_name)
46         : MXFAsset (directory, mxf_name)
47         , _channels (0)
48         , _sampling_rate (0)
49 {
50
51 }
52
53 void
54 SoundAsset::read ()
55 {
56         ASDCP::PCM::MXFReader reader;
57         Kumu::Result_t r = reader.OpenRead (path().string().c_str());
58         if (ASDCP_FAILURE (r)) {
59                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string(), r));
60         }
61
62         ASDCP::PCM::AudioDescriptor desc;
63         if (ASDCP_FAILURE (reader.FillAudioDescriptor (desc))) {
64                 boost::throw_exception (DCPReadError ("could not read audio MXF information"));
65         }
66
67         _sampling_rate = desc.AudioSamplingRate.Numerator / desc.AudioSamplingRate.Denominator;
68         _channels = desc.ChannelCount;
69         _edit_rate = desc.EditRate.Numerator;
70         assert (desc.EditRate.Denominator == 1);
71         _intrinsic_duration = desc.ContainerDuration;
72 }
73
74 string
75 SoundAsset::cpl_node_name () const
76 {
77         return "MainSound";
78 }
79
80 bool
81 SoundAsset::equals (shared_ptr<const ContentAsset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
82 {
83         if (!MXFAsset::equals (other, opt, note)) {
84                 return false;
85         }
86                      
87         ASDCP::PCM::MXFReader reader_A;
88         Kumu::Result_t r = reader_A.OpenRead (path().string().c_str());
89         if (ASDCP_FAILURE (r)) {
90                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string(), r));
91         }
92
93         ASDCP::PCM::MXFReader reader_B;
94         r = reader_B.OpenRead (other->path().string().c_str());
95         if (ASDCP_FAILURE (r)) {
96                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string(), r));
97         }
98
99         ASDCP::PCM::AudioDescriptor desc_A;
100         if (ASDCP_FAILURE (reader_A.FillAudioDescriptor (desc_A))) {
101                 boost::throw_exception (DCPReadError ("could not read audio MXF information"));
102         }
103         ASDCP::PCM::AudioDescriptor desc_B;
104         if (ASDCP_FAILURE (reader_B.FillAudioDescriptor (desc_B))) {
105                 boost::throw_exception (DCPReadError ("could not read audio MXF information"));
106         }
107         
108         if (
109                 desc_A.EditRate != desc_B.EditRate ||
110                 desc_A.AudioSamplingRate != desc_B.AudioSamplingRate ||
111                 desc_A.Locked != desc_B.Locked ||
112                 desc_A.ChannelCount != desc_B.ChannelCount ||
113                 desc_A.QuantizationBits != desc_B.QuantizationBits ||
114                 desc_A.BlockAlign != desc_B.BlockAlign ||
115                 desc_A.AvgBps != desc_B.AvgBps ||
116                 desc_A.LinkedTrackID != desc_B.LinkedTrackID ||
117                 desc_A.ContainerDuration != desc_B.ContainerDuration
118 //              desc_A.ChannelFormat != desc_B.ChannelFormat ||
119                 ) {
120                 
121                 note (ERROR, "audio MXF picture descriptors differ");
122                 return false;
123         }
124         
125         ASDCP::PCM::FrameBuffer buffer_A (1 * Kumu::Megabyte);
126         ASDCP::PCM::FrameBuffer buffer_B (1 * Kumu::Megabyte);
127         
128         for (int i = 0; i < _intrinsic_duration; ++i) {
129                 if (ASDCP_FAILURE (reader_A.ReadFrame (i, buffer_A))) {
130                         boost::throw_exception (DCPReadError ("could not read audio frame"));
131                 }
132                 
133                 if (ASDCP_FAILURE (reader_B.ReadFrame (i, buffer_B))) {
134                         boost::throw_exception (DCPReadError ("could not read audio frame"));
135                 }
136                 
137                 if (buffer_A.Size() != buffer_B.Size()) {
138                         note (ERROR, "sizes of audio data for frame " + lexical_cast<string>(i) + " differ");
139                         return false;
140                 }
141                 
142                 if (memcmp (buffer_A.RoData(), buffer_B.RoData(), buffer_A.Size()) != 0) {
143                         for (uint32_t i = 0; i < buffer_A.Size(); ++i) {
144                                 int const d = abs (buffer_A.RoData()[i] - buffer_B.RoData()[i]);
145                                 if (d > opt.max_audio_sample_error) {
146                                         note (ERROR, "PCM data difference of " + lexical_cast<string> (d));
147                                         return false;
148                                 }
149                         }
150                 }
151         }
152
153         return true;
154 }
155
156 shared_ptr<const SoundFrame>
157 SoundAsset::get_frame (int n) const
158 {
159         /* XXX: should add on entry point here? */
160         return shared_ptr<const SoundFrame> (new SoundFrame (path().string(), n, _decryption_context));
161 }
162
163 shared_ptr<SoundAssetWriter>
164 SoundAsset::start_write ()
165 {
166         /* XXX: can't we use a shared_ptr here? */
167         return shared_ptr<SoundAssetWriter> (new SoundAssetWriter (this));
168 }
169
170 struct SoundAssetWriter::ASDCPState
171 {
172         ASDCP::PCM::MXFWriter mxf_writer;
173         ASDCP::PCM::FrameBuffer frame_buffer;
174         ASDCP::WriterInfo writer_info;
175         ASDCP::PCM::AudioDescriptor audio_desc;
176         ASDCP::AESEncContext* encryption_context;
177 };
178
179 SoundAssetWriter::SoundAssetWriter (SoundAsset* a)
180         : _state (new SoundAssetWriter::ASDCPState)
181         , _asset (a)
182         , _finalized (false)
183         , _frames_written (0)
184         , _frame_buffer_offset (0)
185 {
186         _state->encryption_context = a->encryption_context ();
187         
188         /* Derived from ASDCP::Wav::SimpleWaveHeader::FillADesc */
189         _state->audio_desc.EditRate = ASDCP::Rational (_asset->edit_rate(), 1);
190         _state->audio_desc.AudioSamplingRate = ASDCP::Rational (_asset->sampling_rate(), 1);
191         _state->audio_desc.Locked = 0;
192         _state->audio_desc.ChannelCount = _asset->channels ();
193         _state->audio_desc.QuantizationBits = 24;
194         _state->audio_desc.BlockAlign = 3 * _asset->channels();
195         _state->audio_desc.AvgBps = _asset->sampling_rate() * _state->audio_desc.BlockAlign;
196         _state->audio_desc.LinkedTrackID = 0;
197         _state->audio_desc.ChannelFormat = ASDCP::PCM::CF_NONE;
198         
199         _state->frame_buffer.Capacity (ASDCP::PCM::CalcFrameBufferSize (_state->audio_desc));
200         _state->frame_buffer.Size (ASDCP::PCM::CalcFrameBufferSize (_state->audio_desc));
201         memset (_state->frame_buffer.Data(), 0, _state->frame_buffer.Capacity());
202         
203         _asset->fill_writer_info (&_state->writer_info);
204         
205         Kumu::Result_t r = _state->mxf_writer.OpenWrite (_asset->path().string().c_str(), _state->writer_info, _state->audio_desc);
206         if (ASDCP_FAILURE (r)) {
207                 boost::throw_exception (FileError ("could not open audio MXF for writing", _asset->path().string(), r));
208         }
209 }
210
211 void
212 SoundAssetWriter::write (float const * const * data, int frames)
213 {
214         for (int i = 0; i < frames; ++i) {
215
216                 byte_t* out = _state->frame_buffer.Data() + _frame_buffer_offset;
217
218                 /* Write one sample per channel */
219                 for (int j = 0; j < _asset->channels(); ++j) {
220                         int32_t const s = data[j][i] * (1 << 23);
221                         *out++ = (s & 0xff);
222                         *out++ = (s & 0xff00) >> 8;
223                         *out++ = (s & 0xff0000) >> 16;
224                 }
225                 _frame_buffer_offset += 3 * _asset->channels();
226
227                 assert (_frame_buffer_offset <= int (_state->frame_buffer.Capacity()));
228
229                 /* Finish the MXF frame if required */
230                 if (_frame_buffer_offset == int (_state->frame_buffer.Capacity())) {
231                         write_current_frame ();
232                         _frame_buffer_offset = 0;
233                         memset (_state->frame_buffer.Data(), 0, _state->frame_buffer.Capacity());
234                 }
235         }
236 }
237
238 void
239 SoundAssetWriter::write_current_frame ()
240 {
241         ASDCP::Result_t const r = _state->mxf_writer.WriteFrame (_state->frame_buffer, _state->encryption_context, 0);
242         if (ASDCP_FAILURE (r)) {
243                 boost::throw_exception (MiscError ("could not write audio MXF frame (" + lexical_cast<string> (int (r)) + ")"));
244         }
245
246         ++_frames_written;
247 }
248
249 void
250 SoundAssetWriter::finalize ()
251 {
252         if (_frame_buffer_offset > 0) {
253                 write_current_frame ();
254         }
255         
256         if (ASDCP_FAILURE (_state->mxf_writer.Finalize())) {
257                 boost::throw_exception (MiscError ("could not finalise audio MXF"));
258         }
259
260         _finalized = true;
261         _asset->set_intrinsic_duration (_frames_written);
262         _asset->set_duration (_frames_written);
263 }
264
265 string
266 SoundAsset::key_type () const
267 {
268         return "MDAK";
269 }