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