Ejemplo n.º 1
0
        /// <summary>
        /// Adds the element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>The <see cref="MediaData"/>.</returns>
        public MediaData AddElement(TimelineElement element)
        {
            MediaData media = null;

            if (element.Asset is VideoAsset || element.Asset is AudioAsset)
            {
                media                          = new PlayableMediaData(element);
                media.BufferStart             += this.Media_BufferStart;
                media.BufferEnd               += this.Media_BufferEnd;
                media.DownloadProgressChanged += this.Media_DownloadProgressChanged;
            }
            else if (element.Asset is ImageAsset)
            {
                media = new ImageMediaData(element);
            }
            else if (element.Asset is TitleAsset)
            {
                media = new TitleMediaData(element);
            }

            if (media != null)
            {
                this.mediaData.Add(media);
            }

            return(media);
        }
Ejemplo n.º 2
0
        private void DataCallback(MediaData mediaInfo)
        {
            switch (++_callbackCounter)
            {
            case downloadInfoCallback:
                var file = new FileInfo(Path.Combine
                                        (
                                            _config[ConfigurationKeys.AudioDownloadDirectory],
                                            $"{mediaInfo.Title}{MP3AudioSplitter.Mp3Extension}"
                                        ));

                if (file.Exists)
                {
                    OnCancel();

                    _windowService.ChangePage <AudioSplitDefinitionPageViewModel>(new MediaDownloadResponse
                    {
                        File = file,
                        Data = mediaInfo
                    });
                }
                else
                {
                    SongTitle = mediaInfo.Title;
                }
                break;

            case videoDownloadedCallback:
                HasDownloaded = true;
                break;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Determines if given mediadata is indexable
        /// </summary>
        /// <param name="media"></param>
        /// <returns></returns>
        public virtual bool AllowIndexing(MediaData media)
        {
            if (media == null)
            {
                return(false);
            }

            bool allowed = true;
            var  ext     = media.SearchFileExtension();

            if (!string.IsNullOrWhiteSpace(ext))
            {
                allowed = _AttachmentSettings?.SupportedFileExtensions?.Any(x => string.Compare(ext, x.Trim().TrimStart('.'), true) == 0) == true;
            }

            if (allowed && _AttachmentSettings.EnableFileSizeLimit)
            {
                long fileByteSize = -1;

                if (media?.BinaryData != null)
                {
                    using (var stream = media.BinaryData.OpenRead())
                    {
                        fileByteSize = stream.Length;
                    }
                }

                allowed = _AttachmentSettings.FileSizeLimit <= fileByteSize;
            }

            return(allowed);
        }
Ejemplo n.º 4
0
 private string GetLink(MediaData file)
 {
     using (var stream = file.BinaryData.OpenRead())
     {
         var reader = new StreamReader(stream);
         var ret    = "";
         while (!reader.EndOfStream)
         {
             ret = reader.ReadLine();
         }
         if (ret == null)
         {
             return("");
         }
         reader.Close();
         if (ret.IsFilePath())
         {
             try
             {
                 var url = new UriBuilder("file://" + ret);
                 if (ret.IndexOf(":", StringComparison.Ordinal) > 0)
                 {
                     url = new UriBuilder("file:///" + ret);
                 }
                 ret = url.ToString();
                 return(ret);
             }
             catch (Exception exc)
             {
                 ret = exc.Message;
             }
         }
         return(ret.IsURL() ? new UriBuilder(ret).ToString() : "");
     }
 }
        /// <summary>
        /// Reads the attributes of a ManagedAudioMedia xuk element.
        /// </summary>
        /// <param name="source">The source <see cref="XmlReader"/></param>
        protected override void XukInAttributes(XmlReader source)
        {
            base.XukInAttributes(source);

            string uid = source.GetAttribute(XukStrings.MediaDataUid);

            if (string.IsNullOrEmpty(uid))
            {
                throw new exception.XukException("MediaDataUid attribute is missing from AudioMediaData");
            }
            //if (!Presentation.MediaDataManager.IsManagerOf(uid))
            //{
            //    throw new exception.XukException(String.Format(
            //                                         "The MediaDataManager does not manage a AudioMediaData with uid {0}",
            //                                         uid));
            //}

            MediaData md = Presentation.MediaDataManager.GetManagedObject(uid);

            if (!(md is AudioMediaData))
            {
                throw new exception.XukException(String.Format(
                                                     "The AudioMediaData with uid {0} is a {1} which is not a urakawa.media.data.audio.AudioMediaData",
                                                     uid, md.GetType().FullName));
            }
            AudioMediaData = md as AudioMediaData;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Returns a list of the next media available.
        /// </summary>
        /// <param name="nextPosition">The position being evaluated.</param>
        /// <returns>The list of media.</returns>
        private IList <int> NextCurrentMedia(TimeSpan nextPosition)
        {
            IList <int> nextCurrentMedia = new List <int>();

            for (int i = 0; i < this.mediaData.Count; i++)
            {
                MediaData m = this.mediaData[i];

                double position;
                if (m is BlankMediaData)
                {
                    position = TimeSpan.FromSeconds(m.TimelineElement.Position.TotalSeconds).TotalSeconds - (m.Out.TotalSeconds - m.In.TotalSeconds);
                }
                else
                {
                    position = m.TimelineElement.Position.TotalSeconds;
                }

                if (position <= nextPosition.TotalSeconds && (position + (m.Out.TotalSeconds - m.In.TotalSeconds)) >= nextPosition.TotalSeconds)
                {
                    nextCurrentMedia.Add(i);
                }
            }

            return(nextCurrentMedia);
        }
        public void GenerateReport(Guid reportId, Guid summaryId, string headerText)
        {
            // Find the Workflow Instance
            var report  = _rptUoW.Find <Report>(reportId);
            var summary = _summariesUnitOfWork.Find <Summary>(summaryId);

            // Generate Attachment and MediaData
            var mediaMeta = new MediaMeta();
            var mediaData = new MediaData();
            var document  = new Document();

            mediaMeta.AttachedDate = DateTime.Now;
            mediaMeta.AttachedBy   = report.CreatedBy.ToString();
            //Get Media Data memory Stream value
            document.MemoryStream = _documentService.RenderReport(report, AttachmentType.PDF, headerText);
            document.ReportName   = ReportInfoFormatter.GetLongName(report);
            mediaMeta.FileName    = document.ReportName;
            mediaData.Data        = document.MemoryStream;
            mediaMeta.Source      = AttachmentDescription.OfficerReport.GetDescription();
            mediaMeta.Id          = Guid.NewGuid();

            mediaMeta.ContentSubType = mediaMeta.Extension = AttachmentType.PDF.ToString();
            mediaMeta.ContentType    = "Application";
            mediaMeta.Size           = mediaData.Data.Length;
            mediaData.Id             = _mediaMetaService.CreateNewMedia(mediaMeta);
            _mediaDataService.UploadMediaData(mediaData);

            // Add officer Attachment file
            AttachOfficerReport(MapAttachment(mediaMeta), report, summary);

            _documentService.Dispose();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Toggles the motion of the current media element.
        /// </summary>
        /// <param name="mediaData">The media data o the current element.</param>
        public void ToggleSlowMotion(MediaData mediaData)
        {
            bool result = false;

            if (mediaData != null)
            {
                CoreSmoothStreamingMediaElement mediaElement = mediaData.Media as CoreSmoothStreamingMediaElement;

                if (mediaElement != null)
                {
                    result = mediaElement.OnSlowMotion();
                }
            }
            else
            {
                if (this.HasSource)
                {
                    result = this.Player.OnSlowMotion();
                }
            }

            if (!result)
            {
                this.SlowMotionButton.IsChecked = false;
            }
        }
Ejemplo n.º 9
0
    static TimeSpan GetMediaDuration(string mediaFile, TimeSpan maxTimeToWait)
    {
        var mediaData = new MediaData()
        {
            MediaUri = new Uri(mediaFile)
        };
        var      thread   = new Thread(GetMediaDurationThreadStart);
        DateTime deadline = DateTime.Now.Add(maxTimeToWait);

        thread.Start(mediaData);

        while (!mediaData.Done && ((TimeSpan.Zero == maxTimeToWait) || (DateTime.Now < deadline)))
        {
            Thread.Sleep(100);
        }

        Dispatcher.FromThread(thread).InvokeShutdown();
        if (!mediaData.Done)
        {
            throw new Exception(string.Format("GetMediaDuration timed out after {0}", maxTimeToWait));
        }
        if (mediaData.Failure)
        {
            throw new Exception(string.Format("MediaFailed {0}", mediaFile));
        }
        return(mediaData.Duration);
    }
Ejemplo n.º 10
0
        /// <summary>
        /// 分发码流
        /// </summary>
        /// <param name="channelNo">通道号码</param>
        /// <param name="data">码流</param>
        public void SendMediaData(string channelLabel, MediaData data)
        {
            NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log);

            try
            {
                bool successed = this.channelDicLocker.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME);
                // 申请互斥
                if (successed)
                {
                    try
                    {
                        if (this.monitorChannelDic.ContainsKey(channelLabel))
                        {
                            this.monitorChannelDic[channelLabel].AddMediaData(data);
                        }
                    }
                    finally
                    {
                        // 释放互斥量
                        this.channelDicLocker.ExitReadLock();
                    }
                }
                else
                {
                    // 日志
                    logEx.Error("SendRtpData: Enert Write Lock Failed.WaitingReadCount:{0};WaitingWriteCount:{1}.", this.channelDicLocker.WaitingReadCount, this.channelDicLocker.WaitingWriteCount);
                }
            }
            catch (Exception ex)
            {
                // 日志
                logEx.Error(ex, "SendRtpData: Enert Write Lock Exception.");
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Picks a thumbnail of the current media element.
        /// </summary>
        /// <param name="mediaData">The media data o the current element.</param>
        public void PickThumbnail(MediaData mediaData)
        {
            if (mediaData != null)
            {
                SmoothStreamingMediaElement mediaElement = mediaData.Media as SmoothStreamingMediaElement;

                if (mediaElement != null)
                {
                    this.StartThumbnailBuffer();
                    bool     thumbnailSeekCompleted = false;
                    TimeSpan currentPosition        = mediaElement.Position;

                    CoreSmoothStreamingMediaElement thumbnailMediaElement = new CoreSmoothStreamingMediaElement
                    {
                        Width    = mediaElement.ActualWidth,
                        Height   = mediaElement.ActualHeight,
                        IsMuted  = true,
                        AutoPlay = false,
                        Volume   = 0,
                    };

                    DispatcherTimer thubmnailTimer = new DispatcherTimer {
                        Interval = new TimeSpan(0, 0, 0, 5)
                    };

                    thubmnailTimer.Tick += (sender, e) =>
                    {
                        if (thumbnailSeekCompleted)
                        {
                            thumbnailSeekCompleted = false;
                            thubmnailTimer.Stop();
                            WriteableBitmap writeableBitmap = new WriteableBitmap(thumbnailMediaElement, null);

                            // writeableBitmap.Render(mediaElement, null);
                            writeableBitmap.Invalidate();
                            this.Model.SetThumbnail(writeableBitmap);
                            this.PlayerContainerGrid.Children.Remove(thumbnailMediaElement);
                            thumbnailMediaElement = null;
                            thubmnailTimer        = null;
                            this.EndThumbnailBuffer();
                        }
                    };

                    thubmnailTimer.Start();

                    this.PlayerContainerGrid.Children.Add(thumbnailMediaElement);

                    thumbnailMediaElement.ManifestReady += (sender, e) => ((CoreSmoothStreamingMediaElement)sender).SelectMaxAvailableBitrateTracks("cameraAngle", "camera1");

                    thumbnailMediaElement.MediaOpened += (sender, e) =>
                    {
                        ((SmoothStreamingMediaElement)sender).Position       = currentPosition;
                        ((CoreSmoothStreamingMediaElement)sender).Visibility = Visibility.Collapsed;
                    };

                    thumbnailMediaElement.SeekCompleted        += (sender, e) => thumbnailSeekCompleted = true;
                    thumbnailMediaElement.SmoothStreamingSource = mediaElement.SmoothStreamingSource;
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Determines if given mediadata is indexable
        /// </summary>
        /// <param name="media"></param>
        /// <returns></returns>
        public virtual bool AllowIndexing(MediaData media)
        {
            if (media == null || !_attachmentSettings.EnableAttachmentPlugins)
            {
                return(false);
            }

            var allowed = true;
            var ext     = media.SearchFileExtension();

            if (!string.IsNullOrWhiteSpace(ext))
            {
                allowed = _attachmentSettings?.SupportedFileExtensions?.Any(x => string.Compare(ext, x.Trim().TrimStart('.'), StringComparison.OrdinalIgnoreCase) == 0) == true;
            }

            if (!allowed || !_attachmentSettings.EnableFileSizeLimit)
            {
                return(allowed);
            }
            long fileByteSize = -1;

            if (media.BinaryData != null)
            {
                using (var stream = media.BinaryData.OpenRead())
                {
                    fileByteSize = stream.Length;
                }
            }

            allowed = fileByteSize > 1 && _attachmentSettings.FileSizeLimit <= fileByteSize;

            return(allowed);
        }
Ejemplo n.º 13
0
        public static MediaData CreateMediaData(byte[] data)
        {
            var res = new MediaData();

            res.Data = data;
            return(res);
        }
 private void Item_DeleteMediaEvent(object sender, Code.Media.MediaData e)
 {
     if (e != null)
     {
         MessageBoxResult messageBoxResult = MessageBox.Show("Bạn có muốn xoá file video này không?", "Xoá video", System.Windows.MessageBoxButton.YesNo);
         if (messageBoxResult == MessageBoxResult.Yes)
         {
             alta_class_ftp.deleteFile(e.Url, App.setting.ftp_user, App.setting.ftp_password);
             MediaData.Delete(e);
             UIMedia m = this.list_Box_Item.SelectedItem as UIMedia;
             m.Animation_Opacity_View_Frame(false, () =>
             {
                 this.list_Box_Item.Items.Remove(m);
                 this.Datas.Remove(e);
                 this.totalMedia -= 1;
                 if (this.to < this.totalMedia)
                 {
                     if (this.User == null)
                     {
                         this.Datas = App.curUser.LoadMedias(this.from, this.to, out this.totalMedia, this.TypeMedia);
                     }
                     else
                     {
                         this.Datas = this.User.LoadMedias(this.from, this.to, out this.totalMedia, this.TypeMedia, true);
                     }
                     this.LoadGUI();
                 }
             }, 600);
             this.list_Box_Item.SelectedIndex = -1;
         }
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Removes the blank element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>The <see cref="MediaData"/>.</returns>
        public MediaData RemoveBlankElement(TimelineElement element)
        {
            MediaData media = this.FindBlankMediaByElement(element);

            this.Remove(media);
            return(media);
        }
Ejemplo n.º 16
0
 //-------------------------------------------------------------------------------------------------------------------
 private void DeleteAllFileAction()
 {
     if (MessageBox.Show("Are you sure?", "All track will be deleted.", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
     {
         MediaData.DeleteAllTracks();
     }
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Removes the specified media.
 /// </summary>
 /// <param name="media">The media.</param>
 private void Remove(MediaData media)
 {
     if (media != null)
     {
         this.mediaData.Remove(media);
     }
 }
Ejemplo n.º 18
0
 public Album(MediaData data, int?artistId, int?genreId) : base()
 {
     Title    = data.Album;
     ArtistId = artistId;
     GenreId  = genreId;
     Year     = (int)data.Year;
 }
Ejemplo n.º 19
0
 private void DeleteLinksBetweenMediaAndCodes(MediaData media, IEnumerable <string> codes)
 {
     foreach (string code in codes)
     {
         DeleteMediaLink(media, code);
     }
 }
Ejemplo n.º 20
0
        public async Task <MediaStatus> LoadMedia(
            ChromecastApplication application,
            Uri mediaUrl,
            string contentType,
            CancellationToken token,
            IMetadata metadata   = null,
            string streamType    = "BUFFERED",
            double duration      = 0D,
            object customData    = null,
            Track[] tracks       = null,
            int[] activeTrackIds = null,
            bool autoPlay        = true,
            double currentTime   = 0D)
        {
            int requestId   = RequestIdProvider.Next;
            var mediaObject = new MediaData(mediaUrl.ToString(), contentType, metadata, streamType, duration, customData, tracks);
            var req         = new LoadRequest(requestId, application.SessionId, mediaObject, autoPlay, currentTime,
                                              customData, activeTrackIds);

            var reqJson = req.ToJson();
            var requestCompletedSource = await AddRequestTracking(requestId, token).ConfigureAwait(false);

            await Write(MessageFactory.Load(application.TransportId, reqJson), token).ConfigureAwait(false);

            return(await requestCompletedSource.Task.WaitOnRequestCompletion(token).ConfigureAwait(false));
        }
Ejemplo n.º 21
0
        private SimpleMedia GetInsight(string id, bool isStory)
        {
            //url for one media
            string mediaUrl =
                $"{_fbGraphApiBaseUrl}/{id}?access_token={_accessToken}&fields=media_url%2Cmedia_type%2Ccomments_count%2Clike_count%2Ctimestamp%2Cpermalink%2Ccaption";
            //invoke the request
            string jsonResult = this.GetGraphApiUrl(mediaUrl);
            // convert to json annotated object
            MediaData mediaData = JsonConvert.DeserializeObject <MediaData>(jsonResult);

            InstagramInsight insight = GetMediaImpressionsInsight(mediaData.id, isStory);

            var engagementValue  = insight.data.FirstOrDefault(i => i.name == "engagement");
            var impressionsValue = insight.data.FirstOrDefault(i => i.name == "impressions");
            var reachValue       = insight.data.FirstOrDefault(i => i.name == "reach");

            return
                (new SimpleMedia
            {
                id = mediaData.id,
                like_count = mediaData.like_count,
                comments_count = mediaData.comments_count,
                impression_count = impressionsValue?.values[0].value ?? -1,
                engagement_count = engagementValue?.values[0].value ?? -1,
                reach_count = reachValue?.values[0].value ?? -1,
                media_url = mediaData.media_url,
                permalink = mediaData.permalink,
                //Comments = GetMediaCommentsEntities(mediaData.id),
                timestamp = mediaData.timestamp
            });
        }
Ejemplo n.º 22
0
        public void DeleteVideoCategory(int CategoryId)
        {
            var videoCategory = GetVideoCategory(CategoryId);

            MediaData.VideoCategories.DeleteOnSubmit(videoCategory);
            MediaData.SubmitChanges();
        }
 private void Item_DeleteCameraEvent(object sender, MediaData e)
 {
     if (e != null)
     {
         MessageBoxResult messageBoxResult = MessageBox.Show("Bạn có muốn xoá camera này không?", "Xoá camera", System.Windows.MessageBoxButton.YesNo);
         if (messageBoxResult == MessageBoxResult.Yes)
         {
             Code.Media.MediaData.Delete(e);
             UIcamera m = this.list_Box_Item.SelectedItem as UIcamera;
             m.Animation_Opacity_View_Frame(false, () =>
             {
                 this.list_Box_Item.Items.Remove(m);
                 this.Datas.Remove(e);
                 this.totalMedia -= 1;
                 if (this.to < this.totalMedia)
                 {
                     if (this.User == null)
                     {
                         this.Datas = App.curUser.LoadMedias(this.from, this.to, out this.totalMedia, this.TypeMedia);
                     }
                     else
                     {
                         this.Datas = this.User.LoadMedias(this.from, this.to, out this.totalMedia, this.TypeMedia, true);
                     }
                     this.LoadGUI();
                 }
             }, 600);
             this.list_Box_Item.SelectedIndex = -1;
         }
     }
 }
Ejemplo n.º 24
0
        //private FileStream fs = new FileStream(@"D:\IvsVideoStream2.264", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
        //private int writeCount = 0;

        /// <summary>
        /// 向下注册的码流回调函数
        /// </summary>
        /// <param name="cameraNo">摄像头编号</param>
        /// <param name="mediaData">码流</param>
        /// <param name="monitorId">监控平台ID</param>
        private void DataCallBackFunc(string cameraNo, MediaData mediaData, string monitorId)
        {
            //摄像头编号要加上平台唯一标记
            cameraNo = EncodeNo(cameraNo, monitorId);

            dataCallBack(cameraNo, mediaData, monitorId);
        }
        /// <summary>
        /// Move a folder image to slide show view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FolderImage_Move(object sender, MouseEventArgs e)
        {
            // Get position of mouse
            System.Windows.Point point = e.GetPosition(null);
            // Calculate distance
            Vector diff = mouseMoveStartingPoint - point;

            // If draged distance greater than minumum distance
            if (e.LeftButton == MouseButtonState.Pressed &&
                (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
                 Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
            {
                // Get source id
                Border    border    = (Border)sender;
                MediaData mediaData = (MediaData)border.DataContext;
                // Create new temporary media data entry
                bool thumbNailLoaded = true;
                if (mediaData is ImageData)
                {
                    // If image has loaded
                    thumbNailLoaded = ((ImageData)mediaData).ThumbNailImageLoaded;
                }
                if (thumbNailLoaded)
                {
                    //MediaData mediaData = NewMediaData(folderImages[id], -1, -1, false);
                    if (mediaData != null)
                    {
                        DragDrop.DoDragDrop((DependencyObject)sender, mediaData, DragDropEffects.Move);
                    }
                }
            }
        }
Ejemplo n.º 26
0
        private void UpdateMetaData(IInRiverResource resource, InRiverImportResource updatedResource)
        {
            MediaData editableMediaData = (MediaData)((MediaData)resource).CreateWritableClone();

            ResourceMetaField resourceFileId = updatedResource.MetaFields.FirstOrDefault(m => m.Id == "ResourceFileId");

            if (resourceFileId != null && !string.IsNullOrEmpty(resourceFileId.Values.First().Data) && resource.ResourceFileId != int.Parse(resourceFileId.Values.First().Data))
            {
                IBlobFactory blobFactory = ServiceLocator.Current.GetInstance <IBlobFactory>();

                FileInfo fileInfo = new FileInfo(updatedResource.Path);
                if (fileInfo.Exists == false)
                {
                    throw new FileNotFoundException("File could not be imported", updatedResource.Path);
                }

                string ext = fileInfo.Extension;

                Blob blob = blobFactory.CreateBlob(editableMediaData.BinaryDataContainer, ext);
                using (Stream s = blob.OpenWrite())
                {
                    FileStream fileStream = File.OpenRead(fileInfo.FullName);
                    fileStream.CopyTo(s);
                }

                editableMediaData.BinaryData   = blob;
                editableMediaData.RouteSegment = GetUrlSlug(updatedResource);
            }

            ((IInRiverResource)editableMediaData).HandleMetaData(updatedResource.MetaFields);

            _contentRepository.Save(editableMediaData, SaveAction.Publish, AccessLevel.NoAccess);
        }
 /// <summary>
 /// Constructor setting the source <see cref="IManaged"/>,
 /// the new <see cref="MediaData"/> and the <see cref="MediaData"/> prior to the change
 /// </summary>
 /// <param name="source">The source <see cref="Media"/> - must also be <see cref="IManaged"/></param>
 /// <param name="newMD">The new <see cref="MediaData"/></param>
 /// <param name="prevMD">The <see cref="MediaData"/> prior to the change</param>
 public MediaDataChangedEventArgs(Media source, MediaData newMD, MediaData prevMD)
     : base(source)
 {
     SourceManagedMedia = source as IManaged;
     NewMediaData       = newMD;
     PreviousMediaData  = prevMD;
 }
Ejemplo n.º 28
0
        /// <param name="media">The media to remove as link</param>
        /// <param name="code">The code of the catalog content from which the <paramref name="media"/> should be removed.</param>
        private void DeleteMediaLink(MediaData media, string code)
        {
            ContentReference contentReference = _referenceConverter.GetContentLink(code);

            if (ContentReference.IsNullOrEmpty(contentReference))
            {
                return;
            }

            IAssetContainer writableContent = null;

            if (_contentRepository.TryGet(contentReference, out NodeContent nodeContent))
            {
                writableContent = nodeContent.CreateWritableClone <NodeContent>();
            }
            else if (_contentRepository.TryGet(contentReference, out EntryContentBase catalogEntry))
            {
                writableContent = catalogEntry.CreateWritableClone <EntryContentBase>();
            }

            writableContent?.CommerceMediaCollection.CreateWritableClone();
            CommerceMedia mediaToRemove = writableContent?.CommerceMediaCollection?.FirstOrDefault(x => x.AssetLink.Equals(media.ContentLink));

            if (mediaToRemove == null)
            {
                return;
            }

            writableContent.CommerceMediaCollection.Remove(mediaToRemove);
            _contentRepository.Save((IContent)writableContent, SaveAction.Publish, AccessLevel.NoAccess);
        }
Ejemplo n.º 29
0
        public Discussion cloneDiscussion(DiscCtx ctx, Discussion original, Person moderator, int i)
        {
            var d = new Discussion();

            d.Subject = injectNumber(original.Subject, i);

            //copy background
            d.Background      = new RichText();
            d.Background.Text = original.Background.Text;
            foreach (var src in original.Background.Source)
            {
                var s = new Source();
                s.Text        = src.Text;
                s.OrderNumber = src.OrderNumber;
                d.Background.Source.Add(s);
            }

            foreach (var media in original.Attachment)
            {
                var attach = new Attachment();
                attach.Discussion    = d;
                attach.Format        = media.Format;
                attach.Link          = media.Link;
                attach.Name          = media.Name;
                attach.Title         = media.Title;
                attach.VideoEmbedURL = media.VideoEmbedURL;
                attach.VideoLinkURL  = media.VideoLinkURL;
                attach.VideoThumbURL = media.VideoThumbURL;
                attach.OrderNumber   = media.OrderNumber;

                if (media.Thumb != null)
                {
                    attach.Thumb = (byte[])media.Thumb.Clone();
                }

                if (media.MediaData != null && media.MediaData.Data != null)
                {
                    var mediaClone = new MediaData();
                    mediaClone.Data  = (byte[])media.MediaData.Data.Clone();
                    attach.MediaData = mediaClone;
                }

                attach.Person = moderator;

                d.Attachment.Add(attach);
            }

            d.HtmlBackground = original.HtmlBackground;

            foreach (var topic in original.Topic)
            {
                var t = new Topic();
                t.Name = injectNumber(topic.Name, i);
                t.Person.Add(moderator);
                d.Topic.Add(t);
            }

            return(d);
        }
Ejemplo n.º 30
0
 //-------------------------------------------------------------------------------------------------------------------
 private void DeletePlayListAction()
 {
     OnMainGridScrollIntoView(MediaData.CurrentList.SelectedTrack);
     if (MessageBox.Show("Are you sure?", "List will be deleted.", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
     {
         MediaData.DeleteCurrentPlayList();
     }
 }
Ejemplo n.º 31
0
 public static string GetFileSize(MediaData media)
 {
     if (media != null)
     {
         using (var stream = media.BinaryData.OpenRead())
         {
             return (stream.Length / 1024) + " kB";
         }
     }
     return string.Empty;
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Recursively trawls through a directory structure for media files,
        /// using them to build a DataSet of media metadata.
        /// </summary>
        /// <param name="directory">Starting point for the recursive search</param>
        /// <returns>MediaData object (a strongly-typed DataSet)</returns>
        public MediaData RetrieveRecursiveDirectoryInfo(string directory)
        {
            MediaData md = new MediaData();

            RecurseDirectories(directory, md);

            return md;
        }
 private void WriteBlobToStorage(string name, byte[] data, MediaData md)
 {
     var blob = _blobfactory.CreateBlob(md.BinaryDataContainer, Path.GetExtension(name));
     using (var s = blob.OpenWrite())
     {
         BinaryWriter w = new BinaryWriter(s);
         w.Write(data);
         w.Flush();
     }
     md.BinaryData = blob;
 }
Ejemplo n.º 34
0
        /// <summary>
        /// 发送码流添加进队列
        /// </summary>
        /// <param name="trp"></param>
        public void AddMediaData(MediaData data)
        {
            NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log);

            // 通道失效,不发送码流
            if (isValid == false)
            {
                if (flag == false)
                {
                    logEx.Error("AddMediaData label={0} is invalid.");
                    flag = true;
                }

                return;
            }

            try
            {
                bool successed = this.meidaDataQueueLocker.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME);
                // 申请互斥
                if (successed)
                {
                    try
                    {
                        this.mediaDataQueue.Enqueue(data);
                    }
                    finally
                    {
                        // 释放互斥量
                        this.meidaDataQueueLocker.ExitWriteLock();
                    }
                }
                else
                {
                    // 日志
                    logEx.Error("AddRtp: Enert Write Lock Failed.WaitingReadCount:{0};WaitingWriteCount:{1}.", this.meidaDataQueueLocker.WaitingReadCount, this.meidaDataQueueLocker.WaitingWriteCount);
                }
            }
            catch (Exception ex)
            {
                // 日志
                logEx.Error(ex, "AddRtp: Enert Write Lock Exception.");
            }

            this.waitEvent.Set();
        }
Ejemplo n.º 35
0
        /// <summary>
        /// rtp码流回调处理
        /// </summary>
        /// <param name="pBuf">帧数据字节数组</param>
        /// <param name="pFrameData">帧数据类型</param>
        /// <param name="uiChannel">通道</param>
        /// <param name="uiBufSize">帧数据字节数组长度</param>
        private void FrameDataCallBackFun(IntPtr pBuf, uint uiBufSize, ref ST_FRAME_DATA pFrameData, uint uiChannel)
        {
            NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log);
            ST_FRAME_DATA frameData = pFrameData;

            MediaDataSender mediaDataSender = null;
            if (this.handelOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME))
            {
                try
                {
                    if (this.videoChannelDataSenderDic.ContainsKey(uiChannel))
                    {
                        mediaDataSender = this.videoChannelDataSenderDic[uiChannel];
                    }
                }
                finally
                {
                    this.handelOperateLock.ExitReadLock();
                }
            }

            if (mediaDataSender == null)
            {
                logEx.Warn("FrameDataCallBackFun mediaDataSender = NULL");
                return;
            }

            StreamType streamType = StreamType.VIDEO_H264;
            //对于支持的码流类型,用break退出switch,对于不支持的码流类型直接舍弃,用return返回
            switch (frameData.iStreamType)
            {
                //对于音频只接收G711A和G711U,其他舍弃
                case (int)IvsStreamType.PAY_LOAD_TYPE_PCMU:
                    streamType = StreamType.AUDIO_G711U;
                    break;
                case (int)IvsStreamType.PAY_LOAD_TYPE_PCMA:
                    streamType = StreamType.AUDIO_G711A;
                    break;

                //只接收H264的视频码流
                case (int)IvsStreamType.PAY_LOAD_TYPE_H264:
                    //H264的标准视频流,作为视频流处理
                    streamType = StreamType.VIDEO_H264;
                    break;
                default:
                    //不支持的类型,直接舍弃,返回
                    return;
            }

            if (streamType == StreamType.AUDIO_G711A || streamType == StreamType.AUDIO_G711U)
            {
                 //如果是音频流,需要判断mic的状态,开启时才发送音频流
                if (this.micOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME))
                {
                    try
                    {
                        if (this.cameraMicStatusDic.ContainsKey(mediaDataSender.CameraNo))
                        {
                            //如果mic为非开启状态,则不发送音频码流,
                            if (!this.cameraMicStatusDic[mediaDataSender.CameraNo])
                            {
                                logEx.Warn("This data is audio,but the mic is off.Chuck the data.Camera no:{0}", mediaDataSender.CameraNo);
                                return;
                            }
                        }
                        else
                        {
                            //默认为关闭状态,因此如果cameraMicStatusDic不包含该摄像头,则认为处于关闭状态,舍弃音频码流
                            logEx.Warn("This data is audio,but the mic is off.Chuck the data.Camera no:{0}", mediaDataSender.CameraNo);
                            return;
                        }
                    }
                    finally
                    {
                        this.micOperateLock.ExitReadLock();
                    }
                }
            }

            try
            {
                MediaData mediaData = new MediaData();
                //获取非托管的数据
                byte[] datagram = new byte[uiBufSize];

                if (!(streamType == StreamType.AUDIO_G711A || streamType == StreamType.AUDIO_G711U))
                {
                    Marshal.Copy(pBuf, datagram, 0, (int)uiBufSize);
                    //视频帧数据头部增加四个四节的开始表实0x000001
                    byte[] newDatagram = new byte[uiBufSize + 4];
                    datagram.CopyTo(newDatagram, 4);
                    newDatagram[3] = 1;
                    mediaData.Data = newDatagram;
                    mediaData.Size = (uint)(uiBufSize + 4);
                }
                else
                {
                    mediaData.Data = datagram;
                    mediaData.Size = (uiBufSize);
                }

                //裸码流
                mediaData.DataType = MediaDataType.FRAME_DATA;
                mediaData.StreamType = streamType;

                //将帧类型转换成各融合网关统一的帧类型
                string name = Enum.GetName(typeof(IvsH264NaluType), frameData.iFrameDataType);
                if (Enum.IsDefined(typeof(FrameDataType), name))
                {
                    FrameDataType frameDataType = (FrameDataType)Enum.Parse(typeof(FrameDataType), name);
                    mediaData.FrameType = frameDataType;
                }
                else
                {
                    mediaData.FrameType = FrameDataType.H264_NALU_TYPE_UNDEFINED;
                }

                //向回调函数转发码流
                mediaDataSender.SendData(mediaData, this.sender);
            }
            catch (System.Exception ex)
            {
                logEx.Error("FrameDataCallBackFun failed.Execption message:{0}", ex.Message);
            }
        }
Ejemplo n.º 36
0
        private void CreateThumbnail()
        {
            var mediaData = new MediaData(this.mediaItem);
            MediaStream thumbnailStream = mediaData.GetThumbnailStream();
            if (thumbnailStream == null)
                return;

            string file = GetThumbnailFilename();
            FileUtil.EnsureFileFolder(file);
            FileUtil.CreateFile(FileUtil.MapPath(file), thumbnailStream.Stream, true);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Retrieves media information for a single directory as a DataSet.
        /// </summary>
        /// <param name="directory">Directory to be used for data retrieval</param>
        /// <returns>MediaData object (a strongly-typed DataSet)</returns>
        public MediaData RetrieveSingleDirectoryInfo(string directory)
        {
            MediaData md = new MediaData();

            DirectoryInfo dirInfo = new DirectoryInfo(directory);
            FileInfo[] fileInfos = dirInfo.GetFiles("*.wma");

            for (int i=0; i < fileInfos.Length; i++)
            {
                MediaData.TrackRow row = md.Track.NewTrackRow();
                RetrieveTrackRow(dirInfo + "\\" + fileInfos[i].Name, ref row);
                md.Track.AddTrackRow(row);

                NotifyEventSubscribers(row);
            }

            return md;
        }
Ejemplo n.º 38
0
 /// <summary>
 /// 发送音频码流
 /// </summary>
 /// <param name="videoData"></param>
 /// <param name="sender"></param>
 public void SendAudioData(MediaData videoData, string sender)
 {
     this.DataCallBack(this.CameraNo, videoData, sender);
 }
Ejemplo n.º 39
0
        /// <summary>
        /// 发送视频码流,
        /// 对于H264的帧数据,如果监控平台回调的码流,SPS PPS IDR是分开发送的,则需要进行拼帧处理,将SPS+PPS+IDR拼接在一起发送
        /// </summary>
        /// <param name="mediaData"></param>
        /// <param name="sender"></param>
        public void SendVideoData(MediaData mediaData, string sender)
        {
            //对于H264的帧数据,如果监控平台回调的码流,SPS PPS IDR是分开发送的,则需要进行拼帧处理,将SPS+PPS+IDR拼接在一起发送
            if (mediaData.DataType == MediaDataType.FRAME_DATA)
            {
                switch (mediaData.FrameType)
                {
                    case FrameDataType.H264_SEI_NALU_TYPE:
                        //SEI的包,直接丢弃
                        return;

                    case FrameDataType.H264_SPS_NALU_TYPE:
                        //SPS的类型,先清空缓存
                        //this.CacheData = new byte[mediaData.Size];
                        //将SPS的数据缓存
                        this.CacheData = mediaData.Data;
                        this.LastCacheFrameType = mediaData.FrameType;

                        //直接return,暂不发送
                        return;

                    case FrameDataType.H264_PPS_NALU_TYPE:
                        //如果缓存最后一帧数据不为SPS或者PPS,说明数据乱序,舍弃。
                        if ((this.LastCacheFrameType != FrameDataType.H264_SPS_NALU_TYPE) && (this.LastCacheFrameType != FrameDataType.H264_PPS_NALU_TYPE))
                        {
                            return;
                        }

                        //将PPS的数据缓存,暂不发送
                        byte[] byteTemp = new byte[this.CacheData.Length + mediaData.Data.Length];
                        this.CacheData.CopyTo(byteTemp, 0);
                        mediaData.Data.CopyTo(byteTemp, this.CacheData.Length);
                        this.CacheData = byteTemp;

                        this.LastCacheFrameType = mediaData.FrameType;

                        //直接return,暂不发送
                        return;

                    case FrameDataType.H264_IDR_NALU_TYPE:
                        //如果缓存是上最后一帧数据不为PPS,说明数据乱序,舍弃
                        if (this.LastCacheFrameType != FrameDataType.H264_PPS_NALU_TYPE)
                        {
                            return;
                        }

                        byteTemp = new byte[this.CacheData.Length + mediaData.Data.Length];
                        this.CacheData.CopyTo(byteTemp, 0);
                        mediaData.Data.CopyTo(byteTemp, this.CacheData.Length);
                        mediaData.Data = byteTemp;
                        mediaData.Size = (uint)mediaData.Data.Length;
                        //break跳出 switch,进行发送
                        break;

                    default:
                        //其他类型的数据,直接发送
                        break;
                }
            }

            this.DataCallBack(this.CameraNo, mediaData, sender);
        }
Ejemplo n.º 40
0
        //private FileStream fs = new FileStream(@"D:\IvsVideoStreambefore.264", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
        //private int writeCount = 0;
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="videoData"></param>
        /// <param name="sender"></param>
        public void SendData(MediaData mediaData, string sender)
        {
            if (mediaData.StreamType == StreamType.VIDEO_H264)
            {
                //if (writeCount < 1000)
                //{
                //    fs.Write(mediaData.Data, 0, (int)mediaData.Size);
                //    writeCount++;
                //}

                SendVideoData(mediaData, sender);
            }
            if (mediaData.StreamType == StreamType.AUDIO_G711A || mediaData.StreamType == StreamType.AUDIO_G711U)
            {
                SendAudioData(mediaData, sender);
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Recursive function used by RetrieveRecursiveDirectoryInfo to drill down
        /// the directory tree.
        /// </summary>
        /// <param name="directory">Current directory level</param>
        /// <param name="md">MediaData structure in current form</param>
        private void RecurseDirectories(string directory, MediaData md)
        {
            DirectoryInfo parent = new DirectoryInfo(directory);

            DirectoryInfo[] children = parent.GetDirectories();
            foreach (DirectoryInfo folder in children)
            {
                FileInfo[] fileInfos = folder.GetFiles("*.wma");

                for (int i=0; i < fileInfos.Length; i++)
                {
                    MediaData.TrackRow row = md.Track.NewTrackRow();
                    RetrieveTrackRow(folder.FullName + "\\" + fileInfos[i].Name, ref row);
                    md.Track.AddTrackRow(row);

                    NotifyEventSubscribers(row);
                }

                RecurseDirectories(folder.FullName, md);
            }
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Internal method used to fire the TrackAdded event.
 /// </summary>
 /// <param name="row">Row that's just been added</param>
 private void NotifyEventSubscribers(MediaData.TrackRow row)
 {
     // notify any event subscribers
     if (TrackAdded != null)
     {
         TrackAdded(this, new TrackInfoEventArgs(
             (row.IsTitleNull()  ? "" : row.Title),
             (row.IsAuthorNull() ? "" : row.Author)));
     }
 }
Ejemplo n.º 43
0
        /// <summary>
        /// 发送rtp码流
        /// </summary>
        /// <param name="cameraNo">摄像头编号</param>
        /// <param name="data">码流</param>
        /// <param name="sender">监控系统</param>
        private void SendMediaData(string cameraNo, MediaData videoData, string sender)
        {
            NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log);

            if (videoData.StreamType == StreamType.VIDEO_H264)
            {
                this.SendVideoData(cameraNo, videoData, sender);
            }
            else
            {
                this.SendAudioData(cameraNo, videoData, sender);
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Used internally to fill a row of a DataSet with metadata for the given media file.
        /// </summary>
        /// <param name="filename">Windows Media File (.wma file)</param></param>
        /// <param name="row">The TrackRow to be filled with data</param>
        private void RetrieveTrackRow(string filename, ref MediaData.TrackRow row)
        {
            MediaData.TrackDataTable tab = new MediaData.TrackDataTable();

            using (MetadataEditor md = new MetadataEditor(filename))
            {
            row.AlbumTitle = md[MediaMetadata.AlbumTitle] as string;
            row.AlbumArtist = md[MediaMetadata.AlbumArtist] as string;
            row.Author = md[MediaMetadata.Author] as string;

            object o = md[MediaMetadata.BitRate];
            if (o == null)
              row.SetBitRateNull();
            else
              row.BitRate = (uint)o;

            row.Composer = md[MediaMetadata.Composer] as string;
            row.Conductor = md[MediaMetadata.Conductor] as string;

            o = md[MediaMetadata.Duration];
            if (o == null)
              row.SetDurationNull();
            else
            {
              row.Duration = new TimeSpan((long)(ulong)o);
            }

            row.FileName = filename;

            o = md[MediaMetadata.FileSize];
            if (o == null)
              row.SetFileSizeNull();
            else
              row.FileSize = (ulong)o;

            row.Genre = md[MediaMetadata.Genre] as string;

            o = md[MediaMetadata.IsProtected];
            if (o == null)
              row.SetIsProtectedNull();
            else
              row.IsProtected = (bool)o;

            row.Lyrics = md[MediaMetadata.Lyrics] as string;
            row.AcoustID = md[MediaMetadata.AcoustID] as string;
            row.MBID = md[MediaMetadata.MBID] as string;
            row.Publisher = md[MediaMetadata.Publisher] as string;
            row.Text = md[MediaMetadata.Text] as string;
            row.Title = md[MediaMetadata.Title] as string;

            o = md[MediaMetadata.TrackNumber];
                if (o == null)
                    row.SetTrackNumberNull();
                else
                    row.TrackNumber = (uint) o;
              }
        }
Ejemplo n.º 45
0
        /// <summary>
        /// 发送视频码流
        /// </summary>
        /// <param name="cameraNo"></param>
        /// <param name="videoData"></param>
        /// <param name="sender"></param>
        private void SendVideoData(string cameraNo, MediaData videoData, string sender)
        {
            NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log);

            try
            {
                Dictionary<string, List<string>> temp = new Dictionary<string, List<string>>(this.cameraVideoRelationDic);
                if (null == temp)
                {
                    logEx.Trace("SendVideoData temp is null.");
                    return;
                }

                if (!temp.ContainsKey(cameraNo))
                {
                    logEx.Trace("SendVideoData can't find cameraNo={0}.", cameraNo);
                    return;
                }

                // 分发视频码流
                foreach (string item in temp[cameraNo])
                {
                    this.monitorChannelManager.SendMediaData(item, videoData);
                }
            }
            catch (Exception ex)
            {
                // 日志
                logEx.Error(ex, "SendVideoData: Enert Write Lock Exception.");
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// 开始读取 码流数据
        /// </summary>
        /// <param name="str"></param>
        public void ReadData(Common.DataCallBack dataCallBack)
        {
            NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log);

            Thread th = new Thread(new ThreadStart(() =>
            {
                while (!shouldStop)
                {
                    try
                    {
                        if (pipedStream != null && pipedStream.IsConnected)
                        {
                            byte[] byteArray = new byte[4]; //unit字节长度
                            pipedStream.ReadMode = PipeTransmissionMode.Byte;

                            MediaData mediaData = new MediaData();

                            pipedStream.Read(byteArray, 0, 4);
                            mediaData.Size = (uint)BitConverter.ToInt32(byteArray, 0);
                            if (mediaData.Size == 0)
                            {
                                continue;
                            }
                            pipedStream.Read(byteArray, 0, 4);
                            mediaData.StreamType = (StreamType)BitConverter.ToInt32(byteArray, 0);
                            pipedStream.Read(byteArray, 0, 4);
                            mediaData.DataType = (MediaDataType)BitConverter.ToInt32(byteArray, 0);
                            pipedStream.Read(byteArray, 0, 4);
                            mediaData.FrameType = (FrameDataType)BitConverter.ToInt32(byteArray, 0);

                            byte[] dataByteArray = new byte[mediaData.Size];
                            //读取管道中的流
                            pipedStream.Read(dataByteArray, 0, (int)mediaData.Size);
                            mediaData.Data = dataByteArray;

                            mediaDataSize = mediaData.Size;

                            //if (wCount < 1200)
                            //{
                            //    fs.Write(mediaData.Data, 0, (int)mediaData.Size);
                            //    wCount++;
                            //}

                            //回调函数
                            dataCallBack(cameraNo, mediaData, cameraNo.Substring(0, cameraNo.IndexOf("#")));
                        }
                    }
                    catch (Exception ex)
                    {
                        logEx.Error("VideoPipe.ReadData is error,ex={0}", ex.ToString());
                        if (pipedStream != null && !pipedStream.IsConnected)
                        {
                            VideoPipeManage.Instance().DeleteVideoPipe(cameraNo);
                            Stop();
                        }
                    }
                }
            }));
            th.IsBackground = true;
            th.Start();
        }
Ejemplo n.º 47
0
        /// <summary>
        /// 分发码流
        /// </summary>
        /// <param name="channelNo">通道号码</param>
        /// <param name="data">码流</param>
        public void SendMediaData(string channelLabel, MediaData data)
        {
            NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log);

            try
            {
                bool successed = this.channelDicLocker.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME);
                // 申请互斥
                if (successed)
                {
                    try
                    {
                        if (this.monitorChannelDic.ContainsKey(channelLabel))
                        {
                            this.monitorChannelDic[channelLabel].AddMediaData(data);
                        }
                    }
                    finally
                    {
                        // 释放互斥量
                        this.channelDicLocker.ExitReadLock();
                    }
                }
                else
                {
                    // 日志
                    logEx.Error("SendRtpData: Enert Write Lock Failed.WaitingReadCount:{0};WaitingWriteCount:{1}.", this.channelDicLocker.WaitingReadCount, this.channelDicLocker.WaitingWriteCount);
                }
            }
            catch (Exception ex)
            {
                // 日志
                logEx.Error(ex, "SendRtpData: Enert Write Lock Exception.");
            }
        }