public IMedia Capture(IPlayoutServerChannel channel, TimeSpan tcIn, TimeSpan tcOut, bool narrowMode, string mediaName, string fileName)
        {
            _tcFormat = channel.VideoFormat;
            var directory = (ServerDirectory)_ownerServer.MediaDirectory;
            var newMedia  = new ServerMedia(directory, Guid.NewGuid(), 0, ArchiveDirectory)
            {
                FileName    = fileName,
                MediaName   = mediaName,
                TcStart     = tcIn,
                TcPlay      = tcIn,
                Duration    = tcOut - tcIn,
                MediaStatus = TMediaStatus.Copying,
                LastUpdated = DateTime.UtcNow,
                MediaType   = TMediaType.Movie
            };

            if (_recorder?.Capture(channel.Id, tcIn.ToSMPTETimecodeString(channel.VideoFormat), tcOut.ToSMPTETimecodeString(channel.VideoFormat), narrowMode, fileName) == true)
            {
                RecordingMedia = newMedia;
                Logger.Debug("Started recording from {0} file {1} TcIn {2} TcOut {3}", channel.ChannelName, fileName, tcIn, tcOut);
                return(newMedia);
            }
            Logger.Error("Unsuccessfull recording from {0} file {1} TcIn {2} TcOut {3}", channel.ChannelName, fileName, tcIn, tcOut);
            return(null);
        }
        private void _mediaPRIVerified(object o, MediaEventArgs e)
        {
            var sec = MediaDirectorySEC as ServerDirectory;
            var pri = MediaDirectoryPRI as ServerDirectory;

            if (sec != null && pri != null &&
                sec != pri &&
                sec.IsInitialized &&
                pri.IsInitialized)
            {
                ServerMedia sECMedia = sec.FindMediaFirst(sm => e.Media.FileSize == sm.FileSize &&
                                                          e.Media.FileName == sm.FileName && sm.FileExists()) as ServerMedia;
                if (e.Media.MediaStatus == TMediaStatus.Available)
                {
                    if (sECMedia == null)
                    {
                        FileManager.Queue(new FileOperation {
                            Kind = TFileOperationKind.Copy, SourceMedia = e.Media, DestDirectory = sec
                        }, false);
                    }
                    else
                    {
                        sECMedia.CloneMediaProperties(e.Media);
                        sECMedia.MediaGuid = e.Media.MediaGuid;
                        sECMedia.ReVerify();
                    }
                }
            }
        }
 private void _onServerDirectoryMediaSaved(object dir, MediaEventArgs e)
 {
     if (e.Media is ServerMedia priMedia &&
         priMedia.MediaStatus != TMediaStatus.Deleted)
     {
         ServerMedia compMedia = _findComplementaryMedia(priMedia);
         if (compMedia?.IsModified == true)
         {
             ThreadPool.QueueUserWorkItem(o => compMedia.Save());
         }
     }
 }
        private void _onServerDirectoryMediaSaved(object dir, MediaEventArgs e)
        {
            ServerMedia priMedia = e.Media as ServerMedia;

            if (priMedia != null && priMedia.MediaStatus != TMediaStatus.Deleted)
            {
                ServerMedia compMedia = _findComplementaryMedia(priMedia);
                if (compMedia != null)
                {
                    ThreadPool.QueueUserWorkItem((o) => compMedia.Save());
                }
            }
        }
        private ServerMedia _findComplementaryMedia(ServerMedia originalMedia)
        {
            var chPRI = (CasparServerChannel)_engine.PlayoutChannelPRI;
            var chSEC = (CasparServerChannel)_engine.PlayoutChannelSEC;

            if (chPRI != null && chSEC != null && chPRI.Owner != chSEC.Owner)
            {
                if ((originalMedia.Directory as ServerDirectory).Server == chPRI.Owner)
                {
                    return((ServerMedia)((MediaDirectory)chSEC.Owner.MediaDirectory).FindMediaByMediaGuid(originalMedia.MediaGuid));
                }
                if ((originalMedia.Directory as ServerDirectory).Server == chSEC.Owner)
                {
                    return((ServerMedia)((MediaDirectory)chPRI.Owner.MediaDirectory).FindMediaByMediaGuid(originalMedia.MediaGuid));
                }
            }
            return(null);
        }
        private void _serverMediaPropertyChanged(object dir, MediaPropertyChangedEventArgs e)
        {
            var adirPri = MediaDirectoryPRI;
            var adirSec = MediaDirectorySEC;

            if (e.Media is ServerMedia &&
                (adirPri != null && adirSec != null && adirPri != adirSec) &&
                !string.IsNullOrEmpty(e.PropertyName) &&
                (e.PropertyName == nameof(IServerMedia.DoNotArchive) ||
                 e.PropertyName == nameof(IServerMedia.IdAux) ||
                 e.PropertyName == nameof(IServerMedia.IdProgramme) ||
                 e.PropertyName == nameof(IServerMedia.KillDate) ||
                 e.PropertyName == nameof(IServerMedia.AudioVolume) ||
                 e.PropertyName == nameof(IServerMedia.MediaCategory) ||
                 e.PropertyName == nameof(IServerMedia.Parental) ||
                 e.PropertyName == nameof(IServerMedia.MediaEmphasis) ||
                 e.PropertyName == nameof(IServerMedia.FileName) ||
                 e.PropertyName == nameof(IServerMedia.MediaName) ||
                 e.PropertyName == nameof(IServerMedia.Duration) ||
                 e.PropertyName == nameof(IServerMedia.DurationPlay) ||
                 e.PropertyName == nameof(IServerMedia.TcStart) ||
                 e.PropertyName == nameof(IServerMedia.TcPlay) ||
                 e.PropertyName == nameof(IServerMedia.VideoFormat) ||
                 e.PropertyName == nameof(IServerMedia.AudioChannelMapping) ||
                 e.PropertyName == nameof(IServerMedia.AudioLevelIntegrated) ||
                 e.PropertyName == nameof(IServerMedia.AudioLevelPeak) ||
                 e.PropertyName == nameof(IServerMedia.IsArchived) ||
                 e.PropertyName == nameof(IServerMedia.Protected) ||
                 e.PropertyName == nameof(IServerMedia.FieldOrderInverted) ||
                 e.PropertyName == nameof(IServerMedia.MediaSegments)
                ))
            {
                ServerMedia compMedia = _findComplementaryMedia(e.Media as ServerMedia);
                if (compMedia != null)
                {
                    PropertyInfo pi = typeof(ServerMedia).GetProperty(e.PropertyName);
                    if (pi != null)
                    {
                        pi.SetValue(compMedia, pi.GetValue(e.Media, null), null);
                    }
                }
            }
        }
        public IMedia Capture(IPlayoutServerChannel channel, TimeSpan timeLimit, bool narrowMode, string fileName)
        {
            _tcFormat = channel.VideoFormat;
            var directory = (ServerDirectory)_ownerServer.MediaDirectory;
            var newMedia  = new ServerMedia(directory, Guid.NewGuid(), 0, ArchiveDirectory)
            {
                FileName = fileName, MediaName = fileName, TcStart = TimeSpan.Zero, TcPlay = TimeSpan.Zero, Duration = timeLimit, MediaStatus = TMediaStatus.Copying, LastUpdated = DateTime.UtcNow, MediaType = TMediaType.Movie
            };

            if (_recorder?.Capture(channel.Id, timeLimit.ToSMPTEFrames(channel.VideoFormat), narrowMode, fileName) == true)
            {
                RecordingMedia    = newMedia;
                CaptureFileName   = fileName;
                CaptureTcIn       = TimeSpan.Zero;
                CaptureTcOut      = TimeSpan.Zero;
                CaptureTimeLimit  = timeLimit;
                CaptureNarrowMode = narrowMode;
                return(newMedia);
            }
            return(null);
        }
        public void SynchronizeMediaSecToPri(bool deleteNotExisted)
        {
            var pri = MediaDirectoryPRI as ServerDirectory;
            var sec = MediaDirectorySEC as ServerDirectory;

            if (pri != null && sec != null &&
                pri != sec &&
                pri.IsInitialized &&
                sec.IsInitialized)
            {
                ThreadPool.QueueUserWorkItem(o =>
                {
                    lock (_lockSynchronizeMediaSecToPri)
                    {
                        if (!_isSynchronizedMediaSecToPri)
                        {
                            Debug.WriteLine(this, "SynchronizeMediaSecToPri started");
                            Logger.Debug("SynchronizeMediaSecToPri started");
                            try
                            {
                                var pRIMediaList = pri.GetFiles();
                                foreach (ServerMedia pRImedia in pRIMediaList)
                                {
                                    if (pRImedia.MediaStatus == TMediaStatus.Available && pRImedia.FileExists())
                                    {
                                        ServerMedia secMedia = (ServerMedia)sec.FindMediaByMediaGuid(pRImedia.MediaGuid);
                                        if (secMedia == null)
                                        {
                                            secMedia = (ServerMedia)sec.FindMediaFirst(m => m.FileExists() && m.FileSize == pRImedia.FileSize && m.FileName == pRImedia.FileName && m.LastUpdated.DateTimeEqualToDays(pRImedia.LastUpdated));
                                            if (secMedia != null)
                                            {
                                                secMedia.CloneMediaProperties(pRImedia);
                                                secMedia.MediaGuid = pRImedia.MediaGuid;
                                                secMedia.Verify();
                                            }
                                            else
                                            {
                                                _fileManager.Queue(new FileOperation()
                                                {
                                                    Kind = TFileOperationKind.Copy, SourceMedia = pRImedia, DestDirectory = sec
                                                });
                                            }
                                        }
                                    }
                                }
                                _isSynchronizedMediaSecToPri = true;
                            }
                            catch (Exception e)
                            {
                                Logger.Error(e, "SynchronizeMediaSecToPri exception");
                            }
                        }
                        if (deleteNotExisted)
                        {
                            try
                            {
                                var secMediaList = sec.GetFiles().ToList();
                                foreach (ServerMedia secMedia in secMediaList)
                                {
                                    if ((ServerMedia)pri.FindMediaByMediaGuid(secMedia.MediaGuid) == null)
                                    {
                                        _fileManager.Queue(new FileOperation()
                                        {
                                            Kind = TFileOperationKind.Delete, SourceMedia = secMedia
                                        });
                                    }
                                }
                                var duplicatesList = secMediaList.Where(m => secMediaList.FirstOrDefault(d => d.MediaGuid == m.MediaGuid && ((ServerMedia)d).IdPersistentMedia != ((ServerMedia)m).IdPersistentMedia) != null).Select(m => m.MediaGuid).Distinct();
                                foreach (var mediaGuid in duplicatesList)
                                {
                                    sec.FindMediaList(m => m.MediaGuid == mediaGuid)
                                    .Skip(1).ToList()
                                    .ForEach(m => m.Delete());
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.Error(e, "SynchronizeMediaSecToPri on deleteNotExisted exception");
                            }
                        }
                        Logger.Debug("SynchronizeMediaSecToPri finished");
                        Debug.WriteLine(this, "SynchronizeMediaSecToPri finished");
                    }
                });
            }
        }
        private void _onUpdatedTemplates(object o, EventArgs e)
        {
            var files = AnimationDirectory.Files;
            var templates = _casparDevice.Templates.All.ToList();
            foreach (Svt.Caspar.TemplateInfo template in templates)
            {
                ServerMedia media = (ServerMedia)files.FirstOrDefault(f => f is ServerMedia
                    && f.FileName == template.Name
                    && f.Folder == template.Folder);
                if (media == null)
                {
                    media = new ServerMedia()
                        {
                            MediaType = TMediaType.AnimationFlash,
                            MediaName = template.Name,
                            Folder = template.Folder,
                            FileName = template.Name,
                            FileSize = (UInt64)template.Size,
                            MediaStatus = TMediaStatus.Available,
                            LastUpdated = DateTimeExtensions.FromFileTime(template.LastUpdated.ToUniversalTime(), DateTimeKind.Utc),
                            MediaGuid = Guid.NewGuid(),
                            Directory = AnimationDirectory,

                        };
                    media.Save();
                }
                else // media != null
                {
                    if (media.FileSize != (UInt64)template.Size
                        || media.LastUpdated != DateTimeExtensions.FromFileTime(template.LastUpdated.ToUniversalTime(), DateTimeKind.Utc))
                    {
                        media.FileSize = (UInt64)template.Size;
                        media.LastUpdated = DateTimeExtensions.FromFileTime(template.LastUpdated.ToUniversalTime(), DateTimeKind.Utc);
                        media.Save();
                    }
                }
            }
            foreach (Media media in files)
            {
                Svt.Caspar.TemplateInfo i = templates.FirstOrDefault(t => media.FileName == t.Name && media.Folder == t.Folder);
                if (i == null)
                    AnimationDirectory.MediaRemove(media);
            }
        }
 internal static void ServerLoadMediaDirectory(AnimationDirectory directory, PlayoutServer server)
 {
     Debug.WriteLine(directory, "ServerLoadMediaDirectory animation started");
     if (Connect())
     {
         MySqlCommand cmd = new MySqlCommand("SELECT * FROM tas.serverMedia WHERE idServer=@idServer and typMedia = @typMedia", connection);
         cmd.Parameters.AddWithValue("@idServer", server.idServer);
         cmd.Parameters.AddWithValue("@typMedia", TMediaType.AnimationFlash);
         try
         {
             lock (connection)
             {
                 using (MySqlDataReader dataReader = cmd.ExecuteReader())
                 {
                     while (dataReader.Read())
                     {
                         ServerMedia nm = new ServerMedia()
                         {
                             idPersistentMedia = dataReader.GetUInt64("idServerMedia"),
                             Directory = directory,
                         };
                         _mediaReadFields(dataReader, nm);
                         if (nm.MediaStatus != TMediaStatus.Available)
                         {
                             nm.MediaStatus = TMediaStatus.Unknown;
                             ThreadPool.QueueUserWorkItem(o => nm.Verify());
                         }
                     }
                     dataReader.Close();
                 }
             }
             Debug.WriteLine(directory, "Directory loaded");
         }
         catch (Exception e)
         {
             Debug.WriteLine(directory, e.Message);
         }
     }
 }
 public abstract bool Load(ServerMedia media, VideoLayer videolayer, long seek, long duration);
 protected override Media CreateMedia()
 {
     ServerMedia newMedia = new ServerMedia()
     {
         Directory = this,
     };
     return newMedia;
 }
 public void ArchiveRestore(ArchiveMedia media, ServerMedia mediaPGM, bool toTop)
 {
     if (mediaPGM != null)
         _archiveCopy(media, mediaPGM, false, toTop);
 }
 private CasparItem _getItem(ServerMedia media, VideoLayer videolayer, long seek)
 {
     if (media != null)
     {
         CasparItem item = new CasparItem(string.Empty);
         if (media.MediaType == TMediaType.Movie || media.MediaType == TMediaType.Movie)
             item.Clipname = "\"" + Path.GetFileNameWithoutExtension(media.FileName) + "\"" +
                 ((media.MediaType == TMediaType.Movie && media.HasExtraLines) ? " FILTER CROP=720:576:0:32" : string.Empty) +
                 ((media.MediaType == TMediaType.Movie) ? " CHANNEL_LAYOUT STEREO" : string.Empty);
         item.VideoLayer = (int)videolayer;
         item.Seek = (int)seek;
         return item;
     }
     else
         return null;
 }
 public override bool Load(ServerMedia media, VideoLayer videolayer, long seek, long duration)
 {
     var channel = _casparChannel;
     if (_checkConnected()
         && media != null
         && channel != null)
     {
         CasparItem item = _getItem(media, videolayer, seek);
         if (item != null)
         {
             item.Length = (int)duration;
             channel.Load(item);
             Debug.WriteLine("CasparLoad media {0} Layer {1} Seek {2}", media, videolayer, seek);
             return true;
         }
     }
     return false;
 }