コード例 #1
0
 public BaseEncodingJobOptions()
 {
     EnableAutoStreamCopy = true;
     AllowVideoStreamCopy = true;
     AllowAudioStreamCopy = true;
     Context = EncodingContext.Streaming;
 }
コード例 #2
0
        public void Encode(int streamIdentifier, EncodingContext context)
        {
            if (streamIdentifier != 0)
            {
                throw new DecoderException(Http2ErrorCode.ProtocolError,
                                           "SETTINGS frame should not have a stream identifier. You specified: " + streamIdentifier);
            }

            if (IsAcknowledgment)
            {
                context.Buffer[context.Offset++] = 1;
                context.FreeBytesLeftInBuffer--;
                return;
            }

            context.Buffer[context.Offset++] = 0;
            foreach (var setting in _settings)
            {
                context.Buffer[context.Offset++] = (byte)setting.Key;
                context.Buffer[context.Offset++] = (byte)(setting.Key & 0xff);
                context.Buffer[context.Offset++] = (byte)(setting.Value);
                context.Buffer[context.Offset++] = (byte)(setting.Value & 0xff);
                context.Buffer[context.Offset++] = (byte)(setting.Value & 0xff00);
                context.Buffer[context.Offset++] = (byte)(setting.Value & 0xff0000);
            }
            context.FreeBytesLeftInBuffer -= 6 * _settings.Count;
        }
コード例 #3
0
        ValueTask IAsyncBinaryWriter.WriteAsync(ReadOnlyMemory <char> chars, EncodingContext context, LengthFormat?lengthFormat, CancellationToken token)
        {
            ValueTask result;

            if (token.IsCancellationRequested)
            {
#if NETSTANDARD2_1
                result = new (Task.FromCanceled(token));
#else
                result = ValueTask.FromCanceled(token);
#endif
            }
            else
            {
                result = new();
                try
                {
                    writer.WriteString(chars.Span, in context, lengthFormat: lengthFormat);
                }
                catch (Exception e)
                {
#if NETSTANDARD2_1
                    result = new (Task.FromException(e));
#else
                    result = ValueTask.FromException(e);
#endif
                }
            }

            return(result);
        }
コード例 #4
0
            protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
            {
                const int       maxChars        = 128; //it is empiric value measured using Console.WriteLine(builder.Length)
                EncodingContext encodingContext = DefaultHttpEncoding;

                using (var encodingBuffer = new ArrayRental <byte>(DefaultHttpEncoding.GetMaxByteCount(maxChars)))
                {
                    //write start boundary
                    await stream.WriteStringAsync(DoubleDash + boundary + CrLf, encodingContext, (byte[])encodingBuffer).ConfigureAwait(false);

                    encodingContext.Reset();
                    var builder = new StringBuilder(maxChars);
                    //write each nested content
                    var writeDivider = false;
                    foreach (var entry in entries)
                    {
                        await EncodeHeadersToStreamAsync(stream, builder, entry, writeDivider, boundary, encodingContext, (byte[])encodingBuffer).ConfigureAwait(false);

                        encodingContext.Reset();
                        Debug.Assert(builder.Length <= maxChars);
                        writeDivider = true;
                        await entry.CopyToAsync(stream).ConfigureAwait(false);
                    }
                    //write footer
                    await stream.WriteStringAsync(CrLf + DoubleDash + boundary + DoubleDash + CrLf, encodingContext, (byte[])encodingBuffer).ConfigureAwait(false);
                }
                encodingContext.Reset();
            }
コード例 #5
0
ファイル: DescriptorTests.cs プロジェクト: uruk-project/Jwt
        public void Descriptor_FullCapacity()
        {
            var payload = new JwtPayload();

            for (int i = 0; i < 256; i++)
            {
                payload.Add(i.ToString(), i);
            }

            var descriptor = new JweDescriptor(SymmetricJwk.GenerateKey(EncryptionAlgorithm.A128CbcHS256), KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = new JwsDescriptor(SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256), SignatureAlgorithm.HS256)
                {
                    Payload = payload
                }
            };

            for (int i = 0; i < 256; i++)
            {
                descriptor.Payload.TryGetClaim(i.ToString(), out var member);
                Assert.Equal(JwtValueKind.Int32, member.Type);
                Assert.Equal(i.ToString(), member.Name.ToString());
                Assert.Equal(i, (int)member.Value);
            }

            PooledByteBufferWriter writer = new PooledByteBufferWriter();
            var context = new EncodingContext(writer, null, 0, false);

            descriptor.Encode(context);
        }
コード例 #6
0
 /// <summary>
 /// Writes the string into the stream.
 /// </summary>
 /// <remarks>
 /// This method doesn't encode the length of the string.
 /// </remarks>
 /// <param name="stream">The stream to write into.</param>
 /// <param name="value">The string to be encoded.</param>
 /// <param name="context">The encoding.</param>
 /// <param name="buffer">The buffer allocated by the caller needed for characters encoding.</param>
 /// <exception cref="ArgumentException"><paramref name="buffer"/> is too small for encoding.</exception>
 public static void WriteString(this Stream stream, string value, EncodingContext context, byte[] buffer)
 {
     if (value.Length == 0)
     {
         return;
     }
     //TODO: Should be rewritten for .NET Standard 2.1
     if (context.Encoding.GetByteCount(value) <= buffer.Length)
     {
         stream.Write(buffer, 0, context.Encoding.GetBytes(value, 0, value.Length, buffer, 0));
     }
     else
     {
         var maxChars = buffer.Length / context.Encoding.GetMaxByteCount(1);
         if (maxChars == 0)
         {
             throw new ArgumentException(ExceptionMessages.BufferTooSmall, nameof(buffer));
         }
         var encoder = context.GetEncoder();
         for (int charStart = 0, numLeft = value.Length, charsRead; numLeft > 0; charStart += charsRead, numLeft -= charsRead)
         {
             charsRead = Math.Min(numLeft, maxChars);
             stream.Write(buffer, 0, encoder.GetBytes(value, charStart, charsRead, buffer, charsRead == numLeft));
         }
     }
 }
コード例 #7
0
 /// <summary>
 /// Writes the string into the stream asynchronously.
 /// </summary>
 /// <remarks>
 /// This method doesn't encode the length of the string.
 /// </remarks>
 /// <param name="stream">The stream to write into.</param>
 /// <param name="value">The string to be encoded.</param>
 /// <param name="context">The encoding context.</param>
 /// <param name="buffer">The buffer allocated by the caller needed for characters encoding.</param>
 /// <param name="token">The token that can be used to cancel the operation.</param>
 /// <returns>The task representing asynchronous state of the operation.</returns>
 /// <exception cref="ArgumentException"><paramref name="buffer"/> is too small for encoding.</exception>
 public static async Task WriteStringAsync(this Stream stream, string value, EncodingContext context, byte[] buffer, CancellationToken token = default)
 {
     if (value.Length == 0)
     {
         return;
     }
     //TODO: Should be rewritten for .NET Standard 2.1
     if (context.Encoding.GetByteCount(value) <= buffer.Length)
     {
         await stream.WriteAsync(buffer, 0, context.Encoding.GetBytes(value, 0, value.Length, buffer, 0), token).ConfigureAwait(false);
     }
     else
     {
         var maxChars = buffer.Length / context.Encoding.GetMaxByteCount(1);
         if (maxChars == 0)
         {
             throw new ArgumentException(ExceptionMessages.BufferTooSmall, nameof(buffer));
         }
         var encoder = context.GetEncoder();
         for (int charStart = 0, numLeft = value.Length, charsRead; numLeft > 0; charStart += charsRead, numLeft -= charsRead)
         {
             charsRead = Math.Min(numLeft, maxChars);
             await stream.WriteAsync(buffer, 0, encoder.GetBytes(value, charStart, charsRead, buffer, charsRead == numLeft), token).ConfigureAwait(false);
         }
     }
 }
コード例 #8
0
        /// <inheritsdoc />
        public override void Encode(EncodingContext context)
        {
            using var bufferWriter = new PooledByteBufferWriter();
            var ctx = new EncodingContext(bufferWriter, context);

            Payload.Encode(ctx);
            EncryptToken(bufferWriter.WrittenSpan, context);
        }
コード例 #9
0
        public static void EncodeAsString(BufferWriter <byte> writer, Encoding encoding)
        {
            var encodingContext = new EncodingContext(encoding, true);

            using (writer)
            {
                var g   = Guid.NewGuid();
                var bi  = new BigInteger(RandomBytes(64));
                var dt  = DateTime.Now;
                var dto = DateTimeOffset.Now;
                writer.WriteInt64(42L, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteUInt64(12UL, LengthFormat.PlainLittleEndian, in encodingContext, provider: InvariantCulture);
                writer.WriteInt32(34, LengthFormat.PlainBigEndian, in encodingContext, provider: InvariantCulture);
                writer.WriteUInt32(78, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteInt16(90, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteUInt16(12, LengthFormat.Plain, in encodingContext, format: "X", provider: InvariantCulture);
                writer.WriteUInt16(12, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteByte(10, LengthFormat.Plain, in encodingContext, format: "X", provider: InvariantCulture);
                writer.WriteSByte(11, LengthFormat.Plain, in encodingContext, format: "X", provider: InvariantCulture);
                writer.WriteByte(10, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteSByte(11, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteGuid(g, LengthFormat.Plain, in encodingContext);
                writer.WriteGuid(g, LengthFormat.Plain, in encodingContext, format: "X");
                writer.WriteDateTime(dt, LengthFormat.Plain, in encodingContext, format: "O", provider: InvariantCulture);
                writer.WriteDateTimeOffset(dto, LengthFormat.Plain, in encodingContext, format: "O", provider: InvariantCulture);
                writer.WriteDateTime(dt, LengthFormat.Plain, in encodingContext, format: "O", provider: InvariantCulture);
                writer.WriteDateTimeOffset(dto, LengthFormat.Plain, in encodingContext, format: "O", provider: InvariantCulture);
                writer.WriteDecimal(42.5M, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteSingle(32.2F, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteDouble(56.6D, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);
                writer.WriteBigInteger(bi, LengthFormat.Plain, in encodingContext, provider: InvariantCulture);

                var decodingContext = new DecodingContext(encoding, true);
                var reader          = IAsyncBinaryReader.Create(writer.WrittenMemory);
                Equal(42L, reader.ReadInt64(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal(12UL, reader.ReadUInt64(LengthFormat.PlainLittleEndian, in decodingContext, provider: InvariantCulture));
                Equal(34, reader.ReadInt32(LengthFormat.PlainBigEndian, in decodingContext, provider: InvariantCulture));
                Equal(78U, reader.ReadUInt32(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal(90, reader.ReadInt16(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal("C", reader.ReadString(LengthFormat.Plain, in decodingContext));
                Equal(12, reader.ReadUInt16(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal("A", reader.ReadString(LengthFormat.Plain, in decodingContext));
                Equal("B", reader.ReadString(LengthFormat.Plain, in decodingContext));
                Equal(10, reader.ReadByte(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal(11, reader.ReadSByte(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal(g, reader.ReadGuid(LengthFormat.Plain, in decodingContext));
                Equal(g, reader.ReadGuid(LengthFormat.Plain, in decodingContext, "X"));
                Equal(dt, reader.ReadDateTime(LengthFormat.Plain, in decodingContext, style: DateTimeStyles.RoundtripKind, provider: InvariantCulture));
                Equal(dto, reader.ReadDateTimeOffset(LengthFormat.Plain, in decodingContext, style: DateTimeStyles.RoundtripKind, provider: InvariantCulture));
                Equal(dt, reader.ReadDateTime(LengthFormat.Plain, in decodingContext, formats: new[] { "O" }, style: DateTimeStyles.RoundtripKind, provider: InvariantCulture));
                Equal(dto, reader.ReadDateTimeOffset(LengthFormat.Plain, in decodingContext, formats: new[] { "O" }, style: DateTimeStyles.RoundtripKind, provider: InvariantCulture));
                Equal(42.5M, reader.ReadDecimal(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal(32.2F, reader.ReadSingle(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal(56.6D, reader.ReadDouble(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
                Equal(bi, reader.ReadBigInteger(LengthFormat.Plain, in decodingContext, provider: InvariantCulture));
            }
        }
コード例 #10
0
        static void Main(string[] args)

        {
            MMDevice dev = MMDeviceEnumerator.DefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);

            capture        = new WasapiLoopbackCapture();
            capture.Device = dev;
            capture.Initialize();

            SoundInSource soundInSource = new SoundInSource(capture);

            nStream = new SingleBlockNotificationStream(soundInSource.ToSampleSource());
            final   = nStream.ToWaveSource();
            nStream.SingleBlockRead     += NStream_SingleBlockRead;
            soundInSource.DataAvailable += encode;
            trashBuf = new byte[final.WaveFormat.BytesPerSecond / 2];

            Console.WriteLine($"sample rate:{capture.WaveFormat.SampleRate}");
            Console.WriteLine($"bits per sample:{capture.WaveFormat.BitsPerSample }");
            Console.WriteLine($"channels:{capture.WaveFormat.Channels }");
            Console.WriteLine($"bytes per sample:{capture.WaveFormat.BytesPerSample }");
            Console.WriteLine($"bytes per second:{capture.WaveFormat.BytesPerSecond }");
            Console.WriteLine($"AudioEncoding:{capture.WaveFormat.WaveFormatTag  }");


            EncodingContext context = FrameEncoder.GetDefaultsContext();

            context.Channels        = 6;
            context.SampleRate      = capture.WaveFormat.SampleRate;
            context.AudioCodingMode = AudioCodingMode.Front3Rear2;
            context.HasLfe          = true;
            context.SampleFormat    = A52SampleFormat.Float;
            enc = new FrameEncoderFloat(ref context);

            //_writer = new WaveWriter("test.ac3", final.WaveFormat);


            capture.Start();

            wBuffSrc = new WriteableBufferingSource(new WaveFormat(capture.WaveFormat.SampleRate, capture.WaveFormat.BitsPerSample, capture.WaveFormat.Channels, AudioEncoding.WAVE_FORMAT_DOLBY_AC3_SPDIF), (int)capture.WaveFormat.MillisecondsToBytes(20));

            w = new WasapiOut2(false, AudioClientShareMode.Shared, 20);

            w.Device = MMDeviceEnumerator.EnumerateDevices(DataFlow.Render, DeviceState.Active).Where(x => x.FriendlyName.Contains("Digital")).Single();
            AudioClient a = AudioClient.FromMMDevice(w.Device);

            w.Initialize(wBuffSrc);
            w.Play();


            Task.Run(async() => await encoderThread());
            //encodeSinus();

            Console.ReadLine();

            System.Environment.Exit(0);
        }
コード例 #11
0
        public IEnumerable<EncodingInstruction> ExecuteEncode(EncodingContext context)
        {
            object newValue = context.Value;
            if (_action != null)
                newValue = _action(context.Value);

            if (newValue != context.Value)
            {
                context.Value = newValue;
                yield return new ContextInvalidated();
            }
        }
コード例 #12
0
        public async Task SerializeToBinaryFormMemoryStream()
        {
            await using var output = new MemoryStream(1024);
            var writer = IAsyncBinaryWriter.Create(output, buffer);
            await writer.WriteInt32Async(data.Count, true);

            var context = new EncodingContext(Encoding.UTF8, true);

            foreach (var(key, value) in data)
            {
                await writer.WriteAsync(key.AsMemory(), context, LengthFormat.Plain);

                await writer.WriteAsync(value.AsMemory(), context, LengthFormat.Plain);
            }
        }
コード例 #13
0
        public async Task ActAsServerAsync(Socket clientSocket)
        {
            var channel = new SocketChannel();

            channel.Assign(clientSocket);

            _encodingContext = new EncodingContext(channel);
            _decodingContext = new DecodingContext(_channel);
            _encoder         = new FrameEncoder(_encodingContext);
            _decoder         = new FrameDecoder();
            await channel.ReceiveAsync(_decodingContext.Buffer, _decodingContext.Offset, _decodingContext.Capacity);

            if (_decodingContext.BytesLeftToProcess < ClientPreface.Length)
            {
                //TODO: Invalid protocol
            }

            // ReSharper disable once LoopCanBeConvertedToQuery
            for (var i = 0; i < ClientPreface.Length; i++)
            {
                if (ClientPreface[i] != _decodingContext.Buffer[_decodingContext.Offset + i])
                {
                    throw new Http2Exception(Http2ErrorCode.ProtocolError, "ClientPreface was not valid.");
                }
            }
            _decodingContext.Offset             += ClientPreface.Length;
            _decodingContext.BytesLeftToProcess -= ClientPreface.Length;

            // didn't get the settings frame directly
            if (_decodingContext.BytesLeftToProcess == 0)
            {
                await _decodingContext.ReceiveMoreAsync();
            }

            var frame = await _decoder.DecodeAsync(_decodingContext) as SettingsFrame;

            if (frame == null)
            {
                throw new Http2Exception(Http2ErrorCode.ProtocolError, "Expected SETTINGS frame after client preface.");
            }

            //ack on client frame
            await _encoder.EncodeAsync(new SettingsFrame { IsAcknowledgment = true });

            // our own settings.
            await _encoder.EncodeAsync(new SettingsFrame());
        }
コード例 #14
0
        public void EncodeEmpty()
        {
            var descriptor = new JwsDescriptor(Jwk.None, SignatureAlgorithm.None);

            using (var bufferWriter = new PooledByteBufferWriter())
            {
                var context = new EncodingContext(bufferWriter, new LruJwtHeaderCache(), 60, true);
                descriptor.Encode(context);

                var result = Jwt.TryParse(bufferWriter.WrittenSpan, TokenValidationPolicy.NoValidation, out var jwt);
                Assert.True(result);
                Assert.NotNull(jwt);
                Assert.True(jwt.Payload.ContainsClaim("exp"));
                Assert.True(jwt.Payload.ContainsClaim("iat"));
                jwt.Dispose();
            }
        }
コード例 #15
0
        public async Task SerializeToBinaryFormFileStream()
        {
            await using var output = new FileStream(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()), FileMode.CreateNew, FileAccess.Write, FileShare.None, 1024, FileOptions.SequentialScan | FileOptions.Asynchronous | FileOptions.DeleteOnClose);
            var writer = IAsyncBinaryWriter.Create(output, buffer);
            await writer.WriteInt32Async(data.Count, true);

            var context = new EncodingContext(Encoding.UTF8, true);

            foreach (var(key, value) in data)
            {
                await writer.WriteAsync(key.AsMemory(), context, LengthFormat.Plain);

                await writer.WriteAsync(value.AsMemory(), context, LengthFormat.Plain);
            }

            await output.FlushAsync();
        }
コード例 #16
0
        public void Encode()
        {
            var descriptor = new JwsDescriptor();
            var context    = new EncodingContext(new JsonHeaderCache(), 60, true);

            using (var bufferWriter = new PooledByteBufferWriter())
            {
                descriptor.Encode(context, bufferWriter);

                var reader = new JwtReader();
                var result = reader.TryReadToken(bufferWriter.WrittenSpan, TokenValidationPolicy.NoValidation);
                Assert.True(result.Succedeed);
                Assert.NotNull(result.Token);
                Assert.True(result.Token.ExpirationTime.HasValue);
                Assert.True(result.Token.IssuedAt.HasValue);
            }
        }
コード例 #17
0
        public IEnumerable<EncodingInstruction> ExecuteEncode(EncodingContext context)
        {
            if (_mapping.UsesReferencing)
            {
                if (context.Process.References.HasReferenceTo(context.Value))
                {
                    double reference = context.Process.References.GetReferenceTo(context.Value);
                    context.Output += JsonToken.Parse(reference);

                    yield break;
                }
                else
                {
                    context.Process.References.Reference(context.Value);
                }
            }

            context.Output += JsonToken.BeginObject;

            Dictionary<string, JsonFieldMappingBase>.Enumerator fields = _mapping.FieldMappings.GetEnumerator();
            for (int index = 0; fields.MoveNext(); index++ )
            {
                JsonFieldMappingBase fieldMapping = fields.Current.Value;

                if (index > 0)
                {
                    context.Output += JsonToken.ValueSeperator;
                }

                object value = fieldMapping.Get(context.Value);

                context.Output += JsonToken.Parse(fieldMapping.JsonField, JsonTokenType.String);
                context.Output += JsonToken.NameSeperator;

                DoEncode instruction = new DoEncode(fieldMapping.Encode(value), fieldMapping.DesiredType);
                yield return instruction;

                context.Output += instruction.Output;
            }

            context.Output += JsonToken.EndObject;
        }
コード例 #18
0
ファイル: ListNode.cs プロジェクト: nick121212/xima_desktop3
        public IEnumerable<EncodingInstruction> ExecuteEncode(EncodingContext context)
        {
            IList list = (IList)context.Value;
            bool parallel = false;

            // See if this list would benefit from parallel processing
            if (context.Process.IsParallel && _genericArgument != null && !context.Process.RequiresReferencing && TypeHelper.IsParallelBeneficial(_genericArgument))
            {
                foreach (object el in list)
                {
                    // Do parallel
                    yield return new DoParallelEncode(el, _genericArgument);
                }

                parallel = true;
            }

            context.Output += JsonToken.BeginArray;

            for (int index = 0; index < list.Count; index++)
            {
                object element = list[index];

                if (index > 0)
                {
                    context.Output += JsonToken.ValueSeperator;
                }
                else if (parallel)
                {
                    // Wait untill all parallel tasks are finished.
                    yield return new SyncParallelEncode();
                }

                DoEncode instruction = new DoEncode(element, _genericArgument);
                yield return instruction;

                context.Output += instruction.Output;

            }

            context.Output += JsonToken.EndArray;
        }
コード例 #19
0
        public async Task ConnectAsync(Uri uri)
        {
            if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                _channel = new SecureSocketChannel();
                await _channel.ConnectAsync(uri.Host, uri.Port == 0? 443 : uri.Port);
            }
            else
            {
                _channel = new SocketChannel();
                await _channel.ConnectAsync(uri.Host, uri.Port == 0? 443 : uri.Port);
            }

            _encodingContext = new EncodingContext(_channel);
            _encoder         = new FrameEncoder(_encodingContext);

            Buffer.BlockCopy(ClientPreface, 0, _encodingContext.Buffer, _encodingContext.Offset, ClientPreface.Length);
            _encodingContext.Offset += ClientPreface.Length;
            var settingsFrame = new SettingsFrame();
            await _encoder.EncodeAsync(settingsFrame);

            if (_encodingContext.ContainsData)
            {
                await _encodingContext.SendAsync();
            }

            var ackOnOurFrame = await _decoder.DecodeAsync(_decodingContext) as SettingsFrame;

            if (ackOnOurFrame == null)
            {
                //TODO: Protocol error
            }

            var serverSettings = await _decoder.DecodeAsync(_decodingContext) as SettingsFrame;

            if (serverSettings == null)
            {
                //TODO: protocol error
            }
        }
コード例 #20
0
ファイル: Http2Client.cs プロジェクト: jgauffin/http2
        public async Task ConnectAsync(Uri uri)
        {
            int port = uri.Port;

            if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                _socket = new SecureSocketChannel();
                if (port == 0)
                {
                    port = uri.Port == 0 ? 443 : uri.Port;
                }
            }
            else
            {
                _socket = new SocketChannel();
                if (port == 0)
                {
                    port = uri.Port == 0 ? 80 : uri.Port;
                }
            }


            await _socket.ConnectAsync(uri.Host, port);

            _context = new EncodingContext(_socket);
            _encoder = new FrameEncoder(_context);


            var http2Settings = new SettingsFrame();

            http2Settings.Encode(1, new EncodingContext());

            var handshake = string.Format(@"GET / HTTP/1.1
Host: {0}
Connection: Upgrade, HTTP2-Settings
Upgrade: h2c
HTTP2-Settings: {1}
     ", uri.Host, http2Settings);
        }
コード例 #21
0
        ValueTask IAsyncBinaryWriter.WriteAsync(ReadOnlyMemory <char> chars, EncodingContext context, LengthFormat?lengthFormat, CancellationToken token)
        {
            Task result;

            if (token.IsCancellationRequested)
            {
                result = Task.FromCanceled(token);
            }
            else
            {
                result = Task.CompletedTask;
                try
                {
                    writer.WriteString(chars.Span, in context, lengthFormat: lengthFormat);
                }
                catch (Exception e)
                {
                    result = Task.FromException(e);
                }
            }

            return(new ValueTask(result));
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: uruk-project/Jwt
        private static ReadOnlyMemory <byte> CreateJws()
        {
            var descriptor = new JweDescriptor(encryptionKey1, KeyManagementAlgorithm.A128KW, EncryptionAlgorithm.A128CbcHS256)
            {
                Payload = new JwsDescriptor(signingKey1, SignatureAlgorithm.HS256)
                {
                    Payload = new JwtPayload
                    {
                        { JwtClaimNames.Iat, 1500000000L },
                        { JwtClaimNames.Exp, 2000000000L },
                        { JwtClaimNames.Iss, "https://idp.example.com/" },
                        { JwtClaimNames.Aud, "636C69656E745F6964" },
                        { JwtClaimNames.Sub, "*****@*****.**" },
                        { JwtClaimNames.Jti, "12345667890" }
                    }
                }
            };

            var bufferWriter = new System.Buffers.ArrayBufferWriter <byte>();
            var context      = new EncodingContext(bufferWriter, null, 0, false);

            descriptor.Encode(context);
            return(bufferWriter.WrittenMemory);
        }
コード例 #23
0
        public static SubtitleProfile GetSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, EncodingContext context, PlayMethod playMethod)
        {
            if (playMethod != PlayMethod.Transcode)
            {
                // Look for supported embedded subs
                foreach (SubtitleProfile profile in subtitleProfiles)
                {
                    if (!profile.SupportsLanguage(subtitleStream.Language))
                    {
                        continue;
                    }

                    if (profile.Method != SubtitleDeliveryMethod.Embed)
                    {
                        continue;
                    }

                    if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && StringHelper.EqualsIgnoreCase(profile.Format, subtitleStream.Codec))
                    {
                        return(profile);
                    }
                }
            }

            // Look for an external profile that matches the stream type (text/graphical)
            foreach (SubtitleProfile profile in subtitleProfiles)
            {
                bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format);

                if (!profile.SupportsLanguage(subtitleStream.Language))
                {
                    continue;
                }

                if (profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format))
                {
                    if (!requiresConversion)
                    {
                        return(profile);
                    }

                    if (subtitleStream.SupportsExternalStream)
                    {
                        return(profile);
                    }

                    // For sync we can handle the longer extraction times
                    if (context == EncodingContext.Static && subtitleStream.IsTextSubtitleStream)
                    {
                        return(profile);
                    }
                }
            }

            return(new SubtitleProfile
            {
                Method = SubtitleDeliveryMethod.Encode,
                Format = subtitleStream.Codec
            });
        }
コード例 #24
0
ファイル: DictNode.cs プロジェクト: nick121212/xima_desktop3
        public IEnumerable<EncodingInstruction> ExecuteEncode(EncodingContext context)
        {
            #if NET40
            IDictionary<string, object> expando = null;
            IDictionary dict = null;
            #else
            IDictionary dict = (IDictionary)context.Value;
            #endif

            #if NET40
            if(_dictType == typeof(ExpandoObject))
            {
                expando = (IDictionary<string, object>)context.Value;
            }
            else
            {
                dict = (IDictionary)context.Value;
            }
            #endif
            
            bool parallel = false;

            // See if this list would benefit from parallel processing
            if (context.Process.IsParallel && _genericArgument != null && !context.Process.RequiresReferencing && TypeHelper.IsParallelBeneficial(_genericArgument))
            {
                #if NET40
                foreach (object el in (dict != null ? (ICollection)dict.Values : (ICollection)expando.Values))
                #else
                foreach (object el in dict.Values)
                #endif
                {
                    // Do parallel
                    yield return new DoParallelEncode(el, _genericArgument);
                }

                parallel = true;
            }

            context.Output += JsonToken.BeginObject;

            object key;
            object value;

            #if NET40
            IEnumerator enumerator = dict != null ? dict.GetEnumerator() : (IEnumerator)expando.GetEnumerator();
            #else
            IDictionaryEnumerator enumerator = dict.GetEnumerator();
            #endif
            for (int index = 0; enumerator.MoveNext(); index++)
            {
                #if NET40
                if (expando != null)
                {
                    KeyValuePair<string, object> pair = (KeyValuePair<string, object>)enumerator.Current;
                    key = pair.Key;
                    value = pair.Value;
                }
                else
                {
                    DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
                    key = entry.Key;
                    value = entry.Value;
                }
                #else
                key = enumerator.Key;
                value = enumerator.Value;
                #endif

                if (index > 0)
                {
                    context.Output += JsonToken.ValueSeperator;
                }
                else if (parallel)
                {
                    // Wait untill all parallel tasks are finished.
                    yield return new SyncParallelEncode();
                }

                context.Output += JsonToken.Parse(key, JsonTokenType.String);
                context.Output += JsonToken.NameSeperator;

                DoEncode instruction = new DoEncode(value, _genericArgument);
                yield return instruction;

                context.Output += instruction.Output;
            }

            context.Output += JsonToken.EndObject;
        }
コード例 #25
0
ファイル: DescriptorTests.cs プロジェクト: uruk-project/Jwt
        public void Descriptor_AllKindOfObject()
        {
            var descriptor = new JweDescriptor(SymmetricJwk.GenerateKey(256), KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = new JwsDescriptor(SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256), SignatureAlgorithm.HS256)
                {
                    Header = new JwtHeader
                    {
                        { "H1", "value1" },
                        { "H2", new Dictionary <string, object> {
                              { "prop1", "value2" }
                          } },
                        { "H3", 123L },
                        { "H4", new Fake {
                              Inner = new Fake {
                                  Value = "Inner1", Inner = new Fake {
                                      Value = "Inner2"
                                  }
                              }, Value = "Inner0"
                          } },
                        { "H5", new [] { "a", "b", "c" } },
                        { "H6", new [] { new object(), new object(), "abc", 123 } },
                        { "H7", true },
                        { "H8", false },
                    },
                    Payload = new JwtPayload
                    {
                        { "P1", "value1" },
                        { "P2", new Dictionary <string, object> {
                              { "prop1", "value2" }
                          } },
                        { "P3", 123L },
                        { "P4", new Fake {
                              Inner = new Fake {
                                  Value = "Inner1", Inner = new Fake {
                                      Value = "Inner2"
                                  }
                              }, Value = "Inner0"
                          } },
                        { "P5", new [] { "a", "b", "c" } },
                        { "P6", new [] { new object(), new object(), "abc", 123 } },
                        { "P7", true },
                        { "P8", false },
                    }
                }
            };

            Assert.True(descriptor.Payload.TryGetClaim("P1", out var claim));
            Assert.Equal(JwtValueKind.String, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P2", out claim));
            Assert.Equal(JwtValueKind.Object, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P3", out claim));
            Assert.Equal(JwtValueKind.Int64, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P4", out claim));
            Assert.Equal(JwtValueKind.Object, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P5", out claim));
            Assert.Equal(JwtValueKind.Array, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P6", out claim));
            Assert.Equal(JwtValueKind.Array, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P7", out claim));
            Assert.Equal(JwtValueKind.True, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P8", out claim));
            Assert.Equal(JwtValueKind.False, claim.Type);

            Assert.True(descriptor.Payload.Header.TryGetValue("alg", out var jwsHeaderParameter));
            Assert.Equal(JwtValueKind.JsonEncodedString, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("kid", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.JsonEncodedString, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H1", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.String, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H2", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Object, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H3", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Int64, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H4", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Object, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H5", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Array, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H6", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Array, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H7", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.True, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H8", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.False, jwsHeaderParameter.Type);

            Assert.True(descriptor.Header.TryGetValue("kid", out var jweHeaderParameter));
            Assert.True(descriptor.Header.TryGetValue("alg", out jweHeaderParameter));
            Assert.Equal(KeyManagementAlgorithm.Dir.Name, ((JsonEncodedText)jweHeaderParameter.Value));
            Assert.True(descriptor.Header.TryGetValue("enc", out jweHeaderParameter));
            Assert.Equal(EncryptionAlgorithm.A128CbcHS256.Name, ((JsonEncodedText)jweHeaderParameter.Value));
            Assert.True(descriptor.Header.TryGetValue("zip", out jweHeaderParameter));
            Assert.Equal(CompressionAlgorithm.Def.Name, (JsonEncodedText)jweHeaderParameter.Value);

            PooledByteBufferWriter writer = new PooledByteBufferWriter();
            var context = new EncodingContext(writer, null, 0, false);

            descriptor.Encode(context);
        }
コード例 #26
0
        public static async Task WriteReadPrimitivesAsync(IAsyncBinaryReaderWriterSource source, bool littleEndian, Encoding encoding)
        {
            await using (source)
            {
                const byte    value8   = 254;
                const short   value16  = 42;
                const int     value32  = int.MaxValue;
                const long    value64  = long.MaxValue;
                const decimal valueM   = 42M;
                const float   valueF   = 56.6F;
                const double  valueD   = 67.7D;
                var           valueG   = Guid.NewGuid();
                var           valueDT  = DateTime.Now;
                var           valueDTO = DateTimeOffset.Now;
                var           valueT   = TimeSpan.FromMilliseconds(1024);

                var writer = source.CreateWriter();
                await writer.WriteInt16Async(value16, littleEndian);

                await writer.WriteInt32Async(value32, littleEndian);

                await writer.WriteInt64Async(value64, littleEndian);

                await writer.WriteAsync(valueM);

                var encodingContext = new EncodingContext(encoding, true);
                await writer.WriteByteAsync(value8, StringLengthEncoding.Plain, encodingContext, provider : InvariantCulture);

                await writer.WriteInt16Async(value16, StringLengthEncoding.Compressed, encodingContext, provider : InvariantCulture);

                await writer.WriteInt32Async(value32, StringLengthEncoding.Plain, encodingContext, provider : InvariantCulture);

                await writer.WriteInt64Async(value64, StringLengthEncoding.PlainBigEndian, encodingContext, provider : InvariantCulture);

                await writer.WriteDecimalAsync(valueM, StringLengthEncoding.PlainLittleEndian, encodingContext, provider : InvariantCulture);

                await writer.WriteSingleAsync(valueF, StringLengthEncoding.Plain, encodingContext, provider : InvariantCulture);

                await writer.WriteDoubleAsync(valueD, StringLengthEncoding.Plain, encodingContext, provider : InvariantCulture);

                await writer.WriteGuidAsync(valueG, StringLengthEncoding.Plain, encodingContext);

                await writer.WriteGuidAsync(valueG, StringLengthEncoding.Plain, encodingContext, "X");

                await writer.WriteDateTimeAsync(valueDT, StringLengthEncoding.Plain, encodingContext, format : "O", provider : InvariantCulture);

                await writer.WriteDateTimeOffsetAsync(valueDTO, StringLengthEncoding.Plain, encodingContext, format : "O", provider : InvariantCulture);

                await writer.WriteDateTimeAsync(valueDT, StringLengthEncoding.Plain, encodingContext, format : "O", provider : InvariantCulture);

                await writer.WriteDateTimeOffsetAsync(valueDTO, StringLengthEncoding.Plain, encodingContext, format : "O", provider : InvariantCulture);

                await writer.WriteTimeSpanAsync(valueT, StringLengthEncoding.Plain, encodingContext);

                await writer.WriteTimeSpanAsync(valueT, StringLengthEncoding.Plain, encodingContext, "G", InvariantCulture);

                var reader = source.CreateReader();
                Equal(value16, await reader.ReadInt16Async(littleEndian));
                Equal(value32, await reader.ReadInt32Async(littleEndian));
                Equal(value64, await reader.ReadInt64Async(littleEndian));
                Equal(valueM, await reader.ReadAsync <decimal>());
                var decodingContext = new DecodingContext(encoding, true);
                Equal(value8, await reader.ReadByteAsync(StringLengthEncoding.Plain, decodingContext, provider: InvariantCulture));
                Equal(value16, await reader.ReadInt16Async(StringLengthEncoding.Compressed, decodingContext, provider: InvariantCulture));
                Equal(value32, await reader.ReadInt32Async(StringLengthEncoding.Plain, decodingContext, provider: InvariantCulture));
                Equal(value64, await reader.ReadInt64Async(StringLengthEncoding.PlainBigEndian, decodingContext, provider: InvariantCulture));
                Equal(valueM, await reader.ReadDecimalAsync(StringLengthEncoding.PlainLittleEndian, decodingContext, provider: InvariantCulture));
                Equal(valueF, await reader.ReadSingleAsync(StringLengthEncoding.Plain, decodingContext, provider: InvariantCulture));
                Equal(valueD, await reader.ReadDoubleAsync(StringLengthEncoding.Plain, decodingContext, provider: InvariantCulture));
                Equal(valueG, await reader.ReadGuidAsync(StringLengthEncoding.Plain, decodingContext));
                Equal(valueG, await reader.ReadGuidAsync(StringLengthEncoding.Plain, decodingContext, "X"));
                Equal(valueDT, await reader.ReadDateTimeAsync(StringLengthEncoding.Plain, decodingContext, style: DateTimeStyles.RoundtripKind, provider: InvariantCulture));
                Equal(valueDTO, await reader.ReadDateTimeOffsetAsync(StringLengthEncoding.Plain, decodingContext, style: DateTimeStyles.RoundtripKind, provider: InvariantCulture));
                Equal(valueDT, await reader.ReadDateTimeAsync(StringLengthEncoding.Plain, decodingContext, new[] { "O" }, style: DateTimeStyles.RoundtripKind, provider: InvariantCulture));
                Equal(valueDTO, await reader.ReadDateTimeOffsetAsync(StringLengthEncoding.Plain, decodingContext, new[] { "O" }, style: DateTimeStyles.RoundtripKind, provider: InvariantCulture));
                Equal(valueT, await reader.ReadTimeSpanAsync(StringLengthEncoding.Plain, decodingContext, InvariantCulture));
                Equal(valueT, await reader.ReadTimeSpanAsync(StringLengthEncoding.Plain, decodingContext, new[] { "G" }, TimeSpanStyles.None, InvariantCulture));
            }
        }
コード例 #27
0
 ValueTask IAsyncBinaryWriter.WriteAsync(ReadOnlyMemory <char> chars, EncodingContext context, StringLengthEncoding?lengthFormat, CancellationToken token)
 => writer.WriteAsync(chars, context, lengthFormat, token);
コード例 #28
0
 private static Task EncodeHeadersToStreamAsync(Stream output, StringBuilder builder, TEntry entry, bool writeDivider, string boundary, EncodingContext context, byte[] buffer)
 {
     builder.Clear();
     if (writeDivider)
     {
         builder.Append(CrLf + DoubleDash).Append(boundary).Append(CrLf);
     }
     //write headers
     WriteHeader(builder, RequestVoteMessage.RecordTermHeader, entry.Term.ToString(InvariantCulture));
     WriteHeader(builder, HeaderNames.LastModified, HeaderUtils.FormatDate(entry.Timestamp));
     // Extra CRLF to end headers (even if there are no headers)
     builder.Append(CrLf);
     return(output.WriteStringAsync(builder.ToString(), context, buffer));
 }
コード例 #29
0
ファイル: ValueNode.cs プロジェクト: erpframework/fluent-json
 public IEnumerable<EncodingInstruction> ExecuteEncode(EncodingContext context)
 {
     context.Output += JsonToken.Parse(context.Value);
     yield break;
 }
コード例 #30
0
ファイル: StreamBuilder.cs プロジェクト: jrags56/MediaBrowser
        public static SubtitleProfile GetSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, EncodingContext context)
        {
            // Look for an external profile that matches the stream type (text/graphical)
            foreach (SubtitleProfile profile in subtitleProfiles)
            {
                bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format);

                if (!profile.SupportsLanguage(subtitleStream.Language))
                {
                    continue;
                }

                if (profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format))
                {
                    if (!requiresConversion)
                    {
                        return profile;
                    }

                    if (subtitleStream.SupportsExternalStream)
                    {
                        return profile;
                    }

                    // For sync we can handle the longer extraction times
                    if (context == EncodingContext.Static && subtitleStream.IsTextSubtitleStream)
                    {
                        return profile;
                    }
                }
            }

            foreach (SubtitleProfile profile in subtitleProfiles)
            {
                bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format);

                if (!profile.SupportsLanguage(subtitleStream.Language))
                {
                    continue;
                }

                if (profile.Method == SubtitleDeliveryMethod.Embed && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format))
                {
                    if (!requiresConversion)
                    {
                        return profile;
                    }

                    return profile;
                }
            }

            return new SubtitleProfile
            {
                Method = SubtitleDeliveryMethod.Encode,
                Format = subtitleStream.Codec
            };
        }
コード例 #31
0
        public static SubtitleProfile GetSubtitleProfile(MediaStream subtitleStream, DeviceProfile deviceProfile, EncodingContext context)
        {
            // Look for an external profile that matches the stream type (text/graphical)
            foreach (SubtitleProfile profile in deviceProfile.SubtitleProfiles)
            {
                if (profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format))
                {
                    if (subtitleStream.SupportsExternalStream)
                    {
                        return(profile);
                    }

                    // For sync we can handle the longer extraction times
                    if (context == EncodingContext.Static && subtitleStream.IsTextSubtitleStream)
                    {
                        return(profile);
                    }
                }
            }

            foreach (SubtitleProfile profile in deviceProfile.SubtitleProfiles)
            {
                if (profile.Method == SubtitleDeliveryMethod.Embed && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format))
                {
                    return(profile);
                }
            }

            return(new SubtitleProfile
            {
                Method = SubtitleDeliveryMethod.Encode,
                Format = subtitleStream.Codec
            });
        }
コード例 #32
0
        public async Task <ActionResult> GetVideoStream(
            [FromRoute, Required] Guid itemId,
            [FromQuery] string?container,
            [FromQuery] bool? @static,
            [FromQuery] string? @params,
            [FromQuery] string?tag,
            [FromQuery] string?deviceProfileId,
            [FromQuery] string?playSessionId,
            [FromQuery] string?segmentContainer,
            [FromQuery] int?segmentLength,
            [FromQuery] int?minSegments,
            [FromQuery] string?mediaSourceId,
            [FromQuery] string?deviceId,
            [FromQuery] string?audioCodec,
            [FromQuery] bool?enableAutoStreamCopy,
            [FromQuery] bool?allowVideoStreamCopy,
            [FromQuery] bool?allowAudioStreamCopy,
            [FromQuery] bool?breakOnNonKeyFrames,
            [FromQuery] int?audioSampleRate,
            [FromQuery] int?maxAudioBitDepth,
            [FromQuery] int?audioBitRate,
            [FromQuery] int?audioChannels,
            [FromQuery] int?maxAudioChannels,
            [FromQuery] string?profile,
            [FromQuery] string?level,
            [FromQuery] float?framerate,
            [FromQuery] float?maxFramerate,
            [FromQuery] bool?copyTimestamps,
            [FromQuery] long?startTimeTicks,
            [FromQuery] int?width,
            [FromQuery] int?height,
            [FromQuery] int?videoBitRate,
            [FromQuery] int?subtitleStreamIndex,
            [FromQuery] SubtitleDeliveryMethod subtitleMethod,
            [FromQuery] int?maxRefFrames,
            [FromQuery] int?maxVideoBitDepth,
            [FromQuery] bool?requireAvc,
            [FromQuery] bool?deInterlace,
            [FromQuery] bool?requireNonAnamorphic,
            [FromQuery] int?transcodingMaxAudioChannels,
            [FromQuery] int?cpuCoreLimit,
            [FromQuery] string?liveStreamId,
            [FromQuery] bool?enableMpegtsM2TsMode,
            [FromQuery] string?videoCodec,
            [FromQuery] string?subtitleCodec,
            [FromQuery] string?transcodeReasons,
            [FromQuery] int?audioStreamIndex,
            [FromQuery] int?videoStreamIndex,
            [FromQuery] EncodingContext context,
            [FromQuery] Dictionary <string, string> streamOptions)
        {
            var isHeadRequest           = Request.Method == System.Net.WebRequestMethods.Http.Head;
            var cancellationTokenSource = new CancellationTokenSource();
            var streamingRequest        = new VideoRequestDto
            {
                Id                          = itemId,
                Container                   = container,
                Static                      = @static ?? true,
                Params                      = @params,
                Tag                         = tag,
                DeviceProfileId             = deviceProfileId,
                PlaySessionId               = playSessionId,
                SegmentContainer            = segmentContainer,
                SegmentLength               = segmentLength,
                MinSegments                 = minSegments,
                MediaSourceId               = mediaSourceId,
                DeviceId                    = deviceId,
                AudioCodec                  = audioCodec,
                EnableAutoStreamCopy        = enableAutoStreamCopy ?? true,
                AllowAudioStreamCopy        = allowAudioStreamCopy ?? true,
                AllowVideoStreamCopy        = allowVideoStreamCopy ?? true,
                BreakOnNonKeyFrames         = breakOnNonKeyFrames ?? false,
                AudioSampleRate             = audioSampleRate,
                MaxAudioChannels            = maxAudioChannels,
                AudioBitRate                = audioBitRate,
                MaxAudioBitDepth            = maxAudioBitDepth,
                AudioChannels               = audioChannels,
                Profile                     = profile,
                Level                       = level,
                Framerate                   = framerate,
                MaxFramerate                = maxFramerate,
                CopyTimestamps              = copyTimestamps ?? true,
                StartTimeTicks              = startTimeTicks,
                Width                       = width,
                Height                      = height,
                VideoBitRate                = videoBitRate,
                SubtitleStreamIndex         = subtitleStreamIndex,
                SubtitleMethod              = subtitleMethod,
                MaxRefFrames                = maxRefFrames,
                MaxVideoBitDepth            = maxVideoBitDepth,
                RequireAvc                  = requireAvc ?? true,
                DeInterlace                 = deInterlace ?? true,
                RequireNonAnamorphic        = requireNonAnamorphic ?? true,
                TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
                CpuCoreLimit                = cpuCoreLimit,
                LiveStreamId                = liveStreamId,
                EnableMpegtsM2TsMode        = enableMpegtsM2TsMode ?? true,
                VideoCodec                  = videoCodec,
                SubtitleCodec               = subtitleCodec,
                TranscodeReasons            = transcodeReasons,
                AudioStreamIndex            = audioStreamIndex,
                VideoStreamIndex            = videoStreamIndex,
                Context                     = context,
                StreamOptions               = streamOptions
            };

            using var state = await StreamingHelpers.GetStreamingState(
                      streamingRequest,
                      Request,
                      _authContext,
                      _mediaSourceManager,
                      _userManager,
                      _libraryManager,
                      _serverConfigurationManager,
                      _mediaEncoder,
                      _fileSystem,
                      _subtitleEncoder,
                      _configuration,
                      _dlnaManager,
                      _deviceManager,
                      _transcodingJobHelper,
                      _transcodingJobType,
                      cancellationTokenSource.Token)
                              .ConfigureAwait(false);

            if (@static.HasValue && @static.Value && state.DirectStreamProvider != null)
            {
                StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, startTimeTicks, Request, _dlnaManager);

                await new ProgressiveFileCopier(state.DirectStreamProvider, null, _transcodingJobHelper, CancellationToken.None)
                {
                    AllowEndOfFile = false
                }.WriteToAsync(Response.Body, CancellationToken.None)
                .ConfigureAwait(false);

                // TODO (moved from MediaBrowser.Api): Don't hardcode contentType
                return(File(Response.Body, MimeTypes.GetMimeType("file.ts") !));
            }

            // Static remote stream
            if (@static.HasValue && @static.Value && state.InputProtocol == MediaProtocol.Http)
            {
                StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, startTimeTicks, Request, _dlnaManager);

                var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
                return(await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, isHeadRequest, httpClient, HttpContext).ConfigureAwait(false));
            }

            if (@static.HasValue && @static.Value && state.InputProtocol != MediaProtocol.File)
            {
                return(BadRequest($"Input protocol {state.InputProtocol} cannot be streamed statically"));
            }

            var outputPath       = state.OutputFilePath;
            var outputPathExists = System.IO.File.Exists(outputPath);

            var transcodingJob    = _transcodingJobHelper.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
            var isTranscodeCached = outputPathExists && transcodingJob != null;

            StreamingHelpers.AddDlnaHeaders(state, Response.Headers, (@static.HasValue && @static.Value) || isTranscodeCached, startTimeTicks, Request, _dlnaManager);

            // Static stream
            if (@static.HasValue && @static.Value)
            {
                var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath);

                if (state.MediaSource.IsInfiniteStream)
                {
                    await new ProgressiveFileCopier(state.MediaPath, null, _transcodingJobHelper, CancellationToken.None)
                    {
                        AllowEndOfFile = false
                    }.WriteToAsync(Response.Body, CancellationToken.None)
                    .ConfigureAwait(false);

                    return(File(Response.Body, contentType));
                }

                return(FileStreamResponseHelpers.GetStaticFileResult(
                           state.MediaPath,
                           contentType,
                           isHeadRequest,
                           HttpContext));
            }

            // Need to start ffmpeg (because media can't be returned directly)
            var encodingOptions            = _serverConfigurationManager.GetEncodingOptions();
            var encodingHelper             = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration);
            var ffmpegCommandLineArguments = encodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, outputPath, "superfast");

            return(await FileStreamResponseHelpers.GetTranscodedFile(
                       state,
                       isHeadRequest,
                       HttpContext,
                       _transcodingJobHelper,
                       ffmpegCommandLineArguments,
                       _transcodingJobType,
                       cancellationTokenSource).ConfigureAwait(false));
        }
コード例 #33
0
        /// <summary>
        /// Encodes the string to bytes and write them to pipe asynchronously.
        /// </summary>
        /// <param name="writer">The pipe writer.</param>
        /// <param name="value">The block of characters to encode.</param>
        /// <param name="context">The text encoding context.</param>
        /// <param name="bufferSize">The buffer size (in bytes) used for encoding.</param>
        /// <param name="lengthFormat">String length encoding format; or <see langword="null"/> to prevent encoding of string length.</param>
        /// <param name="token">The token that can be used to cancel operation.</param>
        /// <returns>The result of operation.</returns>
        /// <exception cref="OperationCanceledException">The operation has been canceled.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="lengthFormat"/> is invalid.</exception>
        /// <exception cref="EndOfStreamException">Pipe closed unexpectedly.</exception>
        public static async ValueTask WriteStringAsync(this PipeWriter writer, ReadOnlyMemory <char> value, EncodingContext context, int bufferSize = 0, LengthFormat?lengthFormat = null, CancellationToken token = default)
        {
            var result = await writer.WriteLengthAsync(value, context.Encoding, lengthFormat, token).ConfigureAwait(false);

            result.ThrowIfCancellationRequested(token);
            if (value.IsEmpty)
            {
                return;
            }
            var encoder = context.GetEncoder();

            for (int charsLeft = value.Length, charsUsed, maxChars, bytesPerChar = context.Encoding.GetMaxByteCount(1); charsLeft > 0; value = value.Slice(charsUsed), charsLeft -= charsUsed)
            {
                if (result.IsCompleted)
                {
                    throw new EndOfStreamException();
                }
                var buffer = writer.GetMemory(bufferSize);
                maxChars  = buffer.Length / bytesPerChar;
                charsUsed = Math.Min(maxChars, charsLeft);
                encoder.Convert(value.Span.Slice(0, charsUsed), buffer.Span, charsUsed == charsLeft, out charsUsed, out var bytesUsed, out _);
                writer.Advance(bytesUsed);
                result = await writer.FlushAsync(token).ConfigureAwait(false);

                result.ThrowIfCancellationRequested(token);
            }
        }
コード例 #34
0
 public static ValueTask <FlushResult> WriteSByteAsync(this PipeWriter writer, sbyte value, LengthFormat lengthFormat, EncodingContext context, string?format = null, IFormatProvider?provider = null, CancellationToken token = default)
 {
     writer.WriteSByte(value, lengthFormat, in context, format, provider);
     return(writer.FlushAsync(token));
 }
コード例 #35
0
 public Task <ActionResult> GetVideoStreamByContainer(
     [FromRoute, Required] Guid itemId,
     [FromRoute, Required] string container,
     [FromQuery] bool? @static,
     [FromQuery] string? @params,
     [FromQuery] string?tag,
     [FromQuery] string?deviceProfileId,
     [FromQuery] string?playSessionId,
     [FromQuery] string?segmentContainer,
     [FromQuery] int?segmentLength,
     [FromQuery] int?minSegments,
     [FromQuery] string?mediaSourceId,
     [FromQuery] string?deviceId,
     [FromQuery] string?audioCodec,
     [FromQuery] bool?enableAutoStreamCopy,
     [FromQuery] bool?allowVideoStreamCopy,
     [FromQuery] bool?allowAudioStreamCopy,
     [FromQuery] bool?breakOnNonKeyFrames,
     [FromQuery] int?audioSampleRate,
     [FromQuery] int?maxAudioBitDepth,
     [FromQuery] int?audioBitRate,
     [FromQuery] int?audioChannels,
     [FromQuery] int?maxAudioChannels,
     [FromQuery] string?profile,
     [FromQuery] string?level,
     [FromQuery] float?framerate,
     [FromQuery] float?maxFramerate,
     [FromQuery] bool?copyTimestamps,
     [FromQuery] long?startTimeTicks,
     [FromQuery] int?width,
     [FromQuery] int?height,
     [FromQuery] int?videoBitRate,
     [FromQuery] int?subtitleStreamIndex,
     [FromQuery] SubtitleDeliveryMethod subtitleMethod,
     [FromQuery] int?maxRefFrames,
     [FromQuery] int?maxVideoBitDepth,
     [FromQuery] bool?requireAvc,
     [FromQuery] bool?deInterlace,
     [FromQuery] bool?requireNonAnamorphic,
     [FromQuery] int?transcodingMaxAudioChannels,
     [FromQuery] int?cpuCoreLimit,
     [FromQuery] string?liveStreamId,
     [FromQuery] bool?enableMpegtsM2TsMode,
     [FromQuery] string?videoCodec,
     [FromQuery] string?subtitleCodec,
     [FromQuery] string?transcodeReasons,
     [FromQuery] int?audioStreamIndex,
     [FromQuery] int?videoStreamIndex,
     [FromQuery] EncodingContext context,
     [FromQuery] Dictionary <string, string> streamOptions)
 {
     return(GetVideoStream(
                itemId,
                container,
                @static,
                @params,
                tag,
                deviceProfileId,
                playSessionId,
                segmentContainer,
                segmentLength,
                minSegments,
                mediaSourceId,
                deviceId,
                audioCodec,
                enableAutoStreamCopy,
                allowVideoStreamCopy,
                allowAudioStreamCopy,
                breakOnNonKeyFrames,
                audioSampleRate,
                maxAudioBitDepth,
                audioBitRate,
                audioChannels,
                maxAudioChannels,
                profile,
                level,
                framerate,
                maxFramerate,
                copyTimestamps,
                startTimeTicks,
                width,
                height,
                videoBitRate,
                subtitleStreamIndex,
                subtitleMethod,
                maxRefFrames,
                maxVideoBitDepth,
                requireAvc,
                deInterlace,
                requireNonAnamorphic,
                transcodingMaxAudioChannels,
                cpuCoreLimit,
                liveStreamId,
                enableMpegtsM2TsMode,
                videoCodec,
                subtitleCodec,
                transcodeReasons,
                audioStreamIndex,
                videoStreamIndex,
                context,
                streamOptions));
 }
コード例 #36
0
 public static ValueTask <FlushResult> WriteGuidAsync(this PipeWriter writer, Guid value, LengthFormat lengthFormat, EncodingContext context, string?format = null, CancellationToken token = default)
 {
     writer.WriteGuid(value, lengthFormat, in context, format);
     return(writer.FlushAsync(token));
 }