public override void UnExecute() { ChannelsProperty chProp = m_SelectionData.m_TreeNode.GetOrCreateChannelsProperty(); ManagedAudioMedia manMed = m_SelectionData.m_TreeNode.GetManagedAudioMedia(); if (manMed != null) { chProp.SetMedia(ChannelOfOriginalMedia, null); } chProp.SetMedia(ChannelOfOriginalMedia, OriginalManagedAudioMedia.Copy()); }
public override void Execute() { ManagedAudioMedia audioMedia = m_SelectionData.m_TreeNode.GetManagedAudioMedia(); AudioMediaData mediaData = audioMedia.AudioMediaData; Time timeBegin = SelectionData.m_LocalStreamLeftMark == -1 ? Time.Zero : new Time(mediaData.PCMFormat.Data.ConvertBytesToTime(SelectionData.m_LocalStreamLeftMark)); Time timeEnd = SelectionData.m_LocalStreamRightMark == -1 ? Time.Zero : new Time(mediaData.PCMFormat.Data.ConvertBytesToTime(SelectionData.m_LocalStreamRightMark)); if (SelectionData.TimeBeginEndEqualClipDuration(timeBegin, timeEnd, mediaData)) { ChannelsProperty chProp = m_SelectionData.m_TreeNode.GetChannelsProperty(); chProp.SetMedia(ChannelOfOriginalMedia, null); } else if (SelectionData.TimeBeginEndEqualClipDuration(new Time(), timeEnd, mediaData)) { mediaData.RemovePcmData(timeBegin); } else { mediaData.RemovePcmData(timeBegin, timeEnd); } }
protected virtual void AddPagePropertiesToAudioNode(TreeNode audioWrapperNode, XmlNode pageTargetNode) { TextMedia textMedia = audioWrapperNode.Presentation.MediaFactory.CreateTextMedia(); textMedia.Text = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(pageTargetNode, true, "text", pageTargetNode.NamespaceURI).InnerText; ChannelsProperty cProp = audioWrapperNode.Presentation.PropertyFactory.CreateChannelsProperty(); cProp.SetMedia(audioWrapperNode.Presentation.ChannelsManager.GetOrCreateTextChannel(), textMedia); audioWrapperNode.AddProperty(cProp); System.Xml.XmlAttributeCollection pageAttributes = pageTargetNode.Attributes; if (pageAttributes != null) { XmlProperty xmlProp = audioWrapperNode.GetXmlProperty(); xmlProp.SetQName("pagenum", ""); string nsUri = audioWrapperNode.GetXmlNamespaceUri(); foreach (System.Xml.XmlAttribute attr in pageAttributes) { string uri = ""; if (!string.IsNullOrEmpty(attr.NamespaceURI)) { if (attr.NamespaceURI != nsUri) { uri = attr.NamespaceURI; } } xmlProp.SetAttribute(attr.Name, uri, attr.Value); } } }
protected virtual TreeNode CheckAndAssignForHeadingAudio(TreeNode navPointTreeNode, TreeNode phraseTreeNode, XmlNode audioXmlNode) { XmlNode navLabelXmlNode = m_NavPointNode_NavLabelMap[navPointTreeNode]; XmlNode headingAudio = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(navLabelXmlNode, true, "audio", navLabelXmlNode.NamespaceURI); XmlNode textNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(navLabelXmlNode, true, "text", navLabelXmlNode.NamespaceURI); double headingClipBegin = Math.Abs((new urakawa.media.timing.Time(headingAudio.Attributes.GetNamedItem("clipBegin").Value)).AsMilliseconds); double headingClipEnd = Math.Abs((new urakawa.media.timing.Time(headingAudio.Attributes.GetNamedItem("clipEnd").Value)).AsMilliseconds); double audioClipBegin = Math.Abs((new urakawa.media.timing.Time(audioXmlNode.Attributes.GetNamedItem("clipBegin").Value)).AsMilliseconds); double audioClipEnd = Math.Abs((new urakawa.media.timing.Time(audioXmlNode.Attributes.GetNamedItem("clipEnd").Value)).AsMilliseconds); if (headingAudio.Attributes.GetNamedItem("src").Value == audioXmlNode.Attributes.GetNamedItem("src").Value && Math.Abs(headingClipBegin - audioClipBegin) <= 1 && Math.Abs(headingClipEnd - audioClipEnd) <= 1) { TextMedia textMedia = navPointTreeNode.Presentation.MediaFactory.CreateTextMedia(); textMedia.Text = textNode.InnerText; ChannelsProperty cProp = navPointTreeNode.Presentation.PropertyFactory.CreateChannelsProperty(); cProp.SetMedia(navPointTreeNode.Presentation.ChannelsManager.GetOrCreateTextChannel(), textMedia); //TreeNode txtWrapperNode = parentNode.Presentation.TreeNodeFactory.Create(); phraseTreeNode.AddProperty(cProp); //treeNode.AppendChild(txtWrapperNode); XmlProperty TextNodeXmlProp = navPointTreeNode.Presentation.PropertyFactory.CreateXmlProperty(); phraseTreeNode.AddProperty(TextNodeXmlProp); TextNodeXmlProp.SetQName("hd", ""); } return(phraseTreeNode); }
public override void UnExecute() { AudioChannel audioChannel = Presentation.ChannelsManager.GetOrCreateAudioChannel(); ChannelsProperty chProp = m_TreeNode.GetOrCreateChannelsProperty(); chProp.SetMedia(audioChannel, null); }
public override void UnExecute() { ManagedAudioMedia manMedia = TreeNode.GetManagedAudioMedia(); ChannelsProperty chProp = TreeNode.GetChannelsProperty(); Channel channel = null; foreach (Channel ch in chProp.UsedChannels) { if (manMedia == chProp.GetMedia(ch)) { channel = ch; break; } } chProp.SetMedia(channel, null); chProp.SetMedia(channel, OriginalManagedAudioMedia.Copy()); //Time duration = ManagedAudioMediaSource.Duration; //ManagedAudioMediaTarget.AudioMediaData.RemovePcmData(TimeInsert, TimeInsert.Add(duration)); }
private void parseContentDocument(XmlNode xmlNode, TreeNode parentTreeNode, string filePath) { XmlNodeType xmlType = xmlNode.NodeType; switch (xmlType) { case XmlNodeType.Attribute: { System.Diagnostics.Debug.Fail("Calling this method with an XmlAttribute should never happen !!"); break; } case XmlNodeType.Document: { //XmlNodeList listOfBodies = ((XmlDocument)xmlNode).GetElementsByTagName("body"); //if (listOfBodies.Count == 0) //{ // listOfBodies = ((XmlDocument)xmlNode).GetElementsByTagName("book"); //} XmlNode bodyElement = getFirstChildElementsWithName(xmlNode, true, "body", null); if (bodyElement == null) { bodyElement = getFirstChildElementsWithName(xmlNode, true, "book", null); } if (bodyElement != null) { Presentation presentation = m_Project.Presentations.Get(0); presentation.PropertyFactory.DefaultXmlNamespaceUri = bodyElement.NamespaceURI; // preserve internal DTD if it exists in dtbook string strInternalDTD = ExtractInternalDTD(((XmlDocument)xmlNode).DocumentType); if (strInternalDTD != null) { File.WriteAllText( Path.Combine(presentation.DataProviderManager.DataFileDirectoryFullPath, "DTBookLocalDTD.dtd"), strInternalDTD); } parseContentDocument(bodyElement, parentTreeNode, filePath); } //parseContentDocument(((XmlDocument)xmlNode).DocumentElement, parentTreeNode); break; } case XmlNodeType.Element: { Presentation presentation = m_Project.Presentations.Get(0); TreeNode treeNode = presentation.TreeNodeFactory.Create(); if (parentTreeNode == null) { presentation.RootNode = treeNode; parentTreeNode = presentation.RootNode; } else { parentTreeNode.AppendChild(treeNode); } XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty(); treeNode.AddProperty(xmlProp); xmlProp.LocalName = xmlNode.LocalName; if (xmlNode.ParentNode != null && xmlNode.ParentNode.NodeType == XmlNodeType.Document) { presentation.PropertyFactory.DefaultXmlNamespaceUri = xmlNode.NamespaceURI; } if (xmlNode.NamespaceURI != presentation.PropertyFactory.DefaultXmlNamespaceUri) { xmlProp.NamespaceUri = xmlNode.NamespaceURI; } string updatedSRC = null; if (xmlNode.LocalName == "img") { XmlNode getSRC = xmlNode.Attributes.GetNamedItem("src"); if (getSRC != null) { string relativePath = xmlNode.Attributes.GetNamedItem("src").Value; if (!relativePath.StartsWith("http://")) { string parentPath = Directory.GetParent(filePath).FullName; string imgSourceFullpath = Path.Combine(parentPath, relativePath); string datafilePath = presentation.DataProviderManager.DataFileDirectoryFullPath; string imgDestFullpath = Path.Combine(datafilePath, Path.GetFileName(imgSourceFullpath)); if (!File.Exists(imgDestFullpath)) { //File.Delete(imgDestFullpath); File.Copy(imgSourceFullpath, imgDestFullpath); } updatedSRC = presentation.RootUri.MakeRelativeUri(new Uri(imgDestFullpath, UriKind.Absolute)) .ToString(); //string dirPath = Path.GetDirectoryName(presentation.RootUri.LocalPath); //updatedSRC = presentation.DataProviderManager.DataFileDirectory + Path.DirectorySeparatorChar + Path.GetFileName(imgDestFullpath); ChannelsProperty chProp = presentation.PropertyFactory.CreateChannelsProperty(); treeNode.AddProperty(chProp); ExternalImageMedia externalImage = presentation.MediaFactory.CreateExternalImageMedia(); externalImage.Src = updatedSRC; chProp.SetMedia(m_ImageChannel, externalImage); } } } XmlAttributeCollection attributeCol = xmlNode.Attributes; if (attributeCol != null) { for (int i = 0; i < attributeCol.Count; i++) { XmlNode attr = attributeCol.Item(i); if (attr.LocalName != "smilref" && attr.Name != "xmlns:xsi" && attr.Name != "xml:space") { if (updatedSRC != null && attr.LocalName == "src") { xmlProp.SetAttribute(attr.LocalName, "", updatedSRC); } else { if (attr.LocalName == "xmlns") { if (attr.Value != presentation.PropertyFactory.DefaultXmlNamespaceUri) { xmlProp.SetAttribute(attr.LocalName, "", attr.Value); } } else if (string.IsNullOrEmpty(attr.NamespaceURI) || attr.NamespaceURI == presentation.PropertyFactory.DefaultXmlNamespaceUri) { xmlProp.SetAttribute(attr.LocalName, "", attr.Value); } else { xmlProp.SetAttribute(attr.Name, attr.NamespaceURI, attr.Value); } } } } } foreach (XmlNode childXmlNode in xmlNode.ChildNodes) { parseContentDocument(childXmlNode, treeNode, filePath); } break; } case XmlNodeType.Text: { Presentation presentation = m_Project.Presentations.Get(0); string text = trimXmlText(xmlNode.Value); TextMedia textMedia = presentation.MediaFactory.CreateTextMedia(); textMedia.Text = text; ChannelsProperty cProp = presentation.PropertyFactory.CreateChannelsProperty(); cProp.SetMedia(m_textChannel, textMedia); int counter = 0; foreach (XmlNode childXmlNode in xmlNode.ParentNode.ChildNodes) { XmlNodeType childXmlType = childXmlNode.NodeType; if (childXmlType == XmlNodeType.Text || childXmlType == XmlNodeType.Element) { counter++; } } if (counter == 1) { parentTreeNode.AddProperty(cProp); } else { TreeNode txtWrapperNode = presentation.TreeNodeFactory.Create(); txtWrapperNode.AddProperty(cProp); parentTreeNode.AppendChild(txtWrapperNode); } break; } default: { return; } } }
private void parseSmil(string fullSmilPath) { if (RequestCancellation) { return; } XmlDocument smilXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullSmilPath, false, false); if (RequestCancellation) { return; } //we skip SMIL metadata parsing (we get publication metadata only from OPF and DTBOOK/XHTMLs) //parseMetadata(smilXmlDoc); //XmlNodeList allTextNodes = smilXmlDoc.GetElementsByTagName("text"); //if (allTextNodes.Count == 0) //{ // return; //} //reportProgress(-1, "Parsing SMIL: [" + Path.GetFileName(fullSmilPath) + "]"); foreach (XmlNode textNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(smilXmlDoc, true, "text", null, false)) { XmlAttributeCollection textNodeAttrs = textNode.Attributes; if (textNodeAttrs == null || textNodeAttrs.Count == 0) { continue; } XmlNode textNodeAttrSrc = textNodeAttrs.GetNamedItem("src"); if (textNodeAttrSrc == null || String.IsNullOrEmpty(textNodeAttrSrc.Value)) { continue; } string src = FileDataProvider.UriDecode(textNodeAttrSrc.Value); int index = src.LastIndexOf('#'); if (index == src.Length - 1) { return; } string srcFragmentId = src.Substring(index + 1); TreeNode textTreeNode = m_Project.Presentations.Get(0).RootNode.GetFirstDescendantOrSelfWithXmlID(srcFragmentId); if (textTreeNode == null) { continue; } ManagedAudioMedia textTreeNodeAudio = textTreeNode.GetManagedAudioMedia(); if (textTreeNodeAudio != null) { //Ignore. continue; } XmlNode parent = textNode.ParentNode; if (parent != null && parent.LocalName == "a") { parent = parent.ParentNode; } if (parent == null) { continue; } if (parent.LocalName != "par") { //System.Diagnostics.Debug.Fail("Text node in SMIL has no parallel time container as parent ! {0}", parent.Name); continue; } XmlNodeList textPeers = parent.ChildNodes; foreach (XmlNode textPeerNode in textPeers) { if (RequestCancellation) { return; } if (textPeerNode.NodeType != XmlNodeType.Element) { continue; } if (textPeerNode.LocalName == "audio") { addAudio(textTreeNode, textPeerNode, false, fullSmilPath); break; } else if (textPeerNode.LocalName == "a") { XmlNodeList aChildren = textPeerNode.ChildNodes; foreach (XmlNode aChild in aChildren) { if (aChild.LocalName == "audio") { addAudio(textTreeNode, aChild, false, fullSmilPath); break; } } } else if (textPeerNode.LocalName == "seq") { #if DEBUG Debugger.Break(); #endif //DEBUG XmlNodeList seqChildren = textPeerNode.ChildNodes; foreach (XmlNode seqChild in seqChildren) { if (seqChild.LocalName == "audio") { addAudio(textTreeNode, seqChild, true, fullSmilPath); } } #if ENABLE_SEQ_MEDIA SequenceMedia seqManAudioMedia = textTreeNode.GetManagedAudioSequenceMedia(); if (seqManAudioMedia == null) { Debug.Fail("This should never happen !"); break; } ManagedAudioMedia managedAudioMedia = textTreeNode.Presentation.MediaFactory.CreateManagedAudioMedia(); AudioMediaData mediaData = textTreeNode.Presentation.MediaDataFactory.CreateAudioMediaData(); managedAudioMedia.AudioMediaData = mediaData; foreach (Media seqChild in seqManAudioMedia.ChildMedias.ContentsAs_Enumerable) { ManagedAudioMedia seqManMedia = (ManagedAudioMedia)seqChild; // WARNING: WavAudioMediaData implementation differs from AudioMediaData: // the latter is naive and performs a stream binary copy, the latter is optimized and re-uses existing WavClips. // WARNING 2: The audio data from the given parameter gets emptied ! mediaData.MergeWith(seqManMedia.AudioMediaData); //Stream stream = seqManMedia.AudioMediaData.OpenPcmInputStream(); //try //{ // mediaData.AppendPcmData(stream, null); //} //finally //{ // stream.Close(); //} //seqManMedia.AudioMediaData.Delete(); // doesn't actually removes the FileDataProviders (need to call Presentation.Cleanup()) ////textTreeNode.Presentation.DataProviderManager.RemoveDataProvider(); } ChannelsProperty chProp = textTreeNode.GetChannelsProperty(); chProp.SetMedia(m_audioChannel, null); chProp.SetMedia(m_audioChannel, managedAudioMedia); #endif //ENABLE_SEQ_MEDIA break; } } } }
protected void addAudio(TreeNode treeNode, XmlNode xmlNode, bool isSequence, string fullSmilPath) { if (RequestCancellation) { return; } string dirPath = Path.GetDirectoryName(fullSmilPath); XmlAttributeCollection audioAttrs = xmlNode.Attributes; if (audioAttrs == null || audioAttrs.Count == 0) { return; } XmlNode audioAttrSrc = audioAttrs.GetNamedItem("src"); if (audioAttrSrc == null || String.IsNullOrEmpty(audioAttrSrc.Value)) { return; } string src = FileDataProvider.UriDecode(audioAttrSrc.Value); XmlNode audioAttrClipBegin = audioAttrs.GetNamedItem("clipBegin"); XmlNode audioAttrClipEnd = audioAttrs.GetNamedItem("clipEnd"); Presentation presentation = treeNode.Presentation; // m_Project.Presentations.Get(0); ManagedAudioMedia media = null; string fullPath = Path.Combine(dirPath, src); fullPath = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\'); addOPF_GlobalAssetPath(fullPath); string ext = Path.GetExtension(src); if (ext.Equals(DataProviderFactory.AUDIO_WAV_EXTENSION, StringComparison.OrdinalIgnoreCase)) { FileDataProvider dataProv = null; if (!File.Exists(fullPath)) { Debug.Fail("File not found: " + fullPath); media = null; } else { //bool deleteSrcAfterCompletion = false; string fullWavPath = fullPath; FileDataProvider obj; m_OriginalAudioFile_FileDataProviderMap.TryGetValue(fullWavPath, out obj); if (obj != null) //m_OriginalAudioFile_FileDataProviderMap.ContainsKey(fullWavPath)) { if (m_AudioConversionSession.FirstDiscoveredPCMFormat == null) { DebugFix.Assert(obj.Presentation != presentation); Object appData = obj.AppData; DebugFix.Assert(appData != null); if (appData != null && appData is WavClip.PcmFormatAndTime) { m_AudioConversionSession.FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); m_AudioConversionSession.FirstDiscoveredPCMFormat.CopyFrom(((WavClip.PcmFormatAndTime)appData).mFormat); } } if (obj.Presentation != presentation) { dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.CopyingAudio, Path.GetFileName(obj.DataFileFullPath))); dataProv.InitByCopyingExistingFile(obj.DataFileFullPath); //m_AudioConversionSession.RelocateDestinationFilePath(newfullWavPath, dataProv.DataFileFullPath); m_OriginalAudioFile_FileDataProviderMap.Remove(fullWavPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullWavPath, dataProv); Object appData = obj.AppData; DebugFix.Assert(appData != null); if (appData != null && appData is WavClip.PcmFormatAndTime) { dataProv.AppData = new WavClip.PcmFormatAndTime(((WavClip.PcmFormatAndTime)appData).mFormat, ((WavClip.PcmFormatAndTime)appData).mTime); } } else { dataProv = obj; // m_OriginalAudioFile_FileDataProviderMap[fullWavPath]; } } else // create FileDataProvider { Stream wavStream = null; try { wavStream = File.Open(fullWavPath, FileMode.Open, FileAccess.Read, FileShare.Read); uint dataLength; AudioLibPCMFormat pcmInfo = null; pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength); if (m_AudioConversionSession.FirstDiscoveredPCMFormat == null) { //m_AudioConversionSession.FirstDiscoveredPCMFormat = new PCMFormatInfo(pcmInfo); m_AudioConversionSession.FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); m_AudioConversionSession.FirstDiscoveredPCMFormat.CopyFrom(pcmInfo); } if (RequestCancellation) { return; } //if (m_firstTimePCMFormat) //{ // presentation.MediaDataManager.DefaultPCMFormat = new PCMFormatInfo(pcmInfo); // m_firstTimePCMFormat = false; //} if (!presentation.MediaDataManager.DefaultPCMFormat.Data.IsCompatibleWith(pcmInfo)) { wavStream.Close(); wavStream = null; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ConvertingAudio, Path.GetFileName(fullWavPath))); string newfullWavPath = m_AudioConversionSession.ConvertAudioFileFormat(fullWavPath); if (RequestCancellation) { return; } dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullWavPath) + " = " + dataProv.DataFileRelativePath); dataProv.InitByMovingExistingFile(newfullWavPath); m_AudioConversionSession.RelocateDestinationFilePath(newfullWavPath, dataProv.DataFileFullPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullWavPath, dataProv); if (RequestCancellation) { return; } } else // use original wav file by copying it to data directory { dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullWavPath) + " = " + dataProv.DataFileRelativePath); reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.CopyingAudio, Path.GetFileName(fullWavPath))); dataProv.InitByCopyingExistingFile(fullWavPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullWavPath, dataProv); if (RequestCancellation) { return; } } } finally { if (wavStream != null) { wavStream.Close(); } } } } // FileDataProvider key check ends if (RequestCancellation) { return; } media = addAudioWav(dataProv, audioAttrClipBegin, audioAttrClipEnd, treeNode); //media = addAudioWav ( fullWavPath, deleteSrcAfterCompletion, audioAttrClipBegin, audioAttrClipEnd ); } else if (ext.Equals(DataProviderFactory.AUDIO_MP3_EXTENSION, StringComparison.OrdinalIgnoreCase) || ext.Equals(DataProviderFactory.AUDIO_MP4_EXTENSION, StringComparison.OrdinalIgnoreCase) || ext.Equals(DataProviderFactory.AUDIO_MP4_EXTENSION_, StringComparison.OrdinalIgnoreCase)) { if (!File.Exists(fullPath)) { Debug.Fail("File not found: {0}", fullPath); return; } if (RequestCancellation) { return; } reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.DecodingAudio, Path.GetFileName(fullPath))); if (RequestCancellation) { return; } string fullMp34PathOriginal = fullPath; FileDataProvider obj; m_OriginalAudioFile_FileDataProviderMap.TryGetValue(fullMp34PathOriginal, out obj); FileDataProvider dataProv = null; if (obj != null) //m_OriginalAudioFile_FileDataProviderMap.ContainsKey(fullMp3PathOriginal)) { if (m_AudioConversionSession.FirstDiscoveredPCMFormat == null) { DebugFix.Assert(obj.Presentation != presentation); Object appData = obj.AppData; DebugFix.Assert(appData != null); if (appData != null && appData is WavClip.PcmFormatAndTime) { m_AudioConversionSession.FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); m_AudioConversionSession.FirstDiscoveredPCMFormat.CopyFrom(((WavClip.PcmFormatAndTime)appData).mFormat); } } if (obj.Presentation != presentation) { dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.CopyingAudio, Path.GetFileName(obj.DataFileFullPath))); dataProv.InitByCopyingExistingFile(obj.DataFileFullPath); //m_AudioConversionSession.RelocateDestinationFilePath(newfullWavPath, dataProv.DataFileFullPath); m_OriginalAudioFile_FileDataProviderMap.Remove(fullMp34PathOriginal); m_OriginalAudioFile_FileDataProviderMap.Add(fullMp34PathOriginal, dataProv); Object appData = obj.AppData; DebugFix.Assert(appData != null); if (appData != null && appData is WavClip.PcmFormatAndTime) { dataProv.AppData = new WavClip.PcmFormatAndTime(((WavClip.PcmFormatAndTime)appData).mFormat, ((WavClip.PcmFormatAndTime)appData).mTime); } } else { dataProv = obj; // m_OriginalAudioFile_FileDataProviderMap[fullMp3PathOriginal]; } } else { string newfullWavPath = m_AudioConversionSession.ConvertAudioFileFormat(fullMp34PathOriginal); dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullMp34PathOriginal) + " = " + dataProv.DataFileRelativePath); dataProv.InitByMovingExistingFile(newfullWavPath); m_AudioConversionSession.RelocateDestinationFilePath(newfullWavPath, dataProv.DataFileFullPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullMp34PathOriginal, dataProv); if (RequestCancellation) { return; } } if (dataProv != null) { //if (m_firstTimePCMFormat) //{ // Stream wavStream = null; // try // { // wavStream = File.Open(newfullWavPath, FileMode.Open, FileAccess.Read, FileShare.Read); // uint dataLength; // AudioLibPCMFormat pcmInfo = null; // pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength); // presentation.MediaDataManager.DefaultPCMFormat = new PCMFormatInfo(pcmInfo); // } // finally // { // if (wavStream != null) wavStream.Close(); // m_firstTimePCMFormat = false; // } //} if (RequestCancellation) { return; } //media = addAudioWav(newfullWavPath, true, audioAttrClipBegin, audioAttrClipEnd); media = addAudioWav(dataProv, audioAttrClipBegin, audioAttrClipEnd, treeNode); if (RequestCancellation) { return; } if (media == null) { #if DEBUG Debugger.Break(); #endif } } //} } if (RequestCancellation) { return; } if (media == null) { if (!TreenodesWithoutManagedAudioMediaData.Contains(treeNode)) { TreenodesWithoutManagedAudioMediaData.Add(treeNode); } Debug.Fail("Creating ExternalAudioMedia ??"); Time timeClipBegin = null; ExternalAudioMedia exmedia = presentation.MediaFactory.CreateExternalAudioMedia(); exmedia.Src = src; if (audioAttrClipBegin != null && !string.IsNullOrEmpty(audioAttrClipBegin.Value)) { timeClipBegin = new Time(); try { timeClipBegin = new Time(audioAttrClipBegin.Value); } catch (Exception ex) { string str = "CLIP BEGIN TIME PARSE FAIL: " + audioAttrClipBegin.Value; Console.WriteLine(str); Debug.Fail(str); } exmedia.ClipBegin = timeClipBegin; } if (audioAttrClipEnd != null && !string.IsNullOrEmpty(audioAttrClipEnd.Value)) { Time timeClipEnd = null; try { timeClipEnd = new Time(audioAttrClipEnd.Value); } catch (Exception ex) { string str = "CLIP END TIME PARSE FAIL: " + audioAttrClipEnd.Value; Console.WriteLine(str); Debug.Fail(str); } if (timeClipEnd != null) { try { exmedia.ClipEnd = timeClipEnd; } catch (Exception ex) { string str = "CLIP TIME ERROR (end < begin): " + timeClipBegin + " (" + (audioAttrClipBegin != null ? audioAttrClipBegin.Value : "N/A") + ") / " + timeClipEnd + " (" + audioAttrClipEnd.Value + ")"; Console.WriteLine(str); //Debug.Fail(str); } } } } if (RequestCancellation) { return; } if (media != null) { ChannelsProperty chProp = treeNode.GetChannelsProperty(); if (chProp == null) { chProp = presentation.PropertyFactory.CreateChannelsProperty(); treeNode.AddProperty(chProp); } if (isSequence) { #if ENABLE_SEQ_MEDIA SequenceMedia mediaSeq = chProp.GetMedia(m_audioChannel) as SequenceMedia; if (mediaSeq == null) { mediaSeq = presentation.MediaFactory.CreateSequenceMedia(); mediaSeq.AllowMultipleTypes = false; chProp.SetMedia(m_audioChannel, mediaSeq); } mediaSeq.ChildMedias.Insert(mediaSeq.ChildMedias.Count, media); #else ManagedAudioMedia existingMedia = chProp.GetMedia(presentation.ChannelsManager.GetOrCreateAudioChannel()) as ManagedAudioMedia; if (existingMedia == null) { chProp.SetMedia(presentation.ChannelsManager.GetOrCreateAudioChannel(), media); } else { // WARNING: WavAudioMediaData implementation differs from AudioMediaData: // the latter is naive and performs a stream binary copy, the latter is optimized and re-uses existing WavClips. // WARNING 2: The audio data from the given parameter gets emptied ! existingMedia.AudioMediaData.MergeWith(media.AudioMediaData); //Stream stream = seqManMedia.AudioMediaData.OpenPcmInputStream(); //try //{ // mediaData.AppendPcmData(stream, null); //} //finally //{ // stream.Close(); //} } #endif //ENABLE_SEQ_MEDIA } else { //#if DEBUG // ((WavAudioMediaData) media.AudioMediaData).checkWavClips(); //#endif //DEBUG chProp.SetMedia(presentation.ChannelsManager.GetOrCreateAudioChannel(), media); } } else { Debug.Fail("Media could not be created !"); } }
private void parseDTBookXmlDocAndPopulateDataModel(XmlNode xmlNode, core.TreeNode parentTreeNode) { XmlNodeType xmlType = xmlNode.NodeType; switch (xmlType) { case XmlNodeType.Attribute: { System.Diagnostics.Debug.Fail("Calling this method with an XmlAttribute should never happen !!"); break; } case XmlNodeType.Document: { parseDTBookXmlDocAndPopulateDataModel(((XmlDocument)xmlNode).DocumentElement, parentTreeNode); break; } case XmlNodeType.Element: { Presentation presentation = m_Project.GetPresentation(0); core.TreeNode treeNode = presentation.TreeNodeFactory.Create(); if (parentTreeNode == null) { presentation.RootNode = treeNode; parentTreeNode = presentation.RootNode; } else { parentTreeNode.AppendChild(treeNode); } XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty(); treeNode.AddProperty(xmlProp); xmlProp.LocalName = xmlNode.Name; if (xmlNode.ParentNode != null && xmlNode.ParentNode.NodeType == XmlNodeType.Document) { presentation.PropertyFactory.DefaultXmlNamespaceUri = xmlNode.NamespaceURI; } if (xmlNode.NamespaceURI != presentation.PropertyFactory.DefaultXmlNamespaceUri) { xmlProp.NamespaceUri = xmlNode.NamespaceURI; } XmlAttributeCollection attributeCol = xmlNode.Attributes; if (attributeCol != null) { for (int i = 0; i < attributeCol.Count; i++) { XmlNode attr = attributeCol.Item(i); if (attr.Name != "smilref") { xmlProp.SetAttribute(attr.Name, "", attr.Value); } } if (xmlNode.Name == "meta") { XmlNode attrName = attributeCol.GetNamedItem("name"); XmlNode attrContent = attributeCol.GetNamedItem("content"); if (attrName != null && attrContent != null && !String.IsNullOrEmpty(attrName.Value) && !String.IsNullOrEmpty(attrContent.Value)) { Metadata md = presentation.MetadataFactory.CreateMetadata(); md.Name = attrName.Value; md.Content = attrContent.Value; presentation.AddMetadata(md); } } } foreach (XmlNode childXmlNode in xmlNode.ChildNodes) { parseDTBookXmlDocAndPopulateDataModel(childXmlNode, treeNode); } break; } case XmlNodeType.Text: { Presentation presentation = m_Project.GetPresentation(0); string text = xmlNode.Value; TextMedia textMedia = presentation.MediaFactory.CreateTextMedia(); textMedia.Text = text; ChannelsProperty cProp = presentation.PropertyFactory.CreateChannelsProperty(); cProp.SetMedia(m_textChannel, textMedia); int counter = 0; foreach (XmlNode childXmlNode in xmlNode.ParentNode.ChildNodes) { XmlNodeType childXmlType = childXmlNode.NodeType; if (childXmlType == XmlNodeType.Text || childXmlType == XmlNodeType.Element) { counter++; } } if (counter == 1) { parentTreeNode.AddProperty(cProp); } else { core.TreeNode txtWrapperNode = presentation.TreeNodeFactory.Create(); txtWrapperNode.AddProperty(cProp); parentTreeNode.AppendChild(txtWrapperNode); } break; } default: { return; } } }
private void parseHeadLinks(string rootFilePath, Project project, XmlDocument contentDoc) { XmlNode headXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(contentDoc.DocumentElement, true, "head", null); if (headXmlNode == null) { return; } Presentation presentation = project.Presentations.Get(0); List <string> externalFileRelativePaths = new List <string>(); foreach (ExternalFiles.ExternalFileData extData in presentation.ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { if (!string.IsNullOrEmpty(extData.OriginalRelativePath)) { string fullPath = Path.Combine(Path.GetDirectoryName(rootFilePath), extData.OriginalRelativePath); string relPath = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\'); if (!externalFileRelativePaths.Contains(relPath)) { externalFileRelativePaths.Add(relPath); } } } List <XmlNode> externalFilesLinks = new List <XmlNode>(); externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "link", headXmlNode.NamespaceURI, false)); externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "script", headXmlNode.NamespaceURI, false)); externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "style", headXmlNode.NamespaceURI, false)); externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "title", headXmlNode.NamespaceURI, false)); foreach (XmlNode linkNode in externalFilesLinks) { TreeNode treeNode = presentation.TreeNodeFactory.Create(); presentation.HeadNode.AppendChild(treeNode); XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty(); treeNode.AddProperty(xmlProp); xmlProp.SetQName(linkNode.LocalName, headXmlNode.NamespaceURI == linkNode.NamespaceURI ? "" : linkNode.NamespaceURI); //Console.WriteLine("XmlProperty: " + xmlProp.LocalName); foreach (System.Xml.XmlAttribute xAttr in linkNode.Attributes) { if ( //xAttr.LocalName.Equals(XmlReaderWriterHelper.NS_PREFIX_XMLNS, StringComparison.OrdinalIgnoreCase) //|| xAttr.LocalName.Equals("xsi", StringComparison.OrdinalIgnoreCase) xAttr.NamespaceURI.Equals(XmlReaderWriterHelper.NS_URL_XMLNS, StringComparison.OrdinalIgnoreCase) || xAttr.LocalName.Equals("space", StringComparison.OrdinalIgnoreCase) && xAttr.NamespaceURI.Equals(XmlReaderWriterHelper.NS_URL_XML, StringComparison.OrdinalIgnoreCase) ) { continue; } xmlProp.SetAttribute(xAttr.Name, linkNode.NamespaceURI == xAttr.NamespaceURI ? "" : xAttr.NamespaceURI, xAttr.Value); if ((xAttr.Name.Equals("href", StringComparison.OrdinalIgnoreCase) || xAttr.Name.Equals("src", StringComparison.OrdinalIgnoreCase)) && !string.IsNullOrEmpty(xAttr.Value) && !FileDataProvider.isHTTPFile(xAttr.Value)) { string urlDecoded = FileDataProvider.UriDecode(xAttr.Value); string fullPath = Path.Combine(Path.GetDirectoryName(rootFilePath), urlDecoded); string pathFromAttr = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\'); if (!externalFileRelativePaths.Contains(pathFromAttr)) { if (File.Exists(pathFromAttr)) { ExternalFiles.ExternalFileData efd = presentation.ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>(); try { efd.InitializeWithData(pathFromAttr, urlDecoded, true, null); externalFileRelativePaths.Add(pathFromAttr); addOPF_GlobalAssetPath(pathFromAttr); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); #if DEBUG Debugger.Break(); #endif } } #if DEBUG else { Debugger.Break(); } #endif } } } string innerText = linkNode.InnerText; // includes CDATA sections! (merges "//" javascript comment markers too) if (!string.IsNullOrEmpty(innerText)) { urakawa.media.TextMedia textMedia = presentation.MediaFactory.CreateTextMedia(); textMedia.Text = innerText; ChannelsProperty cProp = presentation.PropertyFactory.CreateChannelsProperty(); cProp.SetMedia(presentation.ChannelsManager.GetOrCreateTextChannel(), textMedia); treeNode.AddProperty(cProp); //Console.WriteLine("Link inner text: " + textMedia.Text); } } }
private void parseSmil(string fullSmilPath) { Presentation presentation = m_Project.GetPresentation(0); string dirPath = Path.GetDirectoryName(m_Book_FilePath); XmlDocument smilXmlDoc = readXmlDocument(fullSmilPath); XmlNodeList listOfAudioNodes = smilXmlDoc.GetElementsByTagName("audio"); if (listOfAudioNodes != null) { foreach (XmlNode audioNode in listOfAudioNodes) { XmlAttributeCollection attributeCol = audioNode.Attributes; if (attributeCol != null) { XmlNode attrAudioSrc = attributeCol.GetNamedItem("src"); if (attrAudioSrc != null && !String.IsNullOrEmpty(attrAudioSrc.Value)) { XmlNode parent = audioNode.ParentNode; if (parent != null && parent.Name == "a") { parent = parent.ParentNode; } if (parent != null) { XmlNodeList listOfAudioPeers = parent.ChildNodes; foreach (XmlNode peerNode in listOfAudioPeers) { if (peerNode.NodeType == XmlNodeType.Element && peerNode.Name == "text") { XmlAttributeCollection peerAttrs = peerNode.Attributes; if (peerAttrs != null) { XmlNode attrTextSrc = peerAttrs.GetNamedItem("src"); if (attrTextSrc != null && !String.IsNullOrEmpty(attrTextSrc.Value)) { int index = attrTextSrc.Value.LastIndexOf('#'); if (index < (attrTextSrc.Value.Length - 1)) { string dtbookFragmentId = attrTextSrc.Value.Substring(index + 1); core.TreeNode tNode = getTreeNodeWithXmlElementId(dtbookFragmentId); if (tNode != null) { AbstractAudioMedia existingAudioMedia = tNode.GetAudioMedia(); if (existingAudioMedia != null) { //Ignore. //System.Diagnostics.Debug.Fail("TreeNode already has media ??"); } XmlNode attrClipBegin = attributeCol.GetNamedItem("clipBegin"); XmlNode attrClipEnd = attributeCol.GetNamedItem("clipEnd"); Media media = null; if (attrAudioSrc.Value.EndsWith("wav")) { string fullWavPath = Path.Combine(dirPath, attrAudioSrc.Value); PCMDataInfo pcmInfo = null; Stream wavStream = null; try { wavStream = File.Open(fullWavPath, FileMode.Open, FileAccess.Read, FileShare.Read); pcmInfo = PCMDataInfo.ParseRiffWaveHeader(wavStream); presentation.MediaDataManager.DefaultPCMFormat = pcmInfo.Copy(); TimeDelta duration = new TimeDelta(pcmInfo.Duration); Time clipB = Time.Zero; Time clipE = Time.MaxValue; if (attrClipBegin != null && !string.IsNullOrEmpty(attrClipBegin.Value)) { clipB = new Time(TimeSpan.Parse(attrClipBegin.Value)); } if (attrClipEnd != null && !string.IsNullOrEmpty(attrClipEnd.Value)) { clipE = new Time(TimeSpan.Parse(attrClipEnd.Value)); } if (!clipB.IsEqualTo(Time.Zero) || !clipE.IsEqualTo(Time.MaxValue)) { duration = clipE.GetTimeDelta(clipB); } long byteOffset = 0; if (!clipB.IsEqualTo(Time.Zero)) { byteOffset = pcmInfo.GetByteForTime(clipB); } if (byteOffset > 0) { wavStream.Seek(byteOffset, SeekOrigin.Current); } presentation.MediaDataFactory.DefaultAudioMediaDataType = typeof(WavAudioMediaData); WavAudioMediaData mediaData = (WavAudioMediaData) presentation.MediaDataFactory.CreateAudioMediaData(); mediaData.InsertAudioData(wavStream, Time.Zero, duration); media = presentation.MediaFactory.CreateManagedAudioMedia(); ((ManagedAudioMedia)media).AudioMediaData = mediaData; } finally { if (wavStream != null) { wavStream.Close(); } } } else { media = presentation.MediaFactory.CreateExternalAudioMedia(); ((ExternalAudioMedia)media).Src = attrAudioSrc.Value; if (attrClipBegin != null && !string.IsNullOrEmpty(attrClipBegin.Value)) { ((ExternalAudioMedia)media).ClipBegin = new Time(TimeSpan.Parse(attrClipBegin.Value)); } if (attrClipEnd != null && !string.IsNullOrEmpty(attrClipEnd.Value)) { ((ExternalAudioMedia)media).ClipEnd = new Time(TimeSpan.Parse(attrClipEnd.Value)); } } ChannelsProperty chProp = tNode.GetProperty <ChannelsProperty>(); if (chProp == null) { chProp = presentation.PropertyFactory.CreateChannelsProperty(); tNode.AddProperty(chProp); } chProp.SetMedia(m_audioChannel, media); break; // scan peers to audio node } else { System.Diagnostics.Debug.Fail("XmlProperty with ID not found ??"); } } } } } } } } } } } }
public override bool PreVisit(TreeNode node) { if (m_RootNode == null) { m_RootNode = node; } if (m_currentAudioLevelNode == null) { m_currentAudioLevelNode = m_RootNode; } if (TreeNodeMustBeSkipped(node)) { return(false); } if (RequestCancellation) { checkTransientWavFileAndClose(node); return(false); } if (TreeNodeTriggersNewAudioFile(node)) { m_currentAudioLevelNode = node; checkTransientWavFileAndClose(node); // REMOVED, because doesn't support nested TreeNode matches ! return false; // skips children, see postVisit } if (node.GetAlternateContentProperty() != null) { m_AlternateContentPropertiesList.Add(node.GetAlternateContentProperty()); } if (!node.HasChannelsProperty) { return(true); } if (!node.Presentation.MediaDataManager.EnforceSinglePCMFormat) { Debug.Fail("! EnforceSinglePCMFormat ???"); throw new Exception("! EnforceSinglePCMFormat ???"); } #if ENABLE_SEQ_MEDIA Media media = node.GetManagedAudioMediaOrSequenceMedia(); if (media == null) { return(true); } #endif ManagedAudioMedia manAudioMedia = node.GetManagedAudioMedia(); if (manAudioMedia == null) { return(true); } //if (!manAudioMedia.HasActualAudioMediaData) //{ // return true; //} if (m_TransientWavFileStream == null) { mCurrentAudioFileNumber++; Uri waveFileUri = GetCurrentAudioFileUri(); m_TransientWavFileStream = new FileStream(waveFileUri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.None); m_TransientWavFileStreamRiffOffset = node.Presentation.MediaDataManager.DefaultPCMFormat.Data.RiffHeaderWrite(m_TransientWavFileStream, 0); } long bytesBegin = m_TransientWavFileStream.Position - (long)m_TransientWavFileStreamRiffOffset; #if ENABLE_SEQ_MEDIA SequenceMedia seqAudioMedia = node.GetManagedAudioSequenceMedia(); #endif //ENABLE_SEQ_MEDIA Stream audioPcmStream = null; if (manAudioMedia != null) { audioPcmStream = manAudioMedia.AudioMediaData.OpenPcmInputStream(); } #if ENABLE_SEQ_MEDIA else if (seqAudioMedia != null) { Debug.Fail("SequenceMedia is normally removed at import time...have you tried re-importing the DAISY book ?"); audioPcmStream = seqAudioMedia.OpenPcmInputStreamOfManagedAudioMedia(); } #endif //ENABLE_SEQ_MEDIA else { Debug.Fail("This should never happen !!"); return(false); } if (RequestCancellation) { checkTransientWavFileAndClose(node); return(false); } try { const uint BUFFER_SIZE = 1024 * 1024 * 3; // 3 MB MAX BUFFER uint streamCount = StreamUtils.Copy(audioPcmStream, 0, m_TransientWavFileStream, BUFFER_SIZE); //System.Windows.Forms.MessageBox.Show ( audioPcmStream.Length.ToString () + " : " + m_TransientWavFileStream.Length.ToString () + " : " + streamCount.ToString () ); } catch { m_TransientWavFileStream.Close(); m_TransientWavFileStream = null; m_TransientWavFileStreamRiffOffset = 0; #if DEBUG Debugger.Break(); #endif } finally { audioPcmStream.Close(); } if (m_TransientWavFileStream == null) { Debug.Fail("Stream copy error !!"); return(false); } long bytesEnd = m_TransientWavFileStream.Position - (long)m_TransientWavFileStreamRiffOffset; string src = node.Presentation.RootUri.MakeRelativeUri(GetCurrentAudioFileUri()).ToString(); if (manAudioMedia != null #if ENABLE_SEQ_MEDIA || seqAudioMedia != null #endif //ENABLE_SEQ_MEDIA ) { if (m_TotalTimeInLocalUnits == 0) { Time dur = node.Root.GetDurationOfManagedAudioMediaFlattened(); if (dur != null) { m_TotalTimeInLocalUnits = dur.AsLocalUnits; } } m_TimeElapsedInLocalUnits += manAudioMedia != null ? manAudioMedia.Duration.AsLocalUnits : #if ENABLE_SEQ_MEDIA seqAudioMedia.GetDurationOfManagedAudioMedia().AsLocalUnits #else -1 #endif //ENABLE_SEQ_MEDIA ; int percent = Convert.ToInt32((m_TimeElapsedInLocalUnits * 100) / m_TotalTimeInLocalUnits); if (EncodePublishedAudioFiles) { reportProgress_Throttle(percent, String.Format(UrakawaSDK_daisy_Lang.CreateMP3File, Path.GetFileName(src).Replace(DataProviderFactory.AUDIO_WAV_EXTENSION, DataProviderFactory.AUDIO_MP3_EXTENSION), GetSizeInfo(node))); } else { reportProgress_Throttle(percent, String.Format(UrakawaSDK_daisy_Lang.CreatingAudioFile, Path.GetFileName(src), GetSizeInfo(node))); } //Console.WriteLine("progress percent " + m_ProgressPercentage); } ExternalAudioMedia extAudioMedia = node.Presentation.MediaFactory.Create <ExternalAudioMedia>(); extAudioMedia.Tag = m_currentAudioLevelNode; ushort nChannels = (ushort)(EncodePublishedAudioFilesStereo ? 2 : 1); if ((EncodePublishedAudioFiles || (ushort)EncodePublishedAudioFilesSampleRate != node.Presentation.MediaDataManager.DefaultPCMFormat.Data.SampleRate || nChannels != node.Presentation.MediaDataManager.DefaultPCMFormat.Data.NumberOfChannels ) && !m_ExternalAudioMediaList.Contains(extAudioMedia)) { m_ExternalAudioMediaList.Add(extAudioMedia); } extAudioMedia.Language = node.Presentation.Language; extAudioMedia.Src = src; long timeBegin = node.Presentation.MediaDataManager.DefaultPCMFormat.Data.ConvertBytesToTime(bytesBegin); long timeEnd = node.Presentation.MediaDataManager.DefaultPCMFormat.Data.ConvertBytesToTime(bytesEnd); extAudioMedia.ClipBegin = new Time(timeBegin); extAudioMedia.ClipEnd = new Time(timeEnd); ChannelsProperty chProp = node.GetChannelsProperty(); if (chProp.GetMedia(DestinationChannel) != null) { chProp.SetMedia(DestinationChannel, null); Debug.Fail("This should never happen !!"); } chProp.SetMedia(DestinationChannel, extAudioMedia); return(false); }
public override bool PreVisit(TreeNode node) { if (m_RootNode == null) { m_RootNode = node; } if (TreeNodeMustBeSkipped(node)) { return(false); } if (TreeNodeTriggersNewAudioFile(node)) { createNextAudioFile(node); } if (node.HasProperties(typeof(ChannelsProperty))) { ChannelsProperty chProp = node.GetChannelsProperty(); ManagedAudioMedia mam = chProp.GetMedia(SourceChannel) as ManagedAudioMedia; if (mam != null) { AudioMediaData amd = mam.AudioMediaData; if (mCurrentAudioFileStream == null) { createNextAudioFile(node); } else if (mCurrentAudioFilePCMFormat != null && !mCurrentAudioFilePCMFormat.Data.IsCompatibleWith(amd.PCMFormat.Data)) { #if DEBUG Debugger.Break(); #endif createNextAudioFile(node); } if (mCurrentAudioFileStream != null && mCurrentAudioFilePCMFormat == null) { writeInitialHeader(amd.PCMFormat); } Time durationFromRiffHeader = amd.AudioDuration; Time clipBegin = new Time(mCurrentAudioFilePCMFormat.Data.ConvertBytesToTime(mCurrentAudioFileStream.Position - mCurrentAudioFileStreamRiffWaveHeaderLength)); Time clipEnd = new Time(clipBegin.AsTimeSpanTicks + durationFromRiffHeader.AsTimeSpanTicks, true); //BinaryReader rd = new BinaryReader(stream); Stream stream = amd.OpenPcmInputStream(); try { const uint BUFFER_SIZE = 1024 * 1024 * 3; // 3 MB MAX BUFFER StreamUtils.Copy(stream, 0, mCurrentAudioFileStream, BUFFER_SIZE); } finally { stream.Close(); } ExternalAudioMedia eam = node.Presentation.MediaFactory.Create <ExternalAudioMedia>(); if (eam == null) { throw new exception.FactoryCannotCreateTypeException(String.Format( "The media facotry cannot create a ExternalAudioMedia matching QName {1}:{0}", XukAble.GetXukName(typeof(ExternalAudioMedia), true) ?? typeof(ExternalAudioMedia).Name, node.Presentation.Project.GetXukNamespace())); } eam.Language = mam.Language; eam.Src = node.Presentation.RootUri.MakeRelativeUri(GetCurrentAudioFileUri()).ToString(); eam.ClipBegin = clipBegin; eam.ClipEnd = clipEnd; if (chProp.GetMedia(DestinationChannel) != null) { #if DEBUG Debugger.Break(); #endif chProp.SetMedia(DestinationChannel, null); } chProp.SetMedia(DestinationChannel, eam); } } return(true); }
private void addAudio(TreeNode treeNode, XmlNode xmlNode, bool isSequence, string fullSmilPath) { string dirPath = Path.GetDirectoryName(fullSmilPath); XmlAttributeCollection audioAttrs = xmlNode.Attributes; if (audioAttrs == null || audioAttrs.Count == 0) { return; } XmlNode audioAttrSrc = audioAttrs.GetNamedItem("src"); if (audioAttrSrc == null || String.IsNullOrEmpty(audioAttrSrc.Value)) { return; } XmlNode audioAttrClipBegin = audioAttrs.GetNamedItem("clipBegin"); XmlNode audioAttrClipEnd = audioAttrs.GetNamedItem("clipEnd"); Presentation presentation = m_Project.Presentations.Get(0); Media media = null; if (audioAttrSrc.Value.EndsWith("wav")) { string dirPathBook = Path.GetDirectoryName(m_Book_FilePath); FileDataProvider dataProv = null; string fullWavPathOriginal = Path.Combine(dirPathBook, audioAttrSrc.Value); if (!File.Exists(fullWavPathOriginal)) { System.Diagnostics.Debug.Fail("File not found: {0}", fullWavPathOriginal); media = null; } else { //bool deleteSrcAfterCompletion = false; string fullWavPath = fullWavPathOriginal; uint dataLength; AudioLibPCMFormat pcmInfo = null; if (m_OriginalAudioFile_FileDataProviderMap.ContainsKey(fullWavPath)) { dataProv = m_OriginalAudioFile_FileDataProviderMap[fullWavPath]; } else // create FileDataProvider { 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; //} if (!presentation.MediaDataManager.DefaultPCMFormat.Data.IsCompatibleWith(pcmInfo)) { wavStream.Close(); wavStream = null; string newfullWavPath = m_AudioConversionSession.ConvertAudioFileFormat(fullWavPath); dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullWavPath) + " = " + dataProv.DataFileRelativePath); dataProv.InitByMovingExistingFile(newfullWavPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullWavPath, dataProv); } else // use original wav file by copying it to data directory { dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullWavPath) + " = " + dataProv.DataFileRelativePath); dataProv.InitByCopyingExistingFile(fullWavPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullWavPath, dataProv); } } finally { if (wavStream != null) { wavStream.Close(); } } } } // FileDataProvider key check ends media = addAudioWav(dataProv, audioAttrClipBegin, audioAttrClipEnd); //media = addAudioWav ( fullWavPath, deleteSrcAfterCompletion, audioAttrClipBegin, audioAttrClipEnd ); } else if (audioAttrSrc.Value.EndsWith("mp3")) { string fullMp3PathOriginal = Path.Combine(dirPath, audioAttrSrc.Value); if (!File.Exists(fullMp3PathOriginal)) { System.Diagnostics.Debug.Fail("File not found: {0}", fullMp3PathOriginal); return; } string newfullWavPath = m_AudioConversionSession.ConvertAudioFileFormat(fullMp3PathOriginal); FileDataProvider dataProv = null; if (m_OriginalAudioFile_FileDataProviderMap.ContainsKey(fullMp3PathOriginal)) { dataProv = m_OriginalAudioFile_FileDataProviderMap[fullMp3PathOriginal]; } else { dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullMp3PathOriginal) + " = " + dataProv.DataFileRelativePath); dataProv.InitByMovingExistingFile(newfullWavPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullMp3PathOriginal, dataProv); } if (newfullWavPath != null) { //if (m_firstTimePCMFormat) //{ // Stream wavStream = null; // try // { // wavStream = File.Open(newfullWavPath, FileMode.Open, FileAccess.Read, FileShare.Read); // uint dataLength; // AudioLibPCMFormat pcmInfo = null; // pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength); // presentation.MediaDataManager.DefaultPCMFormat = new PCMFormatInfo(pcmInfo); // } // finally // { // if (wavStream != null) wavStream.Close(); // m_firstTimePCMFormat = false; // } //} //media = addAudioWav(newfullWavPath, true, audioAttrClipBegin, audioAttrClipEnd); media = addAudioWav(dataProv, audioAttrClipBegin, audioAttrClipEnd); } //} } if (media == null) { media = presentation.MediaFactory.CreateExternalAudioMedia(); ((ExternalAudioMedia)media).Src = audioAttrSrc.Value; if (audioAttrClipBegin != null && !string.IsNullOrEmpty(audioAttrClipBegin.Value)) { try { ((ExternalAudioMedia)media).ClipBegin = Time.ParseTimeString(audioAttrClipBegin.Value); } catch (FormatException e) { ((ExternalAudioMedia)media).ClipBegin = new Time(0); string str = "bad time string: " + audioAttrClipBegin.Value; Console.Write(str); Debug.Fail(str); } } if (audioAttrClipEnd != null && !string.IsNullOrEmpty(audioAttrClipEnd.Value)) { try { ((ExternalAudioMedia)media).ClipEnd = Time.ParseTimeString(audioAttrClipEnd.Value); } catch (FormatException e) { ((ExternalAudioMedia)media).ClipEnd = new Time(0); string str = "bad time string: " + audioAttrClipEnd.Value; Console.Write(str); Debug.Fail(str); } } } if (media != null) { ChannelsProperty chProp = treeNode.GetProperty <ChannelsProperty>(); if (chProp == null) { chProp = presentation.PropertyFactory.CreateChannelsProperty(); treeNode.AddProperty(chProp); } if (isSequence) { SequenceMedia mediaSeq = chProp.GetMedia(m_audioChannel) as SequenceMedia; if (mediaSeq == null) { mediaSeq = presentation.MediaFactory.CreateSequenceMedia(); mediaSeq.AllowMultipleTypes = false; chProp.SetMedia(m_audioChannel, mediaSeq); } mediaSeq.ChildMedias.Insert(mediaSeq.ChildMedias.Count, media); } else { chProp.SetMedia(m_audioChannel, media); } } else { System.Diagnostics.Debug.Fail("Media could not be created !"); } }