コード例 #1
0
        private MemcachedClientApiConfiguration(
            IEnumerable <IPEndPoint> servers,
            ISocketPoolConfiguration socketPoolConfiguration,
            IMemcachedKeyTransformer keyTransformer,
            IMemcachedNodeLocator nodeLocator,
            Func <IMemcachedNodeLocator> nodeLocatorFactory,
            ITranscoder transcoder,
            IAuthenticationConfiguration authentication,
            MemcachedProtocol protocol,
            IPerformanceMonitor performanceMonitor)
        {
            Condition.Requires(socketPoolConfiguration, "socket pool configuration").IsNotNull();
            Condition.Requires(keyTransformer, "key transformer").IsNotNull();
            Condition.Requires(transcoder, "transcoder").IsNotNull();
            Condition.Requires(authentication, "authentication").IsNotNull();
            Condition.Requires(nodeLocator, "node locator")
            .Evaluate(!(nodeLocator == null && nodeLocatorFactory == null),
                      "Both node locator and node locator factory are not set. Requires only one to be set.");
            Condition.Requires(nodeLocator, "node locator")
            .Evaluate(!(nodeLocator == null && nodeLocatorFactory == null),
                      "Both node locator and node locator are set. Requires only one to be set.");
            Condition.Requires(servers, "servers").IsNotNull();

            _socketPoolConfiguration = socketPoolConfiguration;
            _keyTransformer          = keyTransformer;
            _nodeLocator             = nodeLocator;
            _nodeLocatorFactory      = nodeLocatorFactory;
            _transcoder        = transcoder;
            _authentication    = authentication;
            PerformanceMonitor = performanceMonitor;
            Protocol           = protocol;
            _servers           = servers.ToList();
        }
コード例 #2
0
        public ITranscoder TranscodeVideo(IMediaItem video, TranscodeType type, uint quality, bool isDirect, uint?width, uint?height, bool maintainAspect, uint offsetSeconds, uint lengthSeconds)
        {
            if (!this.Running)
            {
                logger.Error("TranscodeService is not running!");
                return(null);
            }

            logger.IfInfo("Asked to transcode video: " + video.FileName);
            lock (transcoders) {
                ITranscoder transcoder = null;;
                switch (type)
                {
                case TranscodeType.X264:
                    transcoder = new FFMpegX264Transcoder(video, quality, isDirect, width, height, maintainAspect, offsetSeconds, lengthSeconds);
                    break;

                case TranscodeType.MPEGTS:
                    transcoder = new FFMpegMpegtsTranscoder(video, quality, isDirect, width, height, maintainAspect, offsetSeconds, lengthSeconds);
                    break;
                }

                transcoder = StartTranscoder(transcoder);

                return(transcoder);
            }
        }
コード例 #3
0
ファイル: ImportFolderWatcher.cs プロジェクト: awlawl/Maestro
 public ImportFolderWatcher(IImportFolderInteractor folder, IMusicInfoReader musicInfoReader, ILibraryRepository library, ITranscoder transcoder )
 {
     _folderInteractor = folder;
     _musicInfoReader = musicInfoReader;
     _library = library;
     _transcoder = transcoder;
 }
コード例 #4
0
        public ServerPool(IMemcachedClientConfiguration configuration)
        {
            if (configuration == null)
                throw new ArgumentNullException("configuration", "Invalid or missing pool configuration. Check if the enyim.com/memcached section or your custom section presents in the app/web.config.");

            this.configuration = configuration;
            this.isAliveTimer = new Timer(callback_isAliveTimer, null, (int)this.configuration.SocketPool.DeadTimeout.TotalMilliseconds, (int)this.configuration.SocketPool.DeadTimeout.TotalMilliseconds);

            // create the key transformer instance
            Type t = this.configuration.KeyTransformer;
            this.keyTransformer = (t == null) ? new DefaultKeyTransformer() : (IMemcachedKeyTransformer)Enyim.Reflection.FastActivator.CreateInstance(t);

            // create the item transcoder instance
            t = this.configuration.Transcoder;
            this.transcoder = (t == null) ? new DefaultTranscoder() : (ITranscoder)Enyim.Reflection.FastActivator.CreateInstance(t);

            // initialize the server list

            foreach (IPEndPoint ip in configuration.Servers)
            {
                this.workingServers.Add(MemcachedNode.Factory.Get(ip, configuration));
            }

            // (re)creates the locator
            this.RebuildIndexes();
        }
コード例 #5
0
        private void Reset()
        {
            lock (queue) {
                if (user_job != null)
                {
                    user_job.CancelRequested -= OnCancelRequested;
                    user_job.Finished        -= OnFinished;
                    user_job.Finish();
                    user_job = null;
                }

                if (transcoder != null)
                {
                    transcoder.Finish();
                    transcoder = null;
                }

                foreach (TranscodeContext context in queue)
                {
                    context.CancelledHandler();
                }

                if (transcoding)
                {
                    current_context.CancelledHandler();
                    transcoding = false;
                }

                queue.Clear();
            }
        }
コード例 #6
0
 public ImportFolderWatcher(IImportFolderInteractor folder, IMusicInfoReader musicInfoReader, ILibraryRepository library, ITranscoder transcoder)
 {
     _folderInteractor = folder;
     _musicInfoReader  = musicInfoReader;
     _library          = library;
     _transcoder       = transcoder;
 }
コード例 #7
0
        public ServerPool(IMemcachedClientConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration", "Invalid or missing pool configuration. Check if the enyim.com/memcached section or your custom section presents in the app/web.config.");
            }

            this.configuration = configuration;
            this.isAliveTimer  = new Timer(callback_isAliveTimer, null, (int)this.configuration.SocketPool.DeadTimeout.TotalMilliseconds, (int)this.configuration.SocketPool.DeadTimeout.TotalMilliseconds);

            // create the key transformer instance
            Type t = this.configuration.KeyTransformer;

            this.keyTransformer = (t == null) ? new DefaultKeyTransformer() : (IMemcachedKeyTransformer)Activator.CreateInstance(t);

            // create the item transcoder instance
            t = this.configuration.Transcoder;
            this.transcoder = (t == null) ? new DefaultTranscoder() : (ITranscoder)Activator.CreateInstance(t);


            // initialize the server list
            ISocketPoolConfiguration ispc = configuration.SocketPool;

            foreach (IPEndPoint ip in configuration.Servers)
            {
                this.workingServers.Add(new MemcachedNode(ip, ispc));
            }

            // (re)creates the locator
            this.RebuildIndexes();
        }
コード例 #8
0
        private MemcachedClientApiConfiguration(
			IEnumerable<IPEndPoint> servers,
			ISocketPoolConfiguration socketPoolConfiguration,
			IMemcachedKeyTransformer keyTransformer, 
			IMemcachedNodeLocator nodeLocator, 
			Func<IMemcachedNodeLocator> nodeLocatorFactory, 
			ITranscoder transcoder, 
			IAuthenticationConfiguration authentication, 
			MemcachedProtocol protocol, 
			IPerformanceMonitor performanceMonitor)
        {
            Condition.Requires(socketPoolConfiguration, "socket pool configuration").IsNotNull();
            Condition.Requires(keyTransformer, "key transformer").IsNotNull();
            Condition.Requires(transcoder, "transcoder").IsNotNull();
            Condition.Requires(authentication, "authentication").IsNotNull();
            Condition.Requires(nodeLocator, "node locator")
                .Evaluate(!(nodeLocator == null && nodeLocatorFactory == null),
                "Both node locator and node locator factory are not set. Requires only one to be set.");
            Condition.Requires(nodeLocator, "node locator")
                .Evaluate(!(nodeLocator == null && nodeLocatorFactory == null),
                "Both node locator and node locator are set. Requires only one to be set.");
            Condition.Requires(servers, "servers").IsNotNull();

            _socketPoolConfiguration = socketPoolConfiguration;
            _keyTransformer = keyTransformer;
            _nodeLocator = nodeLocator;
            _nodeLocatorFactory = nodeLocatorFactory;
            _transcoder = transcoder;
            _authentication = authentication;
            PerformanceMonitor = performanceMonitor;
            Protocol = protocol;
            _servers = servers.ToList();
        }
コード例 #9
0
 public Upload(IPortalApplication portalApplication, IMcmRepository repository, IStorage storage, ITranscoder transcoder, LarmSettings settings) : base(portalApplication)
 {
     Repository = repository;
     Storage = storage;
     Transcoder = transcoder;
     Settings = settings;
 }
コード例 #10
0
 protected MemcachedClientBase(ICluster cluster, IOperationFactory opFactory, IKeyTransformer keyTransformer, ITranscoder transcoder)
 {
     this.cluster        = cluster;
     this.opFactory      = opFactory;
     this.keyTransformer = keyTransformer;
     this.transcoder     = transcoder;
 }
コード例 #11
0
        public static ITranscoder GetTranscoder(this TranscoderProfile profile)
        {
            // For now only support files in current assembly
            ITranscoder inst = (ITranscoder)Activator.CreateInstance(Type.GetType(profile.TranscoderImplementationClass));

            return(inst);
        }
コード例 #12
0
        public RetrieveResourceService(
            IInstanceStore instanceStore,
            IFileStore blobDataStore,
            ITranscoder transcoder,
            IFrameHandler frameHandler,
            IRetrieveTransferSyntaxHandler retrieveTransferSyntaxHandler,
            RecyclableMemoryStreamManager recyclableMemoryStreamManager,
            ILogger <RetrieveResourceService> logger)
        {
            EnsureArg.IsNotNull(instanceStore, nameof(instanceStore));
            EnsureArg.IsNotNull(blobDataStore, nameof(blobDataStore));
            EnsureArg.IsNotNull(transcoder, nameof(transcoder));
            EnsureArg.IsNotNull(frameHandler, nameof(frameHandler));
            EnsureArg.IsNotNull(retrieveTransferSyntaxHandler, nameof(retrieveTransferSyntaxHandler));
            EnsureArg.IsNotNull(recyclableMemoryStreamManager, nameof(recyclableMemoryStreamManager));
            EnsureArg.IsNotNull(logger, nameof(logger));

            _instanceStore = instanceStore;
            _blobDataStore = blobDataStore;
            _transcoder    = transcoder;
            _frameHandler  = frameHandler;
            _retrieveTransferSyntaxHandler = retrieveTransferSyntaxHandler;
            _recyclableMemoryStreamManager = recyclableMemoryStreamManager;
            _logger = logger;
        }
コード例 #13
0
        public ITranscoder TranscodeSong(IMediaItem song, TranscodeType type, uint quality, bool isDirect, uint offsetSeconds, uint lengthSeconds)
        {
            if (!this.Running)
            {
                logger.Error("TranscodeService is not running!");
                return(null);
            }

            logger.IfInfo("Asked to transcode song: " + song.FileName);
            lock (transcoders) {
                ITranscoder transcoder = null;
                switch (type)
                {
                case TranscodeType.MP3:
                    transcoder = new FFMpegMP3Transcoder(song, quality, isDirect, offsetSeconds, lengthSeconds);
                    break;

                case TranscodeType.OGG:
                    transcoder = new FFMpegOGGTranscoder(song, quality, isDirect, offsetSeconds, lengthSeconds);
                    break;

                case TranscodeType.OPUS:
                    transcoder = new FFMpegOpusTranscoder(song, quality, isDirect, offsetSeconds, lengthSeconds);
                    break;

                case TranscodeType.AAC:
                    transcoder = new FFMpegAACTranscoder(song, quality, isDirect, offsetSeconds, lengthSeconds);
                    break;
                }

                transcoder = StartTranscoder(transcoder);

                return(transcoder);
            }
        }
コード例 #14
0
        public RetrieveResourceService(
            IInstanceStore instanceStore,
            IFileStore blobDataStore,
            ITranscoder transcoder,
            IFrameHandler frameHandler,
            IRetrieveTransferSyntaxHandler retrieveTransferSyntaxHandler,
            IDicomRequestContextAccessor dicomRequestContextAccessor,
            ILogger <RetrieveResourceService> logger)
        {
            EnsureArg.IsNotNull(instanceStore, nameof(instanceStore));
            EnsureArg.IsNotNull(blobDataStore, nameof(blobDataStore));
            EnsureArg.IsNotNull(transcoder, nameof(transcoder));
            EnsureArg.IsNotNull(frameHandler, nameof(frameHandler));
            EnsureArg.IsNotNull(retrieveTransferSyntaxHandler, nameof(retrieveTransferSyntaxHandler));
            EnsureArg.IsNotNull(dicomRequestContextAccessor, nameof(dicomRequestContextAccessor));
            EnsureArg.IsNotNull(logger, nameof(logger));

            _instanceStore = instanceStore;
            _blobDataStore = blobDataStore;
            _transcoder    = transcoder;
            _frameHandler  = frameHandler;
            _retrieveTransferSyntaxHandler = retrieveTransferSyntaxHandler;
            _dicomRequestContextAccessor   = dicomRequestContextAccessor;
            _logger = logger;
        }
コード例 #15
0
        public static MemcachedClient CreateClient(ITranscoder transcoder)
        {
            var config = new MemcachedClientConfiguration() { Protocol = MemcachedProtocol.Binary, Transcoder = transcoder };
            config.Servers.Add(new System.Net.IPEndPoint(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }), 11211));

            return new MemcachedClient(config);
        }
コード例 #16
0
        public byte[] Encode(ITranscoder transcoder, bool canCompress, object value)
        {
            lock(this)
            {
                buffer.Clear();
                transcoder.Encode(buffer, value);

                byte[] bytes = buffer.ToArray();
                byte compress = 0;
                /*if (canCompress && bytes.Length > COMPRESSION_LEN)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (GZipStream gipStream = new GZipStream(ms, CompressionMode.Compress))
                        {
                            gipStream.Write(bytes, 0, bytes.Length);
                        }
                        bytes = ms.ToArray();
                        compress = 1;
                    }
                }*/

                buffer.Clear();

                buffer.WriteShort(MAGIC_NUMBER);
                buffer.WriteByte(compress);
                buffer.WriteInt(bytes.Length);
                buffer.WriteBytes(bytes);

                byte[] newBytes = buffer.ToArray();
                
                return newBytes;
            }
        }
コード例 #17
0
        public byte[] Encode(ITranscoder transcoder, bool canCompress, object value)
        {
            lock (this)
            {
                buffer.Clear();
                transcoder.Encode(buffer, value);

                byte[] bytes    = buffer.ToArray();
                byte   compress = 0;

                /*if (canCompress && bytes.Length > COMPRESSION_LEN)
                 * {
                 *  using (MemoryStream ms = new MemoryStream())
                 *  {
                 *      using (GZipStream gipStream = new GZipStream(ms, CompressionMode.Compress))
                 *      {
                 *          gipStream.Write(bytes, 0, bytes.Length);
                 *      }
                 *      bytes = ms.ToArray();
                 *      compress = 1;
                 *  }
                 * }*/

                buffer.Clear();

                buffer.WriteShort(MAGIC_NUMBER);
                buffer.WriteByte(compress);
                buffer.WriteInt(bytes.Length);
                buffer.WriteBytes(bytes);

                byte[] newBytes = buffer.ToArray();

                return(newBytes);
            }
        }
コード例 #18
0
        private ITranscoder StartTranscoder(ITranscoder inTranscoder)
        {
            ITranscoder transcoder = inTranscoder;

            if ((object)transcoder != null)
            {
                // Don't reuse direct transcoders
                if (!transcoder.IsDirect && transcoders.Contains(transcoder))
                {
                    logger.IfInfo("Using existing transcoder");

                    // Get the existing transcoder
                    int index = transcoders.IndexOf(transcoder);
                    transcoder = transcoders[index];

                    // Increment the reference count
                    transcoder.ReferenceCount++;
                }
                else
                {
                    logger.IfInfo("Creating a new transcoder");

                    // Add the transcoder to the array
                    transcoders.Add(transcoder);

                    // Increment the reference count
                    transcoder.ReferenceCount++;

                    // Start the transcode process
                    transcoder.StartTranscode();
                }
            }

            return(transcoder);
        }
コード例 #19
0
 /// <summary>
 /// Create a new <see cref="LocalFileSystem"/> with the specified options.
 /// </summary>
 /// <param name="options">The options to use.</param>
 /// <param name="provider">An extension provider to get content types from files extensions.</param>
 /// <param name="transcoder">The transcoder of local files.</param>
 public LocalFileSystem(IOptionsMonitor <BasicOptions> options,
                        IContentTypeProvider provider,
                        ITranscoder transcoder)
 {
     _options    = options;
     _provider   = provider;
     _transcoder = transcoder;
 }
コード例 #20
0
 public TasksProcessorActor(ITranscoder transcoder, IMetadataExtractor metadataExtractor)
 {
     _transcoder        = transcoder;
     _metadataExtractor = metadataExtractor;
     Task.Run(() => {
         ExecuteTasks();
     });
 }
コード例 #21
0
ファイル: CacheKey.cs プロジェクト: Hengle/ClientFrameWork
 public CacheKey(string flag, int version, int expireTime, bool canCompress, ITranscoder transcoder, string saveDiskPath)
 {
     this.flag         = flag;
     this.version      = version;
     this.expireTime   = expireTime;
     this.canCompress  = canCompress;
     this.transcoder   = transcoder;
     this.saveDiskPath = saveDiskPath;
 }
コード例 #22
0
 public TranscoderTests(ITestOutputHelper output)
 {
     _files      = new Mock <IFileSystem>();
     _transcoder = new KTranscoder(
         _files.Object,
         Options.Create(new BasicOptions()),
         output.BuildLoggerFor <KTranscoder>()
         );
 }
コード例 #23
0
        public TranscoderTests()
        {
            _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
            _transcoder = new Transcoder(_recyclableMemoryStreamManager, NullLogger <Transcoder> .Instance);

            new DicomSetupBuilder()
            .RegisterServices(s => s.AddTranscoderManager <NativeTranscoderManager>())
            .Build();
        }
コード例 #24
0
 public ServerManager(ILogger <ServerManager> logger, Grabber grabber, FFmpegAsProcess transcoder)
 {
     _grabber        = grabber;
     _transcoder     = transcoder;
     _logger         = logger;
     TranscoderCache = _transcoder.TranscoderCache;
     CheckTranscodingCache().Start();
     _logger.LogInformation($"{nameof(ServerManager)} initialized");
 }
コード例 #25
0
ファイル: EpisodeApi.cs プロジェクト: AnonymusRaccoon/Kyoo
 /// <summary>
 /// Create a new <see cref="EpisodeApi"/>.
 /// </summary>
 /// <param name="libraryManager">
 /// The library manager used to modify or retrieve information in the data store.
 /// </param>
 /// <param name="transcoder">The transcoder used to retrive fonts</param>
 /// <param name="files">The file manager used to send images.</param>
 /// <param name="thumbnails">The thumbnail manager used to retrieve images paths.</param>
 public EpisodeApi(ILibraryManager libraryManager,
                   ITranscoder transcoder,
                   IFileSystem files,
                   IThumbnailsManager thumbnails)
     : base(libraryManager.EpisodeRepository, files, thumbnails)
 {
     _libraryManager = libraryManager;
     _transcoder     = transcoder;
     _files          = files;
 }
コード例 #26
0
        public FrameHandler(
            ITranscoder transcoder,
            RecyclableMemoryStreamManager recyclableMemoryStreamManager)
        {
            EnsureArg.IsNotNull(transcoder, nameof(transcoder));
            EnsureArg.IsNotNull(recyclableMemoryStreamManager, nameof(recyclableMemoryStreamManager));

            _transcoder = transcoder;
            _recyclableMemoryStreamManager = recyclableMemoryStreamManager;
        }
コード例 #27
0
        /// <summary>
        /// Initializes a MemcahcedClient config with auto discovery enabled using the setup provided
        /// </summary>
        /// <param name="loggerFactory">The factory to provide ILogger instance to each class.</param>
        /// <param name="setup">The setup to get conifg settings from</param>
        public ElastiCacheClusterConfig(ILoggerFactory loggerFactory, ClusterConfigSettings setup)
        {
            if (setup == null)
            {
                throw new ArgumentNullException(nameof(setup));
            }
            if (setup.ClusterEndPoint == null)
            {
                throw new ArgumentException("Cluster Settings are null");
            }
            if (string.IsNullOrEmpty(setup.ClusterEndPoint.HostName))
            {
                throw new ArgumentException("Hostname is null");
            }
            if (setup.ClusterEndPoint.Port <= 0)
            {
                throw new ArgumentException("Port cannot be 0 or less");
            }

            _loggerFactory = loggerFactory;
            Setup          = setup;
            Servers        = new List <EndPoint>();

            Protocol = setup.Protocol;

            KeyTransformer = setup.KeyTransformer ?? new DefaultKeyTransformer();
            SocketPool     = setup.SocketPool ?? new SocketPoolConfiguration();
            Authentication = setup.Authentication ?? new AuthenticationConfiguration();

            NodeFactory  = setup.NodeFactory ?? new DefaultConfigNodeFactory();
            _nodeLocator = setup.NodeLocator ?? typeof(DefaultNodeLocator);

            if (setup.Transcoder != null)
            {
                _transcoder = setup.Transcoder ?? new DefaultTranscoder();
            }

            if (setup.ClusterEndPoint.HostName.IndexOf(".cfg", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                if (setup.ClusterNode != null)
                {
                    var tries = setup.ClusterNode.NodeTries > 0 ? setup.ClusterNode.NodeTries : DiscoveryNode.DefaultTryCount;
                    var delay = setup.ClusterNode.NodeDelay >= 0 ? setup.ClusterNode.NodeDelay : DiscoveryNode.DefaultTryDelay;
                    DiscoveryNode = new DiscoveryNode(this, setup.ClusterEndPoint.HostName, setup.ClusterEndPoint.Port, tries, delay);
                }
                else
                {
                    DiscoveryNode = new DiscoveryNode(this, setup.ClusterEndPoint.HostName, setup.ClusterEndPoint.Port);
                }
            }
            else
            {
                throw new ArgumentException("The provided endpoint does not support auto discovery");
            }
        }
コード例 #28
0
        public static MemcachedClient CreateClient(ITranscoder transcoder)
        {
            var config = new MemcachedClientConfiguration()
            {
                Protocol = MemcachedProtocol.Binary, Transcoder = transcoder
            };

            config.Servers.Add(new System.Net.IPEndPoint(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }), 11211));

            return(new MemcachedClient(config));
        }
コード例 #29
0
 public RetrieveResourceServiceTests()
 {
     _instanceStore                 = Substitute.For <IInstanceStore>();
     _fileStore                     = Substitute.For <IFileStore>();
     _retrieveTranscoder            = Substitute.For <ITranscoder>();
     _dicomFrameHandler             = Substitute.For <IFrameHandler>();
     _retrieveTransferSyntaxHandler = new RetrieveTransferSyntaxHandler(NullLogger <RetrieveTransferSyntaxHandler> .Instance);
     _logger = NullLogger <RetrieveResourceService> .Instance;
     _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
     _retrieveResourceService       = new RetrieveResourceService(
         _instanceStore, _fileStore, _retrieveTranscoder, _dicomFrameHandler, _retrieveTransferSyntaxHandler, _logger);
 }
コード例 #30
0
 public RetrieveResourceServiceTests(DataStoreTestsFixture blobStorageFixture, SqlDataStoreTestsFixture sqlIndexStorageFixture)
 {
     _indexDataStore                = sqlIndexStorageFixture.IndexDataStore;
     _instanceStore                 = sqlIndexStorageFixture.InstanceStore;
     _fileStore                     = blobStorageFixture.FileStore;
     _retrieveTranscoder            = Substitute.For <ITranscoder>();
     _frameHandler                  = Substitute.For <IFrameHandler>();
     _retrieveTransferSyntaxHandler = new RetrieveTransferSyntaxHandler(NullLogger <RetrieveTransferSyntaxHandler> .Instance);
     _recyclableMemoryStreamManager = blobStorageFixture.RecyclableMemoryStreamManager;
     _retrieveResourceService       = new RetrieveResourceService(
         _instanceStore, _fileStore, _retrieveTranscoder, _frameHandler, _retrieveTransferSyntaxHandler, blobStorageFixture.RecyclableMemoryStreamManager, NullLogger <RetrieveResourceService> .Instance);
 }
コード例 #31
0
        public object Decode(ITranscoder transcoder, byte[] bytes,bool isNativeFiile)
        {
            lock(this)
            {
                buffer.Clear();
                if (isNativeFiile)
                {
                    return null;
                }

                buffer.WriteBytes(bytes);

                if(buffer.ReadShort() != MAGIC_NUMBER)
                {
                    throw new ApplicationException("bytes have not used TranscoderManager encode.");
                }
                byte compress = buffer.ReadByte();
                int len = buffer.ReadInt();

                if(compress == 1)
                {
                    byte[] tempBytes = new byte[len];
                    buffer.ReadBytes(tempBytes, 0, len);
                    buffer.Clear();

                    using (MemoryStream ms = new MemoryStream(tempBytes))
                    {
                        ms.Flush();
                        using (GZipStream gipStream = new GZipStream(ms, CompressionMode.Decompress))
                        {
                            using (MemoryStream outBuffer = new MemoryStream())
                            {
                                byte[] block = new byte[1024];
                                while (true)
                                {
                                    int bytesRead = gipStream.Read(block, 0, block.Length);
                                    if (bytesRead <= 0)
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        outBuffer.Write(block, 0, bytesRead);
                                    }
                                }
                                buffer.WriteBytes(outBuffer.ToArray());
                            }
                        }
                    }
                }
                return transcoder.Decode(buffer);
            }
        }
コード例 #32
0
        public object Decode(ITranscoder transcoder, byte[] bytes, bool isNativeFiile)
        {
            lock (this)
            {
                buffer.Clear();
                if (isNativeFiile)
                {
                    return(null);
                }

                buffer.WriteBytes(bytes);

                if (buffer.ReadShort() != MAGIC_NUMBER)
                {
                    throw new ApplicationException("bytes have not used TranscoderManager encode.");
                }
                byte compress = buffer.ReadByte();
                int  len      = buffer.ReadInt();

                if (compress == 1)
                {
                    byte[] tempBytes = new byte[len];
                    buffer.ReadBytes(tempBytes, 0, len);
                    buffer.Clear();

                    using (MemoryStream ms = new MemoryStream(tempBytes))
                    {
                        ms.Flush();
                        using (GZipStream gipStream = new GZipStream(ms, CompressionMode.Decompress))
                        {
                            using (MemoryStream outBuffer = new MemoryStream())
                            {
                                byte[] block = new byte[1024];
                                while (true)
                                {
                                    int bytesRead = gipStream.Read(block, 0, block.Length);
                                    if (bytesRead <= 0)
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        outBuffer.Write(block, 0, bytesRead);
                                    }
                                }
                                buffer.WriteBytes(outBuffer.ToArray());
                            }
                        }
                    }
                }
                return(transcoder.Decode(buffer));
            }
        }
コード例 #33
0
		public MemcachedClient(IServerPool pool, IMemcachedKeyTransformer keyTransformer, ITranscoder transcoder, IPerformanceMonitor performanceMonitor)
		{
			if (pool == null) throw new ArgumentNullException("pool");
			if (keyTransformer == null) throw new ArgumentNullException("keyTransformer");
			if (transcoder == null) throw new ArgumentNullException("transcoder");

			this.performanceMonitor = performanceMonitor;
			this.keyTransformer = keyTransformer;
			this.transcoder = transcoder;

			this.pool = pool;
			this.StartPool();
		}
コード例 #34
0
 public RetrieveResourceServiceTests()
 {
     _instanceStore                 = Substitute.For <IInstanceStore>();
     _fileStore                     = Substitute.For <IFileStore>();
     _retrieveTranscoder            = Substitute.For <ITranscoder>();
     _dicomFrameHandler             = Substitute.For <IFrameHandler>();
     _retrieveTransferSyntaxHandler = new RetrieveTransferSyntaxHandler(NullLogger <RetrieveTransferSyntaxHandler> .Instance);
     _logger = NullLogger <RetrieveResourceService> .Instance;
     _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
     _dicomRequestContextAccessor   = Substitute.For <IDicomRequestContextAccessor>();
     _dicomRequestContextAccessor.RequestContext.DataPartitionEntry = new PartitionEntry(DefaultPartition.Key, DefaultPartition.Name);
     _retrieveResourceService = new RetrieveResourceService(
         _instanceStore, _fileStore, _retrieveTranscoder, _dicomFrameHandler, _retrieveTransferSyntaxHandler, _dicomRequestContextAccessor, _logger);
 }
コード例 #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:MemcachedClient"/> using the specified configuration instance.
        /// </summary>
        /// <param name="configuration">The memcachedClient configuration.</param>
        public MemcachedClient(IMemcachedClientConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.keyTransformer     = configuration.CreateKeyTransformer() ?? new DefaultKeyTransformer();
            this.transcoder         = configuration.CreateTranscoder() ?? new DefaultTranscoder();
            this.performanceMonitor = configuration.CreatePerformanceMonitor();

            this.pool = configuration.CreatePool();
            this.pool.Start();
        }
コード例 #36
0
ファイル: ServerPool.cs プロジェクト: vebin/Guanima.Redis
		public DefaultServerPool(IRedisClientConfiguration configuration)
		{
			if (configuration == null)
				throw new ArgumentNullException("configuration", "Invalid or missing pool configuration. Check if the Guanima/Redis section or your custom section presents in the app/web.config.");

			_configuration = configuration;
			_isAliveTimer = new Timer(callback_isAliveTimer, null, (int)_configuration.SocketPool.DeadTimeout.TotalMilliseconds, (int)this._configuration.SocketPool.DeadTimeout.TotalMilliseconds);

			// create the key transformer instance
			Type t = _configuration.KeyTransformer;
			_keyTransformer = (t == null) ? new DefaultKeyTransformer() : (IRedisKeyTransformer)FastActivator.CreateInstance(t);

			// create the item _transcoder instance
			t = _configuration.Transcoder;
			_transcoder = (t == null) ? new DefaultTranscoder() : (ITranscoder)FastActivator.CreateInstance(t);
		}
コード例 #37
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="MemCachedProvider" /> class.
        /// </summary>
        public MemCachedProvider(string ip, int host, ITranscoder transcoder)
        {
            /*Guard.IsConditional(() => host, host, (val) => val != 0);*/
            var config = new MemcachedClientConfiguration();

            config.AddServer(ip, host);
            config.Protocol = MemcachedProtocol.Text;

            config.SocketPool.ReceiveTimeout    = new TimeSpan(0, 0, 10);
            config.SocketPool.ConnectionTimeout = new TimeSpan(0, 0, 10);
            config.SocketPool.DeadTimeout       = new TimeSpan(0, 0, 20);

            config.Transcoder = transcoder;

            this.memcached = new MemcachedClient(config);
        }
コード例 #38
0
        // Token: 0x06001CB9 RID: 7353 RVA: 0x000A52D8 File Offset: 0x000A34D8
        private void OnCreateWorkerDelegate(IComWorker <ITranscoder> worker, object requestParameters)
        {
            ITranscoder worker2 = worker.Worker;

            if (worker2 == null)
            {
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerInitializationFailed, string.Empty, new object[]
                {
                    string.Empty
                });
                throw new TranscodingFatalFaultException("TranscodingTaskManager failed to get ITranscoder interface", null, this);
            }
            TranscodingInitOption initOption = default(TranscodingInitOption);

            initOption.MaxOutputSize         = this.maxOutputSize;
            initOption.RowNumberPerExcelPage = this.rowNumberInExcel;
            initOption.HtmlOutputFormat      = this.htmlFormat;
            initOption.IsImageMode           = this.isImageMode;
            TranscodeErrorCode transcodeErrorCode = TranscodeErrorCode.Succeeded;

            try
            {
                transcodeErrorCode = worker2.Initialize(initOption);
            }
            catch (NullReferenceException innerException)
            {
                throw new TranscodingFatalFaultException("Worker has been terminated by some reason", innerException, this);
            }
            catch (COMException ex)
            {
                ExTraceGlobals.TranscodingTracer.TraceDebug((long)this.GetHashCode(), "Work object initialize failed!");
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerInitializationFailed, string.Empty, new object[]
                {
                    ex.Message
                });
                throw new TranscodingFatalFaultException("TranscodingTaskManager call ITranscoder.Initialize() failed!", ex, this);
            }
            if (transcodeErrorCode != TranscodeErrorCode.Succeeded)
            {
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerInitializationFailed, string.Empty, new object[]
                {
                    string.Empty
                });
                throw new TranscodingFatalFaultException(string.Format("Initializalize Transcoding service failed with error code : {0}.", transcodeErrorCode), null, this);
            }
        }
コード例 #39
0
        public void ConsumedTranscode(ITranscoder transcoder)
        {
            logger.IfInfo("Waiting on " + transcoder.Item.FileName + " for 30 more seconds... State: " + transcoder.State);

            for (int i = 30; i > 0; i--)
            {
                Thread.Sleep(1000);
            }
            // Do nothing if the transcoder is null or is a stdout transcoder
            if ((object)transcoder == null)
            {
                return;
            }

            if (transcoder.IsDirect && transcoder.State == TranscodeState.Active)
            {
                try
                {
                    // Kill the running transcode
                    transcoder.TranscodeProcess.Kill();
                }
                catch{}
            }

            lock (transcoders)
            {
                logger.IfInfo("Consumed transcoder for " + transcoder.Item.FileName);

                // Decrement the reference count
                transcoder.ReferenceCount--;

                if (transcoder.ReferenceCount == 0)
                {
                    // No other clients need this file, remove it
                    transcoders.Remove(transcoder);

                    if (!transcoder.IsDirect)
                    {
                        // Remove the file
                        File.Delete(transcoder.OutputPath);
                    }
                }
            }
        }
コード例 #40
0
        public void CancelTranscode(ITranscoder transcoder)
        {
            // Do nothing if the transcoder is null or is a stdout transcoder
            if ((object)transcoder == null)
            {
                return;
            }

            lock (transcoders)
            {
                logger.IfInfo("Cancelling transcoder for " + transcoder.Item.FileName);

                if (transcoder.ReferenceCount == 1)
                {
                    // No one else is using this transcoder, so cancel it
                    transcoder.CancelTranscode();
                }

                // Consume the transcoder
                ConsumedTranscode(transcoder);
            }
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: neuecc/MemcachedTranscoder
        static void Bench(object data, ITranscoder transcoder, int repeat)
        {
            // warmup and copy
            var item = transcoder.Serialize(data);
            var ___ = transcoder.Deserialize(item);

            var comparer = System.Collections.StructuralComparisons.StructuralEqualityComparer;
            if (!comparer.Equals(data, ___)) throw new Exception("failed");

            var items = Enumerable.Range(0, repeat).Select(_ =>
            {
                return new CacheItem(item.Flags, new ArraySegment<byte>(item.Data.Array.ToArray(), item.Data.Offset, item.Data.Count));
            }).ToArray();

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            var sw = Stopwatch.StartNew();

            for (int i = 0; i < repeat; i++)
            {
                var _ = transcoder.Serialize(data);
            }

            sw.Stop();
            Console.WriteLine("S " + transcoder.GetType().Name + ":" + (int)sw.Elapsed.TotalMilliseconds);
            sw.Restart();

            foreach (var x in items)
            {
                var _ = transcoder.Deserialize(x);
            }

            sw.Stop();
            Console.WriteLine("D " + transcoder.GetType().Name + ":" + (int)sw.Elapsed.TotalMilliseconds);
            Console.WriteLine("Size:" + item.Data.Count);
        }
コード例 #42
0
 protected HTTPLiveTranscoderWrapper(ITranscoder toWrap)
 {
     obj = toWrap;
 }
コード例 #43
0
ファイル: CacheKey.cs プロジェクト: Blizzardx/ClientFrameWork
 public CacheKey(string flag, int version, int expireTime, bool canCompress, ITranscoder transcoder, string saveDiskPath)
 {
     this.flag = flag;
     this.version = version;
     this.expireTime = expireTime;
     this.canCompress = canCompress;
     this.transcoder = transcoder;
     this.saveDiskPath = saveDiskPath;
 }
コード例 #44
0
        private ITranscoder StartTranscoder(ITranscoder inTranscoder)
        {
            ITranscoder transcoder = inTranscoder;
            if ((object)transcoder != null)
            {
                // Don't reuse direct transcoders
                if (!transcoder.IsDirect && transcoders.Contains(transcoder))
                {
                    logger.IfInfo("Using existing transcoder");

                    // Get the existing transcoder
                    int index = transcoders.IndexOf(transcoder);
                    transcoder = transcoders[index];

                    // Increment the reference count
                    transcoder.ReferenceCount++;
                }
                else
                {
                    logger.IfInfo("Creating a new transcoder");

                    // Add the transcoder to the array
                    transcoders.Add(transcoder);

                    // Increment the reference count
                    transcoder.ReferenceCount++;

                    // Start the transcode process
                    transcoder.StartTranscode();
                }
            }

            return transcoder;
        }
コード例 #45
0
 /*
  * Transcoder delegate
  */
 public void TranscodeFinished(ITranscoder transcoder)
 {
     // Do something
     logger.IfInfo("Transcode finished for " + transcoder.Item.FileName);
 }
コード例 #46
0
        private void Reset ()
        {
            lock (queue) {
                if (user_job != null) {
                    user_job.CancelRequested -= OnCancelRequested;
                    user_job.Finished -= OnFinished;
                    user_job.Finish ();
                    user_job = null;
                }

                if (transcoder != null) {
                    transcoder.Finish ();
                    transcoder = null;
                }

                foreach (TranscodeContext context in queue) {
                    context.CancelledHandler ();
                }

                if (transcoding) {
                    current_context.CancelledHandler ();
                    transcoding = false;
                }

                queue.Clear ();
            }
        }