private Stream SetPlayStream_FromFile_OPEN( FileStream fileStream, string filePathOptionalInfo) { Stream stream = fileStream; if (stream != null) { stream.Position = 0; stream.Seek(0, SeekOrigin.Begin); uint dataLength; AudioLibPCMFormat format = AudioLibPCMFormat.RiffHeaderParse(stream, out dataLength); PcmFormat = new PCMFormatInfo(format); dataLength = (uint)(stream.Length - stream.Position); stream = new SubStream(stream, stream.Position, dataLength, filePathOptionalInfo); DebugFix.Assert(dataLength == stream.Length); DataLength = stream.Length; EndOffsetOfPlayStream = DataLength; } return(stream); }
// Draw the waveform in a graphics // TODO: handle other bit depths than 16 bit. private void DrawWaveform(Graphics g, AudioBlock block) { PCMFormatInfo format = this.audio.getPCMFormat(); if (format.getBitDepth() != 16) { throw new Exception("Cannot deal with bitdepth others than 16."); } ushort channels = format.getNumberOfChannels(); ushort frameSize = format.getBlockAlign(); int samplesPerPixel = (int)Math.Ceiling(this.audio.getPCMLength() / (float)frameSize / Width * channels); int bytesPerPixel = samplesPerPixel * frameSize / channels; byte[] bytes = new byte[bytesPerPixel]; short[] samples = new short[samplesPerPixel]; System.IO.Stream au = this.audio.getAudioData(); for (int x = 0; x < Width; ++x) { int read = au.Read(bytes, 0, bytesPerPixel); Buffer.BlockCopy(bytes, 0, samples, 0, read); DrawChannel(g, block.Highlighted ? block.Colors.WaveformChannelSelectedPen : channels == 1 ? block.Colors.WaveformMonoPen : block.Colors.WaveformChannel1Pen, samples, x, read, frameSize, 0, channels); if (channels == 2) { DrawChannel(g, block.Selected ? block.Colors.WaveformChannelSelectedPen : block.Colors.WaveformChannel2Pen, samples, x, read, frameSize, 1, channels); } } au.Close(); }
//protected override void CreateProjectFileAndDirectory() //{ //if (!Directory.Exists(m_outDirectory)) //{ //Directory.CreateDirectory(m_outDirectory); //} //m_Xuk_FilePath = m_Session.Path; //} protected override void initializeProject(string path) { //m_Project = new Project(); m_Project = m_Session.Presentation.Project; #if false //(DEBUG) m_Project.PrettyFormat = true; #else m_Project.PrettyFormat = false; #endif //Presentation presentation = m_Project.AddNewPresentation(new Uri(m_outDirectory), Path.GetFileName(m_Book_FilePath)); m_Presentation = m_Session.Presentation; PCMFormatInfo pcmFormat = m_Presentation.MediaDataManager.DefaultPCMFormat.Copy(); pcmFormat.Data.SampleRate = (ushort)m_audioProjectSampleRate; m_Presentation.MediaDataManager.DefaultPCMFormat = pcmFormat; m_Presentation.MediaDataManager.EnforceSinglePCMFormat = true; //m_textChannel = m_Presentation.ChannelFactory.CreateTextChannel(); //m_textChannel.Name = "The Text Channel"; m_textChannel = m_Presentation.ChannelsManager.GetOrCreateTextChannel(); //m_audioChannel = m_Presentation.ChannelFactory.CreateAudioChannel(); //m_audioChannel.Name = "The Audio Channel"; m_audioChannel = m_Presentation.ChannelsManager.GetOrCreateAudioChannel(); m_TitleMetadata = m_Presentation.GetFirstMetadataItem(Metadata.DC_TITLE); m_IdentifierMetadata = m_Presentation.GetFirstMetadataItem(Metadata.DC_IDENTIFIER); m_XmlIdToSectionNodeMap = new Dictionary <string, SectionNode>(); m_XmlIdToPageNodeMap = new Dictionary <string, EmptyNode>(); }
private void XukInPCMFormat(XmlReader source, IProgressHandler handler) { if (!source.IsEmptyElement) { while (source.Read()) { if (source.NodeType == XmlNodeType.Element) { if (source.NamespaceURI == XukAble.XUK_NS && XukAble.GetXukName(typeof(PCMFormatInfo)).Match(source.LocalName) ) { PCMFormatInfo newInfo = new PCMFormatInfo(); newInfo.XukIn(source, handler); PCMFormat = newInfo; } else if (!source.IsEmptyElement) { source.ReadSubtree().Close(); } } else if (source.NodeType == XmlNodeType.EndElement) { break; } if (source.EOF) { throw new exception.XukException("Unexpectedly reached EOF"); } } } }
private bool isNewDefaultPCMFormatOk(PCMFormatInfo newDefault) { foreach (MediaData md in ManagedObjects.ContentsAs_Enumerable) { WavAudioMediaData amd = md as WavAudioMediaData; if (amd != null && !amd.PCMFormat.Data.IsCompatibleWith(newDefault.Data)) { return(false); } } return(true); }
private void writeInitialHeader(PCMFormatInfo pcmfi) { if (pcmfi == null) { throw new Exception("PCMFormatInfo is null !!!"); } if (mCurrentAudioFileStream == null) { throw new Exception("mCurrentAudioFileStream is null !!!"); } mCurrentAudioFilePCMFormat = pcmfi; mCurrentAudioFileStreamRiffWaveHeaderLength = (uint)mCurrentAudioFilePCMFormat.Data.RiffHeaderWrite(mCurrentAudioFileStream, 0); }
public AudioFormatConvertorSession(string destinationDirectory, PCMFormatInfo destinationFormatInfo, bool autoDetectPcmFormat, bool skipACM) { if (destinationDirectory == null) { throw new ArgumentNullException("destinationDirectory"); } m_destinationDirectory = destinationDirectory; m_destinationFormatInfo = destinationFormatInfo; m_autoDetectPcmFormat = autoDetectPcmFormat; m_SkipACM = skipACM; m_FilePathsMap = new Dictionary <string, string>(); }
/// <summary> /// Determines if a PCM Format change is ok /// </summary> /// <param name="newFormat">The new PCM Format value - assumed not to be <c>null</c></param> /// <param name="failReason">The <see cref="string"/> to which a failure reason must be written in case the change is not ok</param> /// <returns>A <see cref="bool"/> indicating if the change is ok</returns> protected override bool IsPCMFormatChangeOk(PCMFormatInfo newFormat, out string failReason) { if (!base.IsPCMFormatChangeOk(newFormat, out failReason)) { return(false); } if (mWavClips.Count > 0) { if (!PCMFormat.Data.IsCompatibleWith(newFormat.Data)) { failReason = "Cannot change the PCMFormat of the WavAudioMediaData after audio data has been added to it"; return(false); } } return(true); }
protected virtual void initializeProject(string dataFolderPrefix) { m_dataFolderPrefix = dataFolderPrefix; m_Project = new Project(); m_Project.PrettyFormat = m_XukPrettyFormat; Presentation presentation = m_Project.AddNewPresentation(new Uri(m_outDirectory), dataFolderPrefix); PCMFormatInfo pcmFormat = presentation.MediaDataManager.DefaultPCMFormat; //.Copy(); pcmFormat.Data.SampleRate = (ushort)m_audioProjectSampleRate; pcmFormat.Data.NumberOfChannels = m_audioStereo ? (ushort)2 : (ushort)1; presentation.MediaDataManager.DefaultPCMFormat = pcmFormat; //presentation.MediaDataFactory.DefaultAudioMediaDataType = typeof(WavAudioMediaData); //presentation.MediaDataManager.EnforceSinglePCMFormat = true; TextChannel textChannel = presentation.ChannelFactory.CreateTextChannel(); textChannel.Name = "The Text Channel"; DebugFix.Assert(textChannel == presentation.ChannelsManager.GetOrCreateTextChannel()); AudioChannel audioChannel = presentation.ChannelFactory.CreateAudioChannel(); audioChannel.Name = "The Audio Channel"; DebugFix.Assert(audioChannel == presentation.ChannelsManager.GetOrCreateAudioChannel()); ImageChannel imageChannel = presentation.ChannelFactory.CreateImageChannel(); imageChannel.Name = "The Image Channel"; DebugFix.Assert(imageChannel == presentation.ChannelsManager.GetOrCreateImageChannel()); VideoChannel videoChannel = presentation.ChannelFactory.CreateVideoChannel(); videoChannel.Name = "The Video Channel"; DebugFix.Assert(videoChannel == presentation.ChannelsManager.GetOrCreateVideoChannel()); /*string dataPath = presentation.DataProviderManager.DataFileDirectoryFullPath; * if (Directory.Exists(dataPath)) * { * Directory.Delete(dataPath, true); * }*/ }
private void writeAndCloseCurrentAudioFile() { if (mCurrentAudioFileStream == null) { return; } if (mCurrentAudioFilePCMFormat != null) { uint dataLength = (uint)mCurrentAudioFileStream.Length - mCurrentAudioFileStreamRiffWaveHeaderLength; mCurrentAudioFileStream.Position = 0; mCurrentAudioFileStream.Seek(0, SeekOrigin.Begin); mCurrentAudioFilePCMFormat.Data.RiffHeaderWrite(mCurrentAudioFileStream, dataLength); } mCurrentAudioFileStream.Close(); mCurrentAudioFileStream = null; mCurrentAudioFilePCMFormat = null; mCurrentAudioFileStreamRiffWaveHeaderLength = 0; }
public IWaveFormData GetData(int numberOfDataPoints) { WaveFormData res = new WaveFormData(); if (numberOfDataPoints < 1) { throw new MethodParameterIsOutOfBoundsException("The number of data points must be a positive integer"); } res.mNumberOfDataPoints = numberOfDataPoints; PCMFormatInfo fmt = SourceAudioMediaData.PCMFormat; res.mNumberOfChannels = fmt.NumberOfChannels; Stream audio = SourceAudioMediaData.GetAudioData(); res.mBeginTime = TimeSpan.Zero; res.mEndTime = SourceAudioMediaData.AudioDuration.TimeDeltaAsTimeSpan; res.mData = new int[res.NumberOfDataPoints, res.NumberOfChannels, 2]; switch (fmt.BitDepth) { case 8: res.mMinScaleValue = byte.MinValue; res.mMaxScaleValue = byte.MaxValue; Calculate8BitMinMax(audio, res); break; case 16: res.mMinScaleValue = short.MinValue; res.mMaxScaleValue = short.MaxValue; Calculate16BitMinMax(audio, res); break; default: throw new Exception( String.Format( "Bit Depth {0:0} not supported (only bit depths 8 and 16 are supported", SourceAudioMediaData.PCMFormat.BitDepth)); } return(res); }
public PCMFormatInfo GetCurrentPcmFormat() { if (m_viewModel.IsRecording || m_viewModel.IsMonitoring) { if (PcmFormatRecordingMonitoring == null) { PcmFormatRecordingMonitoring = new PCMFormatInfo(m_viewModel.m_Recorder.RecordingPCMFormat); } return(PcmFormatRecordingMonitoring); } if (m_viewModel.IsPlaying) { if (PcmFormat == null) { PcmFormat = new PCMFormatInfo(m_viewModel.m_Player.CurrentAudioPCMFormat); } } if (PcmFormat == null && m_viewModel.m_UrakawaSession.DocumentProject != null) { PcmFormat = m_viewModel.m_UrakawaSession.DocumentProject .Presentations.Get(0).MediaDataManager.DefaultPCMFormat.Copy(); } return(PcmFormat); }
private void generateImageDescriptionInDTBook(TreeNode n, XmlNode currentXmlNode, string exportImageName, XmlDocument DTBookDocument) { AlternateContentProperty altProp = n.GetAlternateContentProperty(); if (currentXmlNode.LocalName == null || !currentXmlNode.LocalName.Equals("img", StringComparison.OrdinalIgnoreCase) || altProp == null || altProp.IsEmpty) { return; } m_Map_AltProperty_TO_Description.Add(altProp, new Description()); PCMFormatInfo audioFormat = m_Presentation.MediaDataManager.DefaultPCMFormat; AudioLibPCMFormat pcmFormat = audioFormat.Data; pcmFormat.SampleRate = (ushort)m_sampleRate; pcmFormat.NumberOfChannels = (ushort)(m_audioStereo ? 2 : 1); Dictionary <string, List <string> > map_DiagramElementName_TO_TextualDescriptions = new Dictionary <string, List <string> >(); string imageDescriptionDirectoryPath = GetAndCreateImageDescriptionDirectoryPath(true, exportImageName, m_OutputDirectory); string descriptionFile = CreateImageDescription(m_SkipACM, pcmFormat, m_encodeAudioFiles, m_BitRate_Encoding, imageDescriptionDirectoryPath, exportImageName, altProp, map_DiagramElementName_TO_TextualDescriptions, m_Map_AltProperty_TO_Description, m_Map_AltContentAudio_TO_RelativeExportedFilePath); if (m_includeImageDescriptions && !String.IsNullOrEmpty(descriptionFile)) { //short term way for executing image description code: will be updated in later phase of implementation XmlNode prodNoteNode = DTBookDocument.CreateElement("prodnote", currentXmlNode.NamespaceURI); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteNode, "render", "optional"); string id_Prodnote = GetNextID(ID_DTBPrefix); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteNode, "id", id_Prodnote); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteNode, "imgref", currentXmlNode.Attributes.GetNamedItem("id").Value); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteNode, "class", DiagramContentModelHelper.EPUB_DescribedAt); currentXmlNode.ParentNode.AppendChild(prodNoteNode); if (!m_Image_ProdNoteMap.ContainsKey(n)) { m_Image_ProdNoteMap.Add(n, new List <XmlNode>()); } m_Image_ProdNoteMap[n].Add(prodNoteNode); XmlNode anchorNode = DTBookDocument.CreateElement("a", currentXmlNode.NamespaceURI); XmlNode pAnchor = DTBookDocument.CreateElement( DiagramContentModelHelper.P, currentXmlNode.NamespaceURI ); pAnchor.AppendChild(anchorNode); prodNoteNode.AppendChild(pAnchor); string descriptionFileUrl = descriptionFile.Replace('\\', '/'); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, anchorNode, "href", FileDataProvider.UriEncode(descriptionFileUrl)); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, anchorNode, "external", "true"); anchorNode.AppendChild(DTBookDocument.CreateTextNode("Image description (DIAGRAM XML)")); if (map_DiagramElementName_TO_TextualDescriptions.Count > 0) { foreach (string diagramDescriptionElementName in map_DiagramElementName_TO_TextualDescriptions.Keys) { //System.Windows.Forms.MessageBox.Show(s + " : " + imageDescriptions[s]); XmlNode prodNoteDesc = DTBookDocument.CreateElement("prodnote", currentXmlNode.NamespaceURI); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteDesc, "render", "optional"); string id_ProdnoteDesc = GetNextID(ID_DTBPrefix); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteDesc, "id", id_ProdnoteDesc); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteDesc, "imgref", currentXmlNode.Attributes.GetNamedItem("id").Value); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteDesc, "class", diagramDescriptionElementName); currentXmlNode.ParentNode.AppendChild(prodNoteDesc); m_Image_ProdNoteMap[n].Add(prodNoteDesc); foreach (string txt in map_DiagramElementName_TO_TextualDescriptions[diagramDescriptionElementName]) { string descText = txt; bool xmlParseFail = descText.StartsWith(DIAGRAM_XML_PARSE_FAIL); bool descriptionTextContainsMarkup = !xmlParseFail && descText.IndexOf('<') >= 0; // descText.Contains("<"); if (descriptionTextContainsMarkup) { try { prodNoteDesc.InnerXml = descText; } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif Console.WriteLine(@"Cannot set DIAGRAM XML: " + descText); XmlNode wrapperNode = DTBookDocument.CreateElement(DiagramContentModelHelper.CODE, currentXmlNode.NamespaceURI); prodNoteDesc.AppendChild(wrapperNode); wrapperNode.AppendChild(DTBookDocument.CreateTextNode(descText)); } } else if (xmlParseFail) { //descText = descText.Replace(DIAGRAM_XML_PARSE_FAIL, ""); descText = descText.Substring(DIAGRAM_XML_PARSE_FAIL.Length); XmlNode wrapperNode = DTBookDocument.CreateElement(DiagramContentModelHelper.CODE, currentXmlNode.NamespaceURI); prodNoteDesc.AppendChild(wrapperNode); wrapperNode.AppendChild(DTBookDocument.CreateTextNode(descText)); } else { string normalizedText = descText.Replace("\r\n", "\n"); string[] parasText = normalizedText.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); //string[] parasText = System.Text.RegularExpressions.Regex.Split(normalizedText, "\n"); for (int i = 0; i < parasText.Length; i++) { string paraText = parasText[i].Trim(); if (string.IsNullOrEmpty(paraText)) { continue; } XmlNode paragraph = DTBookDocument.CreateElement( //DiagramContentModelHelper.NS_PREFIX_ZAI, DiagramContentModelHelper.P , currentXmlNode.NamespaceURI //, DiagramContentModelHelper.NS_URL_ZAI ); paragraph.InnerText = paraText; prodNoteDesc.AppendChild(paragraph); } } } } } /* * if ( EXPORT_IMAGE_DESCRIPTION_IN_DTBOOK ) * {//1 * // to do copy the diagram nodes that descend directly from body * if (m_AltProperrty_DiagramDocument.ContainsKey(n.GetAlternateContentProperty())) * {//2 * * XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, DTBookDocument.GetElementsByTagName("dtbook")[0], * XmlReaderWriterHelper.NS_PREFIX_XMLNS+":" + DiagramContentModelHelper.NS_PREFIX_DIAGRAM, * DiagramContentModelHelper.NS_URL_DIAGRAM); * XmlDocument descriptionDocument = m_AltProperrty_DiagramDocument[n.GetAlternateContentProperty()]; * XmlNodeList diagramNodesList = descriptionDocument.GetElementsByTagName("d:body")[0].ChildNodes; * foreach (XmlNode xn in diagramNodesList) * {//3 * XmlNode newNode = DTBookDocument.ImportNode(xn, true); * prodNoteNode.AppendChild(newNode); * for (int i = 0; i < newNode.Attributes.Count; i++) * {//4 * XmlAttribute attr = newNode.Attributes[i]; * if (attr.Name == DiagramContentModelHelper.NS_PREFIX_XML + ":id") * {//-4 * XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, newNode, "id", attr.Value); * newNode.Attributes.Remove(attr); * }//-3 * }//-2 * * }//-1 * * } * * //XmlNode newNode = DTBookDocument.ImportNode(M_DescriptionDocument.GetElementsByTagName("d:description")[0], true); * //prodNoteNode.AppendChild(newNode); * } */ } //} //catch (System.Exception ex) //{ //System.Windows.Forms.MessageBox.Show(ex.ToString()); //} //} //} }
/// <summary> /// Constructor setting the source <see cref="AudioMediaData"/> of the event /// and the previous+new PCMFormat /// </summary> /// <param name="source">The source <see cref="AudioMediaData"/> of the event</param> /// <param name="newFormat">The new PCMFormat</param> /// <param name="prevFormat">The PCMFormat prior to the change</param> public PCMFormatChangedEventArgs(AudioMediaData source, PCMFormatInfo newFormat, PCMFormatInfo prevFormat) : base(source) { NewPCMFormat = newFormat; PreviousPCMFormat = prevFormat; }
private ManagedAudioMedia addAudioWav(FileDataProvider dataProv, XmlNode audioAttrClipBegin, XmlNode audioAttrClipEnd, TreeNode treeNode) { if (m_autoDetectPcmFormat && m_AudioConversionSession.FirstDiscoveredPCMFormat != null && !m_AudioConversionSession.FirstDiscoveredPCMFormat.IsCompatibleWith(treeNode.Presentation.MediaDataManager.DefaultPCMFormat.Data)) { PCMFormatInfo pcmFormat = treeNode.Presentation.MediaDataManager.DefaultPCMFormat; //.Copy(); pcmFormat.Data.CopyFrom(m_AudioConversionSession.FirstDiscoveredPCMFormat); //pcmFormat.Data.SampleRate = (ushort) m_audioProjectSampleRate; //pcmFormat.Data.NumberOfChannels = m_audioStereo ? (ushort) 2 : (ushort) 1; treeNode.Presentation.MediaDataManager.DefaultPCMFormat = pcmFormat; } if (RequestCancellation) { return(null); } Time clipB = Time.Zero; Time clipE = Time.MaxValue; if (audioAttrClipBegin != null && !string.IsNullOrEmpty(audioAttrClipBegin.Value)) { try { clipB = new Time(audioAttrClipBegin.Value); } catch (Exception ex) { clipB = new Time(); string str = "CLIP BEGIN TIME PARSE FAIL: " + audioAttrClipBegin.Value; Console.WriteLine(str); Debug.Fail(str); } } if (audioAttrClipEnd != null && !string.IsNullOrEmpty(audioAttrClipEnd.Value)) { try { clipE = new Time(audioAttrClipEnd.Value); } catch (Exception ex) { clipE = new Time(); string str = "CLIP END TIME PARSE FAIL: " + audioAttrClipEnd.Value; Console.WriteLine(str); Debug.Fail(str); } } ManagedAudioMedia media = null; Presentation presentation = treeNode.Presentation; // m_Project.Presentations.Get(0); //if (deleteSrcAfterCompletion) //{ WavAudioMediaData mediaData = (WavAudioMediaData) presentation.MediaDataFactory.CreateAudioMediaData(); // mediaData.AudioDuration DOES NOT WORK BECAUSE DEPENDS ON WAVCLIPS LIST!!! WavClip wavClip = new WavClip(dataProv); Time newClipE = clipE.Copy(); if (newClipE.IsGreaterThan(wavClip.MediaDuration)) { clipEndAdjustedToNull(clipB, newClipE, wavClip.MediaDuration, treeNode); //newClipE = wavClip.MediaDuration; newClipE = null; } //FileDataProvider dataProv = m_Src_FileDataProviderMap[fullWavPath]; //System.Windows.Forms.MessageBox.Show ( clipB.ToString () + " : " + clipE.ToString () ) ; //bool isClipEndError = false; try { mediaData.AppendPcmData(dataProv, clipB, newClipE); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif //DEBUG Console.WriteLine("CLIP TIME ERROR1 (end < begin ?): " + clipB + " (" + (audioAttrClipBegin != null ? audioAttrClipBegin.Value : "N/A") + ") / " + clipE + " (" + (audioAttrClipEnd != null ? audioAttrClipEnd.Value : "N/A") + ") === " + wavClip.MediaDuration); //if (ex is exception.MethodParameterIsOutOfBoundsException && clipB != null && clipE != null && clipB.IsLessThanOrEqualTo(clipE)) //{ // isClipEndError = true; //} //else //{ // Console.WriteLine("CLIP TIME ERROR1 (end < begin ?): " + clipB + " (" + (audioAttrClipBegin != null ? audioAttrClipBegin.Value : "N/A") + ") / " + clipE + " (" + (audioAttrClipEnd != null ? audioAttrClipEnd.Value : "N/A") + ")"); // return null; //} } //if (isClipEndError) //{ // // reduce clip end by 1 millisecond for rounding off tolerance // isClipEndError = addAudioWavWithEndOfFileTolerance(mediaData, dataProv, clipB, clipE, treeNode); // if (isClipEndError) // { // Console.WriteLine("CLIP TIME ERROR2 (end < begin ?): " + clipB + " (" + (audioAttrClipBegin != null ? audioAttrClipBegin.Value : "N/A") + ") / " + clipE + " (" + (audioAttrClipEnd != null ? audioAttrClipEnd.Value : "N/A") + ")"); // return null; // } //} if (RequestCancellation) { return(null); } media = presentation.MediaFactory.CreateManagedAudioMedia(); media.AudioMediaData = mediaData; //} /* else * { * * uint dataLength; * AudioLibPCMFormat pcmInfo = null; * Stream wavStream = null; * try * { * wavStream = File.Open(fullWavPath, FileMode.Open, FileAccess.Read, FileShare.Read); * * pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength); * * //if (m_firstTimePCMFormat) * //{ * // presentation.MediaDataManager.DefaultPCMFormat = new PCMFormatInfo(pcmInfo); * // m_firstTimePCMFormat = false; * //} * * Time clipDuration = new Time(pcmInfo.ConvertBytesToTime(dataLength)); * if (!clipB.IsEqualTo(Time.Zero) || !clipE.IsEqualTo(Time.MaxValue)) * { * clipDuration = clipE.GetTime(clipB); * } * else * { * System.Diagnostics.Debug.Fail("Audio clip with full duration ??"); * } * * long byteOffset = 0; * if (!clipB.IsEqualTo(Time.Zero)) * { * byteOffset = pcmInfo.ConvertTimeToBytes(clipB.TimeAsMillisecondFloat); * } * if (byteOffset > 0) * { * wavStream.Seek(byteOffset, SeekOrigin.Current); * } * * presentation.MediaDataFactory.DefaultAudioMediaDataType = * typeof (WavAudioMediaData); * * WavAudioMediaData mediaData = * (WavAudioMediaData) * presentation.MediaDataFactory.CreateAudioMediaData(); * * * mediaData.InsertPcmData(wavStream, Time.Zero, clipDuration); * * media = presentation.MediaFactory.CreateManagedAudioMedia(); * ((ManagedAudioMedia) media).AudioMediaData = mediaData; * } * finally * { * if (wavStream != null) wavStream.Close(); * } * * } */ return(media); }
private void checkAndAddDeferredRecordingDataItems() { if (m_DeferredRecordingDataItems == null) { return; } IsAutoPlay = false; bool needsRefresh = false; bool skipDrawing = Settings.Default.AudioWaveForm_DisableDraw; Settings.Default.AudioWaveForm_DisableDraw = true; //#if !DISABLE_SINGLE_RECORD_FILE string previousRecordedFile = null; FileDataProvider currentFileDataProvider = null; AudioLibPCMFormat currentPcmFormat = null; long currentPcmDataLength = -1; long previousBytePosEnd = 0; //#endif foreach (var deferredRecordingDataItem in m_DeferredRecordingDataItems) { Tuple <TreeNode, TreeNode> treeNodeSelection = m_UrakawaSession.PerformTreeNodeSelection(deferredRecordingDataItem.TreeNode1, false, deferredRecordingDataItem.TreeNode2); if (treeNodeSelection.Item1 != deferredRecordingDataItem.TreeNode1 || treeNodeSelection.Item2 != deferredRecordingDataItem.TreeNode2) { #if DEBUG Debugger.Break(); #endif continue; } if (IsWaveFormLoading && View != null) { View.CancelWaveFormLoad(true); } if (deferredRecordingDataItem.PlayBytePosition >= 0) { PlayBytePosition = deferredRecordingDataItem.PlayBytePosition; } else { m_LastSetPlayBytePosition = deferredRecordingDataItem.PlayBytePosition; } if (PlayBytePosition != deferredRecordingDataItem.PlayBytePosition) { #if DEBUG Debugger.Break(); #endif continue; } if (deferredRecordingDataItem.SelectionBeginBytePosition >= 0 && deferredRecordingDataItem.SelectionEndBytePosition > 0) { State.Selection.SetSelectionBytes(deferredRecordingDataItem.SelectionBeginBytePosition, deferredRecordingDataItem.SelectionEndBytePosition); } else { State.Selection.ClearSelection(); } if (State.Selection.SelectionBeginBytePosition != deferredRecordingDataItem.SelectionBeginBytePosition || State.Selection.SelectionEndBytePosition != deferredRecordingDataItem.SelectionEndBytePosition) { #if DEBUG Debugger.Break(); #endif continue; } if (!Settings.Default.Audio_DisableSingleWavFileRecord) { TreeNode treeNode = deferredRecordingDataItem.TreeNode1 ?? deferredRecordingDataItem.TreeNode2; if (string.IsNullOrEmpty(previousRecordedFile) || previousRecordedFile != deferredRecordingDataItem.RecordedFilePath) { PCMFormatInfo pcmInfo = State.Audio.PcmFormatRecordingMonitoring; currentPcmFormat = (pcmInfo != null ? pcmInfo.Copy().Data : null); if (currentPcmFormat == null) { Stream fileStream = File.Open(deferredRecordingDataItem.RecordedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); try { uint dataLength; currentPcmFormat = AudioLibPCMFormat.RiffHeaderParse(fileStream, out dataLength); currentPcmDataLength = dataLength; } finally { fileStream.Close(); } } currentFileDataProvider = (FileDataProvider)treeNode.Presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); currentFileDataProvider.InitByMovingExistingFile(deferredRecordingDataItem.RecordedFilePath); if (File.Exists(deferredRecordingDataItem.RecordedFilePath)) //check exist just in case file adopted by DataProviderManager { File.Delete(deferredRecordingDataItem.RecordedFilePath); } } //Time duration = new Time(currentPcmFormat.ConvertBytesToTime(currentPcmDataLength)); if (previousBytePosEnd < 0) { previousBytePosEnd = 0; } long bytePosEnd = deferredRecordingDataItem.RecordAndContinue_StopBytePos; openFile(treeNode, currentFileDataProvider, previousBytePosEnd, bytePosEnd, currentPcmFormat, currentPcmDataLength); } else { openFile(deferredRecordingDataItem.RecordedFilePath, true, true, State.Audio.PcmFormatRecordingMonitoring); } needsRefresh = true; //m_viewModel.CommandRefresh.Execute(); //if (m_viewModel.View != null) //{ // m_viewModel.View.CancelWaveFormLoad(true); //} if (!Settings.Default.Audio_DisableSingleWavFileRecord) { previousRecordedFile = deferredRecordingDataItem.RecordedFilePath; previousBytePosEnd = deferredRecordingDataItem.RecordAndContinue_StopBytePos; } } m_DeferredRecordingDataItems = null; Settings.Default.AudioWaveForm_DisableDraw = skipDrawing; if (needsRefresh) { CommandRefresh.Execute(); } }
/// <summary> /// takes wav file / mp3 file as input and converts it to wav file with audio format info supplied as parameter /// </summary> /// <param name="SourceFilePath"></param> /// <param name="destinationDirectory"></param> /// <param name="destinationFormatInfo"></param> /// <returns> full file path of converted file </returns> private string ConvertToDefaultFormat(string SourceFilePath, string destinationDirectory, PCMFormatInfo destinationFormatInfo, bool skipACM) { if (!File.Exists(SourceFilePath)) { throw new FileNotFoundException(SourceFilePath); } if (!Directory.Exists(destinationDirectory)) { FileDataProvider.CreateDirectory(destinationDirectory); } AudioFileType sourceFileType = GetAudioFileType(SourceFilePath); switch (sourceFileType) { case AudioFileType.WavUncompressed: case AudioFileType.WavCompressed: { if (FirstDiscoveredPCMFormat == null) { Stream wavStream = null; try { wavStream = File.Open(SourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); uint dataLength; AudioLibPCMFormat pcmInfo = null; pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength); //FirstDiscoveredPCMFormat = new PCMFormatInfo(pcmInfo); FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); FirstDiscoveredPCMFormat.CopyFrom(pcmInfo); } finally { if (wavStream != null) { wavStream.Close(); } } } WavFormatConverter formatConverter1 = new WavFormatConverter(true, skipACM); AddSubCancellable(formatConverter1); // Preserve existing WAV PCM format, the call below to ConvertSampleRate detects the equality of PCM formats and copies the audio file instead of resampling. AudioLibPCMFormat pcmFormat = m_autoDetectPcmFormat ? FirstDiscoveredPCMFormat : (destinationFormatInfo != null ? destinationFormatInfo.Data : new AudioLibPCMFormat()); string result = null; try { AudioLibPCMFormat originalPcmFormat; result = formatConverter1.ConvertSampleRate(SourceFilePath, destinationDirectory, pcmFormat, out originalPcmFormat); if (originalPcmFormat != null && FirstDiscoveredPCMFormat != null) { DebugFix.Assert(FirstDiscoveredPCMFormat.Equals(originalPcmFormat)); } } finally { RemoveSubCancellable(formatConverter1); } return(result); } case AudioFileType.Mp4_AAC: case AudioFileType.Mp3: { WavFormatConverter formatConverter2 = new WavFormatConverter(true, skipACM); AddSubCancellable(formatConverter2); string result = null; try { AudioLibPCMFormat pcmFormat = m_autoDetectPcmFormat ? FirstDiscoveredPCMFormat : // can be null! (destinationFormatInfo != null ? destinationFormatInfo.Data : new AudioLibPCMFormat()); AudioLibPCMFormat originalPcmFormat; if (sourceFileType == AudioFileType.Mp3) { result = formatConverter2.UnCompressMp3File(SourceFilePath, destinationDirectory, pcmFormat, out originalPcmFormat); } else { DebugFix.Assert(sourceFileType == AudioFileType.Mp4_AAC); result = formatConverter2.UnCompressMp4_AACFile(SourceFilePath, destinationDirectory, pcmFormat, out originalPcmFormat); } if (originalPcmFormat != null) { if (FirstDiscoveredPCMFormat == null) { //FirstDiscoveredPCMFormat = new PCMFormatInfo(originalPcmFormat); FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); FirstDiscoveredPCMFormat.CopyFrom(originalPcmFormat); } } } finally { RemoveSubCancellable(formatConverter2); } return(result); } default: throw new Exception("Source file format not supported"); } }
private void OnClick_ButtonExport(object sender, RoutedEventArgs e) { m_Logger.Log("DescriptionView.OnClick_ButtonExport", Category.Debug, Priority.Medium); Tuple <TreeNode, TreeNode> selection = m_Session.GetTreeNodeSelection(); TreeNode node = selection.Item2 ?? selection.Item1; if (node == null || node.GetAlternateContentProperty() == null || node.GetImageMedia() == null || !(node.GetImageMedia() is ManagedImageMedia)) { return; } SampleRate sampleRate = SampleRate.Hz22050; sampleRate = Urakawa.Settings.Default.AudioExportSampleRate; bool encodeToMp3 = true; encodeToMp3 = Urakawa.Settings.Default.AudioExportEncodeToMp3; var combo = new ComboBox { Margin = new Thickness(0, 0, 0, 12) }; ComboBoxItem item1 = new ComboBoxItem(); item1.Content = AudioLib.SampleRate.Hz11025.ToString(); combo.Items.Add(item1); ComboBoxItem item2 = new ComboBoxItem(); item2.Content = AudioLib.SampleRate.Hz22050.ToString(); combo.Items.Add(item2); ComboBoxItem item3 = new ComboBoxItem(); item3.Content = AudioLib.SampleRate.Hz44100.ToString(); combo.Items.Add(item3); switch (sampleRate) { case AudioLib.SampleRate.Hz11025: { combo.SelectedItem = item1; combo.Text = item1.Content.ToString(); break; } case AudioLib.SampleRate.Hz22050: { combo.SelectedItem = item2; combo.Text = item2.Content.ToString(); break; } case AudioLib.SampleRate.Hz44100: { combo.SelectedItem = item3; combo.Text = item3.Content.ToString(); break; } } var checkBox = new CheckBox { IsThreeState = false, IsChecked = encodeToMp3, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; var label_ = new TextBlock { Text = Tobi_Plugin_Urakawa_Lang.ExportEncodeMp3, Margin = new Thickness(8, 0, 8, 0), HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Focusable = true, TextWrapping = TextWrapping.Wrap }; var panel__ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; panel__.Children.Add(label_); panel__.Children.Add(checkBox); var panel_ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Vertical, HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center, }; panel_.Children.Add(combo); panel_.Children.Add(panel__); var windowPopup_ = new PopupModalWindow(m_ShellView, UserInterfaceStrings.EscapeMnemonic(Tobi_Plugin_Urakawa_Lang.ExportSettings), panel_, PopupModalWindow.DialogButtonsSet.OkCancel, PopupModalWindow.DialogButton.Ok, false, 300, 180, null, 40, m_DescriptionPopupModalWindow); windowPopup_.EnableEnterKeyDefault = true; windowPopup_.ShowModal(); if (!PopupModalWindow.IsButtonOkYesApply(windowPopup_.ClickedDialogButton)) { return; } encodeToMp3 = checkBox.IsChecked.Value; Urakawa.Settings.Default.AudioExportEncodeToMp3 = checkBox.IsChecked.Value; if (combo.SelectedItem == item1) { sampleRate = SampleRate.Hz11025; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } else if (combo.SelectedItem == item2) { sampleRate = SampleRate.Hz22050; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } else if (combo.SelectedItem == item3) { sampleRate = SampleRate.Hz44100; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } string rootFolder = Path.GetDirectoryName(m_Session.DocumentFilePath); var dlg = new FolderBrowserDialog { RootFolder = Environment.SpecialFolder.MyComputer, SelectedPath = rootFolder, ShowNewFolderButton = true, Description = @"Tobi: " + UserInterfaceStrings.EscapeMnemonic("Export DIAGRAM XML") }; DialogResult result = DialogResult.Abort; m_ShellView.DimBackgroundWhile(() => { result = dlg.ShowDialog(); }); if (result != DialogResult.OK && result != DialogResult.Yes) { return; } if (!Directory.Exists(dlg.SelectedPath)) { return; } ManagedImageMedia managedImage = (ManagedImageMedia)node.GetImageMedia(); string exportImageName = //Path.GetFileName FileDataProvider.EliminateForbiddenFileNameCharacters (managedImage.ImageMediaData.OriginalRelativePath) ; string imageDescriptionDirectoryPath = Daisy3_Export.GetAndCreateImageDescriptionDirectoryPath(false, exportImageName, dlg.SelectedPath); if (Directory.Exists(imageDescriptionDirectoryPath)) { if (!m_Session.askUserConfirmOverwriteFileFolder(imageDescriptionDirectoryPath, true, m_DescriptionPopupModalWindow)) { return; } FileDataProvider.TryDeleteDirectory(imageDescriptionDirectoryPath, true); } FileDataProvider.CreateDirectory(imageDescriptionDirectoryPath); PCMFormatInfo audioFormat = node.Presentation.MediaDataManager.DefaultPCMFormat; AudioLibPCMFormat pcmFormat = audioFormat.Data; if ((ushort)sampleRate != pcmFormat.SampleRate) { pcmFormat.SampleRate = (ushort)sampleRate; } Application.Current.MainWindow.Cursor = Cursors.Wait; this.Cursor = Cursors.Wait; //m_ShellView try { string descriptionFile = Daisy3_Export.CreateImageDescription( Urakawa.Settings.Default.AudioCodecDisableACM, pcmFormat, encodeToMp3, 0, imageDescriptionDirectoryPath, exportImageName, node.GetAlternateContentProperty(), null, null, null); } finally { Application.Current.MainWindow.Cursor = Cursors.Arrow; this.Cursor = Cursors.Arrow; //m_ShellView } m_ShellView.ExecuteShellProcess(imageDescriptionDirectoryPath); }
private void EncodeTransientFileToMp4OrAMR(TreeNode node) { ExternalAudioMedia extMedia = m_ExternalAudioMediaList[0]; AudioLib.WavFormatConverter formatConverter = new WavFormatConverter(true, DisableAcmCodecs); string sourceFilePath = base.GetCurrentAudioFileUri().LocalPath; string extension = EncodingFileFormat == AudioFileFormats.MP4 ? DataProviderFactory.AUDIO_MP4_EXTENSION : EncodingFileFormat == AudioFileFormats.AMR ? DataProviderFactory.AUDIO_AMR_EXTENSION : DataProviderFactory.AUDIO_3GPP_EXTENSION; string destinationFilePath = Path.Combine(base.DestinationDirectory.LocalPath, Path.GetFileNameWithoutExtension(sourceFilePath) + extension); //reportProgress(m_ProgressPercentage, String.Format(UrakawaSDK_daisy_Lang.CreateMP3File, Path.GetFileName(destinationFilePath), GetSizeInfo(m_RootNode))); PCMFormatInfo audioFormat = extMedia.Presentation.MediaDataManager.DefaultPCMFormat; //AudioLibPCMFormat pcmFormat = audioFormat.Data; AudioLibPCMFormat pcmFormat = new AudioLibPCMFormat(); pcmFormat.CopyFrom(audioFormat.Data); pcmFormat.SampleRate = (ushort)base.EncodePublishedAudioFilesSampleRate; pcmFormat.NumberOfChannels = (ushort)(base.EncodePublishedAudioFilesStereo ? 2 : 1); AddSubCancellable(formatConverter); bool result = false; try { result = formatConverter.CompressWavToMP4And3GP(sourceFilePath, destinationFilePath, pcmFormat, BitRate_Encoding); } finally { RemoveSubCancellable(formatConverter); } if (RequestCancellation) { m_ExternalAudioMediaList.Clear(); return; } if (result) { m_EncodingFileCompressionRatio = (new FileInfo(sourceFilePath).Length) / (new FileInfo(destinationFilePath).Length); foreach (ExternalAudioMedia ext in m_ExternalAudioMediaList) { if (ext != null) { ext.Src = ext.Src.Replace(DataProviderFactory.AUDIO_WAV_EXTENSION, extension); } } File.Delete(sourceFilePath); } else { // append error messages base.ErrorMessages = base.ErrorMessages + String.Format(UrakawaSDK_daisy_Lang.ErrorInEncoding, Path.GetFileName(sourceFilePath)); } m_ExternalAudioMediaList.Clear(); }
private void EncodeTransientFileResample(TreeNode node) { string sourceFilePath = base.GetCurrentAudioFileUri().LocalPath; //string destinationFilePath = Path.Combine(base.DestinationDirectory.LocalPath, Path.GetFileNameWithoutExtension(sourceFilePath) + "_" + base.EncodePublishedAudioFilesSampleRate + DataProviderFactory.AUDIO_WAV_EXTENSION); //reportProgress(m_ProgressPercentage, String.Format(UrakawaSDK_daisy_Lang.ConvertingAudio,sourceFilePath)); ExternalAudioMedia extMedia = m_ExternalAudioMediaList[0]; PCMFormatInfo audioFormat = extMedia.Presentation.MediaDataManager.DefaultPCMFormat; //AudioLibPCMFormat pcmFormat = audioFormat.Data; AudioLibPCMFormat pcmFormat = new AudioLibPCMFormat(); pcmFormat.CopyFrom(audioFormat.Data); pcmFormat.SampleRate = (ushort)base.EncodePublishedAudioFilesSampleRate; pcmFormat.NumberOfChannels = (ushort)(base.EncodePublishedAudioFilesStereo ? 2 : 1); AudioLib.WavFormatConverter formatConverter = new WavFormatConverter(true, DisableAcmCodecs); AddSubCancellable(formatConverter); string destinationFilePath = null; try { AudioLibPCMFormat originalPcmFormat; destinationFilePath = formatConverter.ConvertSampleRate(sourceFilePath, base.DestinationDirectory.LocalPath, pcmFormat, out originalPcmFormat); if (originalPcmFormat != null) { DebugFix.Assert(audioFormat.Data.Equals(originalPcmFormat)); } } finally { RemoveSubCancellable(formatConverter); } //string sourceName = Path.GetFileNameWithoutExtension(sourceFilePath); //string destName = Path.GetFileNameWithoutExtension(destinationFilePath); //foreach (ExternalAudioMedia ext in m_ExternalAudioMediaList) //{ //if (ext != null) //{ //ext.Src = ext.Src.Replace(sourceName, destName); //} //} File.Delete(sourceFilePath); File.Move(destinationFilePath, sourceFilePath); try { File.SetAttributes(sourceFilePath, FileAttributes.Normal); } catch { } m_ExternalAudioMediaList.Clear(); }
protected void setDevicePCMFormat(PCMFormatInfo pcmFormat) { mPlaybackAudioDevice.setNumberOfChannels(pcmFormat.NumberOfChannels); mPlaybackAudioDevice.setSampleRate(pcmFormat.SampleRate); mPlaybackAudioDevice.setBitDepth(pcmFormat.BitDepth); }
protected virtual void parseContentDocuments(List <string> spineOfContentDocuments, Dictionary <string, string> spineAttributes, List <Dictionary <string, string> > spineItemsAttributes, string coverImagePath, string navDocPath) { if (spineOfContentDocuments == null || spineOfContentDocuments.Count <= 0) { return; } Presentation spinePresentation = m_Project.Presentations.Get(0); spinePresentation.RootNode.GetOrCreateXmlProperty().SetQName("spine", ""); if (!string.IsNullOrEmpty(m_OPF_ContainerRelativePath)) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(OPF_ContainerRelativePath, "", m_OPF_ContainerRelativePath); } foreach (KeyValuePair <string, string> spineAttribute in spineAttributes) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(spineAttribute.Key, "", spineAttribute.Value); } if (m_PackagePrefixAttr != null) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute("prefix", "", m_PackagePrefixAttr.Value); } // Audio files may be shared between chapters of a book! m_OriginalAudioFile_FileDataProviderMap.Clear(); Presentation spineItemPresentation = null; int index = -1; foreach (string docPath in spineOfContentDocuments) { index++; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ReadXMLDoc, docPath)); //DirectoryInfo opfParentDir = Directory.GetParent(m_Book_FilePath); //string dirPath = opfParentDir.ToString(); string fullDocPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), docPath); fullDocPath = FileDataProvider.NormaliseFullFilePath(fullDocPath).Replace('/', '\\'); if (!File.Exists(fullDocPath)) { #if DEBUG Debugger.Break(); #endif //DEBUG continue; } addOPF_GlobalAssetPath(fullDocPath); TreeNode spineChild = spinePresentation.TreeNodeFactory.Create(); TextMedia txt = spinePresentation.MediaFactory.CreateTextMedia(); txt.Text = docPath; // Path.GetFileName(fullDocPath); spineChild.GetOrCreateChannelsProperty().SetMedia(spinePresentation.ChannelsManager.GetOrCreateTextChannel(), txt); spinePresentation.RootNode.AppendChild(spineChild); spineChild.GetOrCreateXmlProperty().SetQName("metadata", ""); foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index]) { spineChild.GetOrCreateXmlProperty().SetAttribute(spineItemAttribute.Key, "", spineItemAttribute.Value); } string ext = Path.GetExtension(fullDocPath); if (docPath == coverImagePath) { DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase)); spineChild.GetOrCreateXmlProperty().SetAttribute("cover-image", "", "true"); } if (docPath == navDocPath) { DebugFix.Assert( ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) || ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase)); spineChild.GetOrCreateXmlProperty().SetAttribute("nav", "", "true"); } if ( !ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.DTBOOK_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.XML_EXTENSION, StringComparison.OrdinalIgnoreCase) ) { DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase)); bool notExistYet = true; foreach (ExternalFiles.ExternalFileData externalFileData in m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { if (!string.IsNullOrEmpty(externalFileData.OriginalRelativePath)) { bool notExist = docPath != externalFileData.OriginalRelativePath; notExistYet = notExistYet && notExist; if (!notExist) { break; } } } DebugFix.Assert(notExistYet); if (notExistYet) { ExternalFiles.ExternalFileData externalData = null; if (docPath == coverImagePath) { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.CoverImageExternalFileData>(); } else { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>(); } if (externalData != null) { externalData.InitializeWithData(fullDocPath, docPath, true, null); addOPF_GlobalAssetPath(fullDocPath); } } continue; } spineChild.GetOrCreateXmlProperty().SetAttribute("xuk", "", "true"); XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullDocPath, true, true); if (RequestCancellation) { return; } m_PublicationUniqueIdentifier = null; m_PublicationUniqueIdentifierNode = null; Project spineItemProject = new Project(); spineItemProject.PrettyFormat = m_XukPrettyFormat; string dataFolderPrefix = FileDataProvider.EliminateForbiddenFileNameCharacters(docPath); spineItemPresentation = spineItemProject.AddNewPresentation(new Uri(m_outDirectory), //Path.GetFileName(fullDocPath) dataFolderPrefix ); PCMFormatInfo pcmFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //.Copy(); pcmFormat.Data.SampleRate = (ushort)m_audioProjectSampleRate; pcmFormat.Data.NumberOfChannels = m_audioStereo ? (ushort)2 : (ushort)1; spineItemPresentation.MediaDataManager.DefaultPCMFormat = pcmFormat; //presentation.MediaDataManager.EnforceSinglePCMFormat = true; //presentation.MediaDataFactory.DefaultAudioMediaDataType = typeof(WavAudioMediaData); TextChannel textChannel = spineItemPresentation.ChannelFactory.CreateTextChannel(); textChannel.Name = "The Text Channel"; DebugFix.Assert(textChannel == spineItemPresentation.ChannelsManager.GetOrCreateTextChannel()); AudioChannel audioChannel = spineItemPresentation.ChannelFactory.CreateAudioChannel(); audioChannel.Name = "The Audio Channel"; DebugFix.Assert(audioChannel == spineItemPresentation.ChannelsManager.GetOrCreateAudioChannel()); ImageChannel imageChannel = spineItemPresentation.ChannelFactory.CreateImageChannel(); imageChannel.Name = "The Image Channel"; DebugFix.Assert(imageChannel == spineItemPresentation.ChannelsManager.GetOrCreateImageChannel()); VideoChannel videoChannel = spineItemPresentation.ChannelFactory.CreateVideoChannel(); videoChannel.Name = "The Video Channel"; DebugFix.Assert(videoChannel == spineItemPresentation.ChannelsManager.GetOrCreateVideoChannel()); /*string dataPath = presentation.DataProviderManager.DataFileDirectoryFullPath; * if (Directory.Exists(dataPath)) * { * Directory.Delete(dataPath, true); * }*/ //AudioLibPCMFormat previousPcm = null; if (m_AudioConversionSession != null) { //previousPcm = m_AudioConversionSession.FirstDiscoveredPCMFormat; RemoveSubCancellable(m_AudioConversionSession); m_AudioConversionSession = null; } m_AudioConversionSession = new AudioFormatConvertorSession( //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY, spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath, spineItemPresentation.MediaDataManager.DefaultPCMFormat, m_autoDetectPcmFormat, m_SkipACM); //if (previousPcm != null) //{ // m_AudioConversionSession.FirstDiscoveredPCMFormat = previousPcm; //} AddSubCancellable(m_AudioConversionSession); TreenodesWithoutManagedAudioMediaData = new List <TreeNode>(); //foreach (var key in m_OriginalAudioFile_FileDataProviderMap.Keys) //{ // FileDataProvider dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //VERSUS// // FileDataProvider dataProv = new FileDataProvider(); // dataProv.MimeType = DataProviderFactory.AUDIO_WAV_MIME_TYPE; //} //m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable if (RequestCancellation) { return; } if (parseContentDocParts(fullDocPath, spineItemProject, xmlDoc, docPath, DocumentMarkupType.NA)) { return; // user cancel } //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMetadata, docPath)); //parseMetadata(fullDocPath, project, xmlDoc); //if (RequestCancellation) return; //ParseHeadLinks(fullDocPath, project, xmlDoc); //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingContent, docPath)); //parseContentDocument(fullDocPath, project, xmlDoc, null, fullDocPath, null, DocumentMarkupType.NA); string title = GetTitle(spineItemPresentation); if (!string.IsNullOrEmpty(title)) { spineChild.GetOrCreateXmlProperty().SetAttribute("title", "", title); } if (false) // do not copy metadata from project to individual chapter { foreach (Metadata metadata in m_Project.Presentations.Get(0).Metadatas.ContentsAs_Enumerable) { Metadata md = spineItemPresentation.MetadataFactory.CreateMetadata(); md.NameContentAttribute = metadata.NameContentAttribute.Copy(); foreach (MetadataAttribute metadataAttribute in metadata.OtherAttributes.ContentsAs_Enumerable) { MetadataAttribute mdAttr = metadataAttribute.Copy(); md.OtherAttributes.Insert(md.OtherAttributes.Count, mdAttr); } spineItemPresentation.Metadatas.Insert(spineItemPresentation.Metadatas.Count, md); } } //XmlNodeList listOfBodies = xmlDoc.GetElementsByTagName("body"); //if (listOfBodies.Count == 0) //{ // listOfBodies = xmlDoc.GetElementsByTagName("book"); //} //XmlNode bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "body", null); //if (bodyElement == null) //{ // bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "book", null); //} //if (bodyElement == null) //{ // continue; //} // TODO: return hierarchical outline where each node points to a XUK relative path, + XukAble.Uid (TreeNode are not corrupted during XukAbleManager.RegenerateUids(); foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index]) { if (spineItemAttribute.Key == "media-overlay") { string opfDirPath = Path.GetDirectoryName(m_Book_FilePath); string overlayPath = spineItemAttribute.Value; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMediaOverlay, overlayPath)); string fullOverlayPath = Path.Combine(opfDirPath, overlayPath); if (!File.Exists(fullOverlayPath)) { continue; } XmlDocument overlayXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullOverlayPath, false, false); IEnumerable <XmlNode> audioElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "audio", null, false); if (audioElements == null) { continue; } foreach (XmlNode audioNode in audioElements) { XmlAttributeCollection attrs = audioNode.Attributes; if (attrs == null) { continue; } XmlNode attrSrc = attrs.GetNamedItem("src"); if (attrSrc == null) { continue; } //XmlNode attrBegin = attrs.GetNamedItem("clipBegin"); //XmlNode attrEnd = attrs.GetNamedItem("clipEnd"); //string overlayDirPath = Path.GetDirectoryName(fullOverlayPath); //string fullAudioPath = Path.Combine(overlayDirPath, attrSrc.Value); //if (!File.Exists(fullAudioPath)) //{ // continue; //} //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.DecodingAudio, Path.GetFileName(fullAudioPath))); TreeNode textTreeNode = null; XmlNodeList children = audioNode.ParentNode.ChildNodes; foreach (XmlNode child in children) { if (child == audioNode) { continue; } if (child.LocalName != "text") { continue; } XmlAttributeCollection textAttrs = child.Attributes; if (textAttrs == null) { continue; } XmlNode textSrc = textAttrs.GetNamedItem("src"); if (textSrc == null) { continue; } string urlDecoded = FileDataProvider.UriDecode(textSrc.Value); if (urlDecoded.IndexOf('#') > 0) { string[] srcParts = urlDecoded.Split('#'); if (srcParts.Length != 2) { continue; } string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath), srcParts[0]); fullTextRefPath = FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\'); if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase)) { //#if DEBUG // Debugger.Break(); //#endif //DEBUG continue; } string txtId = srcParts[1]; textTreeNode = spineItemPresentation.RootNode.GetFirstDescendantWithXmlID(txtId); } else { string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath), urlDecoded); fullTextRefPath = FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\'); if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase)) { //#if DEBUG // Debugger.Break(); //#endif //DEBUG continue; } textTreeNode = spineItemPresentation.RootNode; } } if (textTreeNode != null) { addAudio(textTreeNode, audioNode, false, fullOverlayPath); } } } } spinePresentation.MediaDataManager.DefaultPCMFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //copied! string xuk_FilePath = GetXukFilePath_SpineItem(m_outDirectory, docPath, title, index); string xukFileName = Path.GetFileName(xuk_FilePath); spineChild.GetOrCreateXmlProperty().SetAttribute("xukFileName", "", xukFileName); //deleteDataDirectoryIfEmpty(); string dataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath; spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(Path.GetFileNameWithoutExtension(xuk_FilePath)); string newDataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath; DebugFix.Assert(Directory.Exists(newDataFolderPath)); if (newDataFolderPath != dataFolderPath) { try { if (Directory.Exists(newDataFolderPath)) { FileDataProvider.TryDeleteDirectory(newDataFolderPath, false); } Directory.Move(dataFolderPath, newDataFolderPath); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif // DEBUG Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(dataFolderPrefix); } } spineItemProject.PrettyFormat = m_XukPrettyFormat; SaveXukAction action = new SaveXukAction(spineItemProject, spineItemProject, new Uri(xuk_FilePath), true); action.ShortDescription = UrakawaSDK_daisy_Lang.SavingXUKFile; action.LongDescription = UrakawaSDK_daisy_Lang.SerializeDOMIntoXUKFile; action.Progress += new EventHandler <ProgressEventArgs>( delegate(object sender, ProgressEventArgs e) { double val = e.Current; double max = e.Total; int percent = -1; if (val != max) { percent = (int)((val / max) * 100); } reportProgress_Throttle(percent, val + "/" + max); //reportProgress(-1, action.LongDescription); if (RequestCancellation) { e.Cancel(); } } ); action.Finished += new EventHandler <FinishedEventArgs>( delegate(object sender, FinishedEventArgs e) { reportProgress(100, UrakawaSDK_daisy_Lang.XUKSaved); } ); action.Cancelled += new EventHandler <CancelledEventArgs>( delegate(object sender, CancelledEventArgs e) { reportProgress(0, UrakawaSDK_daisy_Lang.CancelledXUKSaving); } ); action.DoWork(); //if (first) //{ // Presentation presentation = m_Project.Presentations.Get(0); // XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty(); // xmlProp.LocalName = "book"; // presentation.PropertyFactory.DefaultXmlNamespaceUri = bodyElement.NamespaceURI; // xmlProp.NamespaceUri = presentation.PropertyFactory.DefaultXmlNamespaceUri; // TreeNode treeNode = presentation.TreeNodeFactory.Create(); // treeNode.AddProperty(xmlProp); // presentation.RootNode = treeNode; // first = false; //} //foreach (XmlNode childOfBody in bodyElement.ChildNodes) //{ // parseContentDocument(childOfBody, m_Project.Presentations.Get(0).RootNode, fullDocPath); //} } }
internal void CreateNewPresentationInBackend(string path, string title, bool createTitleSection, string id, Settings settings, bool isStubProjectForImport, int audioChannels, int audioSampleRate) { mProject = new Project(); #if false //(DEBUG) mProject.PrettyFormat = true; #else mProject.PrettyFormat = false; #endif string parentDirectory = System.IO.Path.GetDirectoryName(path); Uri obiProjectDirectory = new Uri(parentDirectory); //Presentation presentation = mProject.AddNewPresentation(obiProjectDirectory, System.IO.Path.GetFileName(path)); //ObiPresentation newPres = mProject.PresentationFactory.Create(mProject, obiProjectDirectory, System.IO.Path.GetFileName(path)); ObiPresentation newPres = mProject.PresentationFactory.Create <ObiPresentation>(); newPres.Project = mProject; newPres.RootUri = obiProjectDirectory; //TODO: it would be good for Obi to separate Data folder based on project file name, //TODO: otherwise collision of Data folder may happen if several project files are in same directory. //newPres.DataProviderManager.SetDataFileDirectoryWithPrefix(System.IO.Path.GetFileName(path)); #if DEBUG newPres.WarmUpAllFactories(); #endif mProject.Presentations.Insert(mProject.Presentations.Count, newPres); PCMFormatInfo pcmFormat = new PCMFormatInfo((ushort)audioChannels, (uint)audioSampleRate, (ushort)settings.Audio_BitDepth); newPres.MediaDataManager.DefaultPCMFormat = pcmFormat; newPres.MediaDataManager.EnforceSinglePCMFormat = true; newPres.ChannelsManager.GetOrCreateTextChannel(); //m_textChannel = presentation.ChannelFactory.CreateTextChannel(); //m_textChannel.Name = "The Text Channel"; newPres.ChannelsManager.GetOrCreateAudioChannel(); //m_audioChannel = presentation.ChannelFactory.CreateAudioChannel(); //m_audioChannel.Name = "The Audio Channel"; ObiRootNode rootNode = newPres.TreeNodeFactory.Create <ObiRootNode>(); newPres.RootNode = rootNode; //sdk2 //mProject.setDataModelFactory ( mDataModelFactory ); //mProject.setPresentation ( mDataModelFactory.createPresentation (), 0 ); mPath = path; GetLock(mPath); mChangesCount = 0; newPres.Initialize(this, title, createTitleSection, id, settings, isStubProjectForImport); //sdk2 //Presentation.setRootUri ( new Uri ( path ) ); //sdk2 // create data directory if it is not created //string dataDirectory = ((urakawa.media.data.FileDataProviderManager)Presentation.getDataProviderManager ()).getDataFileDirectoryFullPath (); //if ( !Directory.Exists (dataDirectory ) ) // { // Directory.CreateDirectory ( dataDirectory ); // } //if (ProjectCreated != null) ProjectCreated ( this, null ); SetupBackupFilesForNewSession(path); ShouldDisableDiskSpaceCheck(); Save(mPath); //ForceSave (); }
private static void CheckPublishedFiles(TreeNode node, Channel sourceCh, Channel destCh, Uri curWavUri_, MemoryStream curAudioData, PCMFormatInfo curPCMFormat) { Uri curWavUri = (curWavUri_ == null ? null : new Uri(curWavUri_.ToString())); if (node.HasProperties(typeof(ChannelsProperty))) { ChannelsProperty chProp = node.GetProperty <ChannelsProperty>(); ManagedAudioMedia mam = chProp.GetMedia(sourceCh) as ManagedAudioMedia; ExternalAudioMedia eam = chProp.GetMedia(destCh) as ExternalAudioMedia; Assert.AreEqual(mam == null, eam == null, "There may be external audio media if and only if there is managed audio media"); if (mam != null && eam != null) { Assert.IsTrue(mam.Duration.IsEqualTo(eam.Duration), "Duration of managed and external audio media differs"); if (eam.Uri != null) { FileStream wavFS_ = new FileStream(eam.Uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.None); Stream manAudioStream = mam.AudioMediaData.OpenPcmInputStream(); try { uint dataLength; AudioLibPCMFormat pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavFS_, out dataLength); Assert.IsTrue(pcmInfo.IsCompatibleWith(mam.AudioMediaData.PCMFormat.Data), "External audio has incompatible pcm format"); wavFS_.Position += pcmInfo.ConvertTimeToBytes(eam.ClipBegin.TimeAsMillisecondFloat); Assert.IsTrue( AudioLibPCMFormat.CompareStreamData(manAudioStream, wavFS_, (int)manAudioStream.Length), "External audio contains wrong data"); } finally { wavFS_.Close(); manAudioStream.Close(); } } if (curWavUri != null) { FileStream wavFS = new FileStream(curWavUri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.None); try { uint dataLength; AudioLibPCMFormat pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavFS, out dataLength); Assert.IsTrue(pcmInfo.IsCompatibleWith(curPCMFormat.Data), "External audio has incompatible pcm format"); curAudioData.Position = 0; Assert.AreEqual(curAudioData.Length, (long)dataLength, "External audio has unexpected length"); Assert.IsTrue( AudioLibPCMFormat.CompareStreamData(curAudioData, wavFS, (int)curAudioData.Length), "External audio contains wrong data"); } finally { wavFS.Close(); } } if (curWavUri == null) { curWavUri = new Uri(eam.Uri.ToString()); curAudioData = new MemoryStream(); curPCMFormat = mam.AudioMediaData.PCMFormat; } else if (curWavUri.ToString() != eam.Uri.ToString()) { curWavUri = new Uri(eam.Uri.ToString()); curAudioData = new MemoryStream(); curPCMFormat = mam.AudioMediaData.PCMFormat; } Assert.IsTrue(curPCMFormat.ValueEquals(mam.AudioMediaData.PCMFormat), "Managed audio has incompatible pcm format"); Stream manAudio = mam.AudioMediaData.OpenPcmInputStream(); try { media.data.StreamUtils.CopyData(manAudio, curAudioData); } finally { manAudio.Close(); } } } foreach (TreeNode child in node.Children.ContentsAs_YieldEnumerable) { CheckPublishedFiles(child, sourceCh, destCh, curWavUri, curAudioData, curPCMFormat); } }