Example #1
0
        public string Encode(byte[] buffer, int offset, int characterCount, EncodingOptions options)
        {
            // Initiate.
            this.options = options;

            // Encode each Arabic character.
            for (int i = 0; i < characterCount; i++) {

            // Seperator.
            if (i > 0) {
                writeCharacterSeperator();
            }

            // Encode character.
            encodeCharacter(buffer, offset);
            offset += ByteFormat.CHARACTER_WIDTH;
            }

            // Return text.
            return text.ToString();
        }
        public async Task<InternalEncodingTask> Create(EncodingOptions request, CancellationToken cancellationToken)
        {
            ValidateInput(request);

            var state = new InternalEncodingTask
            {
                Request = request
            };

            var item = string.IsNullOrEmpty(request.MediaSourceId) ?
                _libraryManager.GetItemById(new Guid(request.ItemId)) :
                _libraryManager.GetItemById(new Guid(request.MediaSourceId));

            if (item is ILiveTvRecording)
            {
                var recording = await _liveTvManager.GetInternalRecording(request.ItemId, cancellationToken).ConfigureAwait(false);

                if (string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
                {
                    state.InputVideoType = VideoType.VideoFile;
                }

                var path = recording.RecordingInfo.Path;
                var mediaUrl = recording.RecordingInfo.Url;

                if (string.IsNullOrWhiteSpace(path) && string.IsNullOrWhiteSpace(mediaUrl))
                {
                    var streamInfo = await _liveTvManager.GetRecordingStream(request.ItemId, cancellationToken).ConfigureAwait(false);

                    state.LiveTvStreamId = streamInfo.Id;

                    path = streamInfo.Path;
                    mediaUrl = streamInfo.Url;
                }

                if (!string.IsNullOrEmpty(path) && File.Exists(path))
                {
                    state.MediaPath = path;
                    state.IsInputRemote = false;
                }
                else if (!string.IsNullOrEmpty(mediaUrl))
                {
                    state.MediaPath = mediaUrl;
                    state.IsInputRemote = true;
                }

                state.InputRunTimeTicks = recording.RunTimeTicks;
                if (recording.RecordingInfo.Status == RecordingStatus.InProgress && !state.IsInputRemote)
                {
                    await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
                }

                state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
                state.AudioSync = "1000";
                state.DeInterlace = true;
                state.InputVideoSync = "-1";
                state.InputAudioSync = "1";
            }
            else if (item is LiveTvChannel)
            {
                var channel = _liveTvManager.GetInternalChannel(request.ItemId);

                if (string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
                {
                    state.InputVideoType = VideoType.VideoFile;
                }

                var streamInfo = await _liveTvManager.GetChannelStream(request.ItemId, cancellationToken).ConfigureAwait(false);

                state.LiveTvStreamId = streamInfo.Id;

                if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
                {
                    state.MediaPath = streamInfo.Path;
                    state.IsInputRemote = false;

                    await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
                }
                else if (!string.IsNullOrEmpty(streamInfo.Url))
                {
                    state.MediaPath = streamInfo.Url;
                    state.IsInputRemote = true;
                }

                state.ReadInputAtNativeFramerate = true;
                state.AudioSync = "1000";
                state.DeInterlace = true;
                state.InputVideoSync = "-1";
                state.InputAudioSync = "1";
            }
            else
            {
                state.MediaPath = item.Path;
                state.IsInputRemote = item.LocationType == LocationType.Remote;

                var video = item as Video;

                if (video != null)
                {
                    state.InputVideoType = video.VideoType;
                    state.IsoType = video.IsoType;

                    state.StreamFileNames = video.PlayableStreamFileNames.ToList();
                }

                state.InputRunTimeTicks = item.RunTimeTicks;
            }

            var videoRequest = request as VideoEncodingOptions;

            var mediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
            {
                ItemId = item.Id

            }).ToList();

            if (videoRequest != null)
            {
                state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
                state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
                state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);

                if (state.VideoStream != null && state.VideoStream.IsInterlaced)
                {
                    state.DeInterlace = true;
                }
            }
            else
            {
                state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
            }

            state.HasMediaStreams = mediaStreams.Count > 0;

            state.SegmentLength = state.ReadInputAtNativeFramerate ? 5 : 10;
            state.HlsListSize = state.ReadInputAtNativeFramerate ? 100 : 1440;

            state.QualitySetting = GetQualitySetting();

            ApplyDeviceProfileSettings(state);

            return state;
        }
Example #3
0
        protected override string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding)
        {
            var itsOffsetMs = 0;

            var itsOffset = itsOffsetMs == 0 ? string.Empty : string.Format("-itsoffset {0} ", TimeSpan.FromMilliseconds(itsOffsetMs).TotalSeconds.ToString(UsCulture));

            var videoCodec = EncodingHelper.GetVideoEncoder(state, encodingOptions);

            var threads = EncodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec);

            var inputModifier = EncodingHelper.GetInputModifier(state, encodingOptions);

            // If isEncoding is true we're actually starting ffmpeg
            var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";

            var baseUrlParam = string.Empty;

            if (state.Request is GetLiveHlsStream)
            {
                baseUrlParam = string.Format(" -hls_base_url \"{0}/\"",
                                             "hls/" + Path.GetFileNameWithoutExtension(outputPath));
            }

            var useGenericSegmenter = true;

            if (useGenericSegmenter)
            {
                var outputTsArg = Path.Combine(FileSystem.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request);

                var timeDeltaParam = String.Empty;

                var segmentFormat = GetSegmentFileExtension(state.Request).TrimStart('.');
                if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase))
                {
                    segmentFormat = "mpegts";
                }

                baseUrlParam = string.Format("\"{0}/\"", "hls/" + Path.GetFileNameWithoutExtension(outputPath));

                return(string.Format("{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -f segment -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero -segment_time {6} {10} -individual_header_trailer 0 -segment_format {11} -segment_list_entry_prefix {12} -segment_list_type m3u8 -segment_start_number {7} -segment_list \"{8}\" -y \"{9}\"",
                                     inputModifier,
                                     EncodingHelper.GetInputArgument(state, encodingOptions),
                                     threads,
                                     EncodingHelper.GetMapArgs(state),
                                     GetVideoArguments(state, encodingOptions),
                                     GetAudioArguments(state, encodingOptions),
                                     state.SegmentLength.ToString(UsCulture),
                                     startNumberParam,
                                     outputPath,
                                     outputTsArg,
                                     timeDeltaParam,
                                     segmentFormat,
                                     baseUrlParam
                                     ).Trim());
            }

            // add when stream copying?
            // -avoid_negative_ts make_zero -fflags +genpts

            var args = string.Format("{0} {1} {2} -map_metadata -1 -map_chapters -1 -threads {3} {4} {5} -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero {6} -hls_time {7} -individual_header_trailer 0 -start_number {8} -hls_list_size {9}{10} -y \"{11}\"",
                                     itsOffset,
                                     inputModifier,
                                     EncodingHelper.GetInputArgument(state, encodingOptions),
                                     threads,
                                     EncodingHelper.GetMapArgs(state),
                                     GetVideoArguments(state, encodingOptions),
                                     GetAudioArguments(state, encodingOptions),
                                     state.SegmentLength.ToString(UsCulture),
                                     startNumberParam,
                                     state.HlsListSize.ToString(UsCulture),
                                     baseUrlParam,
                                     outputPath
                                     ).Trim();

            return(args);
        }
Example #4
0
        /// <summary>
        /// Renders the specified matrix.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="format">The format.</param>
        /// <param name="content">The content.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public SvgImage Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            var result = new SvgImage(matrix.Width, matrix.Height);

            Create(result, matrix, format, content, options);

            return(result);
        }
 /// <summary>
 /// Gets the command line arguments.
 /// </summary>
 protected abstract string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding);
Example #6
0
        protected override string GetVideoArguments(StreamState state, EncodingOptions encodingOptions)
        {
            if (!state.IsOutputVideo)
            {
                return(string.Empty);
            }

            var codec = EncodingHelper.GetVideoEncoder(state, encodingOptions);

            var args = "-codec:v:0 " + codec;

            // if (state.EnableMpegtsM2TsMode)
            // {
            //     args += " -mpegts_m2ts_mode 1";
            // }

            // See if we can save come cpu cycles by avoiding encoding
            if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
            {
                if (state.VideoStream != null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
                {
                    string bitStreamArgs = EncodingHelper.GetBitStreamArgs(state.VideoStream);
                    if (!string.IsNullOrEmpty(bitStreamArgs))
                    {
                        args += " " + bitStreamArgs;
                    }
                }

                //args += " -flags -global_header";
            }
            else
            {
                var keyFrameArg = string.Format(
                    CultureInfo.InvariantCulture,
                    " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"",
                    GetStartNumber(state) * state.SegmentLength,
                    state.SegmentLength);
                if (state.TargetFramerate.HasValue)
                {
                    // This is to make sure keyframe interval is limited to our segment,
                    // as forcing keyframes is not enough.
                    // Example: we encoded half of desired length, then codec detected
                    // scene cut and inserted a keyframe; next forced keyframe would
                    // be created outside of segment, which breaks seeking.
                    keyFrameArg += string.Format(
                        CultureInfo.InvariantCulture,
                        " -g {0} -keyint_min {0}",
                        (int)(state.SegmentLength * state.TargetFramerate)
                        );
                }

                var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;

                args += " " + EncodingHelper.GetVideoQualityParam(state, codec, encodingOptions, GetDefaultEncoderPreset()) + keyFrameArg;

                //args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0";

                // Add resolution params, if specified
                if (!hasGraphicalSubs)
                {
                    args += EncodingHelper.GetOutputSizeParam(state, encodingOptions, codec, true);
                }

                // This is for internal graphical subs
                if (hasGraphicalSubs)
                {
                    args += EncodingHelper.GetGraphicalSubtitleParam(state, encodingOptions, codec);
                }

                //args += " -flags -global_header";
            }

            if (args.IndexOf("-copyts", StringComparison.OrdinalIgnoreCase) == -1)
            {
                args += " -copyts";
            }

            if (!string.IsNullOrEmpty(state.OutputVideoSync))
            {
                args += " -vsync " + state.OutputVideoSync;
            }

            args += EncodingHelper.GetOutputFFlags(state);

            return(args);
        }
Example #7
0
 /// <summary>
 /// Gets the video arguments.
 /// </summary>
 protected abstract string GetVideoArguments(StreamState state, EncodingOptions encodingOptions);
Example #8
0
        private static string GetFastSeekValue(EncodingOptions options)
        {
            var time = options.StartTimeTicks;

            if (time.HasValue)
            {
                var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds;

                if (seconds > 0)
                {
                    return string.Format("-ss {0}", seconds.ToString(UsCulture));
                }
            }

            return string.Empty;
        }
Example #9
0
 public KeyFrame(EncodingOptions options)
 {
     Options = options;
 }
Example #10
0
        /// <summary>
        /// Renders the specified matrix.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="format">The format.</param>
        /// <param name="content">The content.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            var width         = matrix.Width;
            var height        = matrix.Height;
            var font          = TextFont ?? DefaultTextFont;
            var emptyArea     = 0;
            var outputContent = font != null &&
                                (options == null || !options.PureBarcode) &&
                                !String.IsNullOrEmpty(content) &&
                                (format == BarcodeFormat.CODE_39 ||
                                 format == BarcodeFormat.CODE_93 ||
                                 format == BarcodeFormat.CODE_128 ||
                                 format == BarcodeFormat.EAN_13 ||
                                 format == BarcodeFormat.EAN_8 ||
                                 format == BarcodeFormat.CODABAR ||
                                 format == BarcodeFormat.ITF ||
                                 format == BarcodeFormat.UPC_A ||
                                 format == BarcodeFormat.UPC_E ||
                                 format == BarcodeFormat.MSI ||
                                 format == BarcodeFormat.PLESSEY);

            if (options != null)
            {
                if (options.Width > width)
                {
                    width = options.Width;
                }
                if (options.Height > height)
                {
                    height = options.Height;
                }
            }

            var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            // calculating the scaling factor
            var pixelsizeWidth = width / matrix.Width;

            using (var bmpData = bmp.Lock())
            {
                bmpData.SetPixels(CreatePixels(matrix, width, height));
            }

            if (outputContent)
            {
                var textAreaHeight = (int)font.LineHeight;

                emptyArea = height > textAreaHeight ? textAreaHeight : 0;
            }

            // output content text below the barcode
            if (emptyArea > 0)
            {
                using (var g = new Graphics(bmp))
                {
                    switch (format)
                    {
                    case BarcodeFormat.UPC_E:
                    case BarcodeFormat.EAN_8:
                        if (content.Length < 8)
                        {
                            content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                        }
                        if (content.Length > 4)
                        {
                            content = content.Insert(4, "   ");
                        }
                        break;

                    case BarcodeFormat.EAN_13:
                        if (content.Length < 13)
                        {
                            content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                        }
                        if (content.Length > 7)
                        {
                            content = content.Insert(7, "   ");
                        }
                        if (content.Length > 1)
                        {
                            content = content.Insert(1, "   ");
                        }
                        break;

                    case BarcodeFormat.UPC_A:
                        if (content.Length < 12)
                        {
                            content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                        }
                        if (content.Length > 11)
                        {
                            content = content.Insert(11, "   ");
                        }
                        if (content.Length > 6)
                        {
                            content = content.Insert(6, "   ");
                        }
                        if (content.Length > 1)
                        {
                            content = content.Insert(1, "   ");
                        }
                        break;
                    }
                    g.FillRectangle(Background, 0, height - emptyArea, width, emptyArea);
                    var brush = new SolidBrush(Foreground);
                    g.DrawText(font, brush, pixelsizeWidth * matrix.Width / 2, height - emptyArea, content);
                }
            }

            return(bmp);
        }
Example #11
0
        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="dt">要打印的DataTable</param>
        /// <param name="Title">打印文件的标题</param>
        public string PrintPriview(DataTable dt, string Title, string paixudanhao, string dayinjimingcheng, params string[] chada)
        {
            var re = "";

            try
            {
                options = new EncodingOptions
                {
                    //DisableECI = true,
                    //CharacterSet = "UTF-8",
                    Width  = 300,
                    Height = 60
                };
                writer         = new BarcodeWriter();
                writer.Format  = BarcodeFormat.CODE_128;
                writer.Options = options;
                Bitmap bitmap = writer.Write(paixudanhao.ToString());
                img = Image.FromHbitmap(bitmap.GetHbitmap());

                string paixudanhao_abc = GetImage_abc(dt);
                if (paixudanhao_abc.Length > 78)
                {
                    paixudanhao_abc = paixudanhao_abc.Substring(0, 78);
                }
                options = new EncodingOptions
                {
                    Width  = 100,
                    Height = 100
                };
                writer         = new BarcodeWriter();
                writer.Format  = BarcodeFormat.QR_CODE;
                writer.Options = options;
                Bitmap bitmap_abc = writer.Write(paixudanhao_abc);
                img_abc = Image.FromHbitmap(bitmap_abc.GetHbitmap());
            }
            catch (Exception a)
            {
                re = "f";
            }
            try
            {
                PrintPreviewDialog PrintPriview = new PrintPreviewDialog();
                PrintPriview.Document    = CreatePrintDocument(dt, Title, dayinjimingcheng, chada);
                PrintPriview.WindowState = FormWindowState.Maximized;
                PrintPriview.ShowDialog();

                //在这里将数据插入到数据里
                //拼写sql语句 入库就ok
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                System.Web.HttpContext.Current.Response.Redirect("../Edit/" + paixudanhao);
                re = "f";
            }
            if (re.Equals("f"))
            {
                return("f");
            }
            else
            {
                return("s");
            }
        }
Example #12
0
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="dt">要打印的DataTable</param>
        /// <param name="Title">打印文件的标题</param>
        public bool Print(DataTable dt, string Title, string paixudanhao, string dayinjimingcheng, params string[] chadan)
        {
            options = new EncodingOptions
            {
                Width  = 300,
                Height = 60
            };
            writer         = new BarcodeWriter();
            writer.Format  = BarcodeFormat.CODE_128;
            writer.Options = options;
            Bitmap bitmap = writer.Write(paixudanhao);

            img = Image.FromHbitmap(bitmap.GetHbitmap());

            string paixudanhao_abc = GetImage_abc(dt);

            if (false && paixudanhao_abc.Length > 78)
            //paixudanhao_abc = paixudanhao_abc.Substring(0, 78);
            {
                options = new EncodingOptions
                {
                    Width  = 100,
                    Height = 100
                };
                string paixudanhao_abc_s = ""; int abci = 0;
                for (int i = 0; i <= paixudanhao_abc.Length / 78; i++)
                {
                    if (i != 0)
                    {
                        abci = i * 78 - 1;
                    }
                    if (i == paixudanhao_abc.Length / 78)
                    {
                        paixudanhao_abc_s = paixudanhao_abc.Substring(abci);
                    }
                    else
                    {
                        paixudanhao_abc_s = paixudanhao_abc.Substring(abci, 78);
                    }

                    writer         = new BarcodeWriter();
                    writer.Format  = BarcodeFormat.QR_CODE;
                    writer.Options = options;
                    Bitmap bitmap_abc = writer.Write(paixudanhao_abc_s);
                    Image  img_abcS   = Image.FromHbitmap(bitmap_abc.GetHbitmap());

                    img_abc_s.Add(img_abcS);
                }
            }
            else
            {
                options = new EncodingOptions
                {
                    Width  = 100,
                    Height = 100
                };
                writer         = new BarcodeWriter();
                writer.Format  = BarcodeFormat.QR_CODE;
                writer.Options = options;
                Bitmap bitmap_abc = writer.Write(paixudanhao_abc);
                img_abc = Image.FromHbitmap(bitmap_abc.GetHbitmap());
            }
            var re = CreatePrintDocument(dt, Title, dayinjimingcheng, chadan);

            if (re != null)
            {
                re.Print();
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public static (ImageBrush, bool) GetQRCodeImage(string uuid, bool LightTheme = true)
        {
            var encOptions = new EncodingOptions
            {
                Width       = 160,
                Height      = 160,
                Margin      = 0,
                PureBarcode = false
            };

            encOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            var bw = new BarcodeWriter();

            bw.Renderer = new BitmapRenderer();
            bw.Options  = encOptions;
            bw.Format   = BarcodeFormat.QR_CODE;

            var bm = bw.Write(uuid);

            try
            {
                var overlay = new Bitmap(Properties.Resources.logoLight32);
                if (!LightTheme)
                {
                    for (int j = 0; (j <= (bm.Height - 1)); j++)
                    {
                        for (int k = 0; (k <= (bm.Width - 1)); k++)
                        {
                            var inv = bm.GetPixel(k, j);
                            inv = System.Drawing.Color.FromArgb(255, (255 - inv.R), (255 - inv.G), (255 - inv.B));
                            bm.SetPixel(k, j, inv);
                        }
                    }
                    overlay = new Bitmap(Properties.Resources.logoDark32);
                }

                var g = Graphics.FromImage(bm);
                var x = (bm.Width - overlay.Width) / 2;
                var y = (bm.Height - overlay.Height) / 2;
                g.FillRectangle(new SolidBrush(System.Drawing.Color.White), x, y, overlay.Width, overlay.Height);
                g.DrawImage(overlay, new System.Drawing.Point(x, y));

                //bmp to bmpimg
                BitmapImage bitmapImage;
                using (var memory = new MemoryStream())
                {
                    bm.Save(memory, ImageFormat.Png);
                    memory.Position = 0;
                    bitmapImage     = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = memory;
                    bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
                }
                // end of bmp to bmpimg

                var brush = new ImageBrush(bitmapImage);
                return(brush, true);
            }
            catch (Exception ex)
            {
                Logger.Error("QRCodeImageGenerator", ex.Message);
                return(new ImageBrush(), false);
            }
        }
Example #14
0
        /// <summary>
        /// Renders the specified matrix.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="format">The format.</param>
        /// <param name="content">The content.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public PixelData Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            int  width         = matrix.Width;
            int  heigth        = matrix.Height;
            bool outputContent = (options == null || !options.PureBarcode) &&
                                 !String.IsNullOrEmpty(content) && (format == BarcodeFormat.CODE_39 ||
                                                                    format == BarcodeFormat.CODE_128 ||
                                                                    format == BarcodeFormat.EAN_13 ||
                                                                    format == BarcodeFormat.EAN_8 ||
                                                                    format == BarcodeFormat.CODABAR ||
                                                                    format == BarcodeFormat.ITF ||
                                                                    format == BarcodeFormat.UPC_A ||
                                                                    format == BarcodeFormat.MSI ||
                                                                    format == BarcodeFormat.PLESSEY);
            int emptyArea = outputContent ? 16 : 0;
            int pixelsize = 1;

            if (options != null)
            {
                if (options.Width > width)
                {
                    width = options.Width;
                }
                if (options.Height > heigth)
                {
                    heigth = options.Height;
                }
                // calculating the scaling factor
                pixelsize = width / matrix.Width;
                if (pixelsize > heigth / matrix.Height)
                {
                    pixelsize = heigth / matrix.Height;
                }
            }

            var pixels = new byte[width * heigth * 4];
            var index  = 0;

            for (int y = 0; y < matrix.Height - emptyArea; y++)
            {
                for (var pixelsizeHeight = 0; pixelsizeHeight < pixelsize; pixelsizeHeight++)
                {
                    for (var x = 0; x < matrix.Width; x++)
                    {
                        var color = matrix[x, y] ? Foreground : Background;
                        for (var pixelsizeWidth = 0; pixelsizeWidth < pixelsize; pixelsizeWidth++)
                        {
#if UNITY
                            pixels[index++] = color.b;
                            pixels[index++] = color.g;
                            pixels[index++] = color.r;
                            pixels[index++] = color.a;
#else
                            pixels[index++] = color.B;
                            pixels[index++] = color.G;
                            pixels[index++] = color.R;
                            pixels[index++] = color.A;
#endif
                        }
                    }
                    for (var x = pixelsize * matrix.Width; x < width; x++)
                    {
#if UNITY
                        pixels[index++] = Background.b;
                        pixels[index++] = Background.g;
                        pixels[index++] = Background.r;
                        pixels[index++] = Background.a;
#else
                        pixels[index++] = Background.B;
                        pixels[index++] = Background.G;
                        pixels[index++] = Background.R;
                        pixels[index++] = Background.A;
#endif
                    }
                }
            }
            for (int y = matrix.Height * pixelsize - emptyArea; y < heigth; y++)
            {
                for (var x = 0; x < width; x++)
                {
#if UNITY
                    pixels[index++] = Background.b;
                    pixels[index++] = Background.g;
                    pixels[index++] = Background.r;
                    pixels[index++] = Background.a;
#else
                    pixels[index++] = Background.B;
                    pixels[index++] = Background.G;
                    pixels[index++] = Background.R;
                    pixels[index++] = Background.A;
#endif
                }
            }

            return(new PixelData(width, heigth, pixels));
        }
Example #15
0
        public Color32[] Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            var result          = new Color32[matrix.Width * matrix.Height];
            var offset          = matrix.Height - 1;
            var foreground      = Foreground;
            var background      = Background;
            var bitRowRemainder = 32 - (32 - matrix.Width % 32);

            for (int y = 0; y < matrix.Height; y++)
            {
                var   ba   = matrix.getRow(offset - y, null);
                int[] bits = ba.Array;

                for (int x = 0; x < bits.Length; x++)
                {
                    int finalIndex = 32;

                    if (x == bits.Length - 1)
                    {
                        finalIndex = bitRowRemainder;
                    }

                    for (int i = 0; i < finalIndex; i++)
                    {
                        int bit = (bits[x] >> i) & 1;

                        if (bit == 1)
                        {
                            result[matrix.Width * y + x * 32 + i] = new Color32(foreground.r, foreground.g, foreground.b, foreground.a);
                        }
                        else
                        {
                            result[matrix.Width * y + x * 32 + i] = new Color32(background.r, background.g, background.b, background.a);
                        }
                    }
                }
            }

            return(result);
        }
Example #16
0
        internal static string GetH264Encoder(EncodingJob state, EncodingOptions options)
        {
            if (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
            {
                // It's currently failing on live tv
                if (state.RunTimeTicks.HasValue)
                {
                    return "h264_qsv";
                }
            }

            return "libx264";
        }
Example #17
0
        internal static string GetH264Encoder(IMediaEncoder mediaEncoder, EncodingJob state, EncodingOptions options)
        {
            var defaultEncoder = "libx264";

            // Only use alternative encoders for video files.
            // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
            // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
            if (state.VideoType == VideoType.VideoFile)
            {
                var hwType = options.HardwareAccelerationType;

                if (string.Equals(hwType, "qsv", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(hwType, "h264_qsv", StringComparison.OrdinalIgnoreCase))
                {
                    return GetAvailableEncoder(mediaEncoder, "h264_qsv", defaultEncoder);
                }

                if (string.Equals(hwType, "nvenc", StringComparison.OrdinalIgnoreCase))
                {
                    return GetAvailableEncoder(mediaEncoder, "h264_nvenc", defaultEncoder);
                }
                if (string.Equals(hwType, "h264_omx", StringComparison.OrdinalIgnoreCase))
                {
                    return GetAvailableEncoder(mediaEncoder, "h264_omx", defaultEncoder);
                }
                if (string.Equals(hwType, "vaapi", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(options.VaapiDevice))
                {
                    return GetAvailableEncoder(mediaEncoder, "h264_vaapi", defaultEncoder);
                }
            }

            return defaultEncoder;
        }
Example #18
0
 public KeyFrame(DataFrame dataFrame, EncodingOptions options) : base(dataFrame)
 {
     Options = options;
 }
Example #19
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            // FYI, sizes are a little weird when rending QR codes. Setting to certain values seems to not "take"
            // until the value exceeds some magical boundary.
            // Explained here: https://stackoverflow.com/questions/17527591/zxing-net-qr-code-size
            // "Each Matrix code type has symmetrical representation requirements. It will always jump to an even number that is a multiple of the codeword size."

            // GS1 General Specification define that GS1-128 (the formal application of Code 128 to the supply chain industry) has a limits of 48 characters per symbol.
            // But technically, there's no limit as long as the device can read it.
            // Let's set our limit to a reasonable 100.
            const int    maxValueLength     = 2048;
            const string defaultImageWidth  = "0";
            const string defaultImageHeight = "40";
            const int    minImageWidth      = 0;
            const int    maxImageWidth      = 2048;
            const int    minImageHeight     = 10;
            const int    maxImageHeight     = 2048;
            const string defaultMargin      = "0";
            const int    maxMargin          = 200;

            // Log the querystring.
            log.LogInformation($"querystring: {req.QueryString.Value}");

            // Validate the value, v
            if (!req.Query.ContainsKey("v"))
            {
                return(new BadRequestObjectResult("No value 'v' specified. You must specify the value you wish to encode."));
            }
            string value = req.Query["v"];

            if (value.Length > maxValueLength)
            {
                return(new BadRequestObjectResult($"Invalid length for value 'v'. This API will not render a barcode longer than {maxValueLength} characters."));
            }

            // Validate the output format 'fmt'.
            var outputFormat = req.Query.ContainsKey("fmt") ? req.Query["fmt"].ToString() : "png";

            if (outputFormat != "png" && outputFormat != "svg")
            {
                return(new BadRequestObjectResult(
                           $"Invalid output file format 'fmt'. Value must be 'png' or 'svg'."));
            }

            // Validate the barcode symbology, 'sym'.
            var symbologyStr = req.Query.ContainsKey("sym") ? req.Query["sym"].ToString() : BarcodeFormat.CODE_128.ToString();
            var parsed       = Enum.TryParse <BarcodeFormat>(symbologyStr, true, out var symbology);

            if (!parsed)
            {
                return(new BadRequestObjectResult(
                           $"Invalid barcode symbology 'sym'. Value must be one of {string.Join(",", Enum.GetNames(typeof(BarcodeFormat)))}"));
            }

            // Validate height, width and margin.
            var heightStr = req.Query.ContainsKey("h") ? req.Query["h"].ToString() : defaultImageHeight;
            var widthStr  = req.Query.ContainsKey("w") ? req.Query["w"].ToString() : defaultImageWidth;
            var marginStr = req.Query.ContainsKey("m") ? req.Query["m"].ToString() : defaultMargin;

            int.TryParse(heightStr, out var height);
            if (height < minImageHeight || height > maxImageHeight)
            {
                return(new BadRequestObjectResult($"Height 'h' must be between {minImageHeight} and {maxImageHeight}."));
            }
            int.TryParse(widthStr, out var width);
            if (width < minImageWidth || width > maxImageWidth)
            {
                return(new BadRequestObjectResult($"Width 'w' must be between {minImageWidth} and {maxImageWidth}."));
            }

            int.TryParse(marginStr, out var margin);
            if (margin < 0 || margin > maxMargin)
            {
                return(new BadRequestObjectResult($"Margin 'm' must be between 0 and {maxMargin}."));
            }

            // Configure the EncodingOptions.
            // There are many options for more complicated symbologies which we don't handle here.
            // Our purposes are focused on Code 128 and QR Code.
            var options = new EncodingOptions
            {
                Height = height
            };

            if (width > 0)
            {
                options.Width = width;
            }

            if (margin > 0)
            {
                options.Margin = margin;
            }


            // Branch depending on whether we're outputting a PNG graphics file or an SVG.
            if (outputFormat == "png")
            {
                var bcWriter = new BarcodeWriterPixelData
                {
                    Format  = symbology,
                    Options = options
                };
                var pixelData = bcWriter.Write(value);
                using (var img = Image.LoadPixelData <Rgba32>(pixelData.Pixels, pixelData.Width, pixelData.Height))
                {
                    using (var ms = new MemoryStream())
                    {
                        img.SaveAsPng(ms);
                        return(new FileContentResult(ms.ToArray(), "image/png"));
                    }
                }
            }
            else // svg
            {
                var svgWriter = new BarcodeWriterSvg()
                {
                    Format = symbology,
                };
                var svg   = svgWriter.Write(value);
                var bytes = Encoding.UTF8.GetBytes(svg.ToString());
                return(new FileContentResult(bytes, "image/svg+xml"));
            }
        }
Example #20
0
        /// <summary>
        /// A basic destination that will write your logs to a File on the hard disk.
        /// </summary>
        /// <param name="fileName">The target file for writing the logs to.</param>
        /// <param name="intReportingLevel">The integer representation of the level or levels that this destination should write log statements for.</param>
        /// <param name="resetFile">Default: true - will delete the current log file if it exists and recreate it.</param>
        /// <param name="encoder">Default: UTF8 - allows user to specify what encoding pattern to use when writing the output file.</param>
        public FileDestination(string fileName, int intReportingLevel, bool resetFile = true, EncodingOptions encoder = EncodingOptions.UTF8)
            : base(intReportingLevel)
        {
            _fi      = new FileInfo(fileName);
            _encoder = GetEncoding(encoder);

            InitFile(resetFile);
        }
Example #21
0
        protected override string GetAudioArguments(StreamState state, EncodingOptions encodingOptions)
        {
            var audioCodec = EncodingHelper.GetAudioEncoder(state);

            if (!state.IsOutputVideo)
            {
                if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase))
                {
                    return("-acodec copy");
                }

                var audioTranscodeParams = new List <string>();

                audioTranscodeParams.Add("-acodec " + audioCodec);

                if (state.OutputAudioBitrate.HasValue)
                {
                    audioTranscodeParams.Add("-ab " + state.OutputAudioBitrate.Value.ToString(CultureInfo.InvariantCulture));
                }

                if (state.OutputAudioChannels.HasValue)
                {
                    audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture));
                }

                if (state.OutputAudioSampleRate.HasValue)
                {
                    audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture));
                }

                audioTranscodeParams.Add("-vn");
                return(string.Join(" ", audioTranscodeParams.ToArray()));
            }

            if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase))
            {
                var videoCodec = EncodingHelper.GetVideoEncoder(state, encodingOptions);

                if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.EnableBreakOnNonKeyFrames(videoCodec))
                {
                    return("-codec:a:0 copy -copypriorss:a:0 0");
                }

                return("-codec:a:0 copy");
            }

            var args = "-codec:a:0 " + audioCodec;

            var channels = state.OutputAudioChannels;

            if (channels.HasValue)
            {
                args += " -ac " + channels.Value;
            }

            var bitrate = state.OutputAudioBitrate;

            if (bitrate.HasValue)
            {
                args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
            }

            if (state.OutputAudioSampleRate.HasValue)
            {
                args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
            }

            args += " " + EncodingHelper.GetAudioFilterParam(state, encodingOptions, true);

            return(args);
        }
Example #22
0
        /// <summary>
        /// Gets the name of the output video codec
        /// </summary>
        /// <returns>System.String.</returns>
        internal static string GetVideoEncoder(IMediaEncoder mediaEncoder, EncodingJob state, EncodingOptions options)
        {
            var codec = state.OutputVideoCodec;

            if (!string.IsNullOrEmpty(codec))
            {
                if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
                {
                    return(GetH264Encoder(mediaEncoder, state, options));
                }
                if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
                {
                    return("libvpx");
                }
                if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
                {
                    return("wmv2");
                }
                if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
                {
                    return("libtheora");
                }

                return(codec.ToLower());
            }

            return("copy");
        }
Example #23
0
        /// <summary>
        /// renders the image
        /// </summary>
        /// <param name="matrix"></param>
        /// <param name="format"></param>
        /// <param name="content"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public Image <TPixel> Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            var width  = matrix.Width;
            var height = matrix.Height;
            var black  = new Rgba32(0xFF000000);
            var white  = new Rgba32(0xFFFFFFFF);

            var pixelsize = 1;

            if (options != null)
            {
                if (options.Width > width)
                {
                    width = options.Width;
                }
                if (options.Height > height)
                {
                    height = options.Height;
                }
                // calculating the scaling factor
                pixelsize = width / matrix.Width;
                if (pixelsize > height / matrix.Height)
                {
                    pixelsize = height / matrix.Height;
                }
            }

            var result = new Image <TPixel>(width, height);

            for (int y = 0; y < matrix.Height; y++)
            {
                for (var pixelsizeHeight = 0; pixelsizeHeight < pixelsize; pixelsizeHeight++)
                {
                    var rowOffset = pixelsize * y + pixelsizeHeight;

                    for (var x = 0; x < matrix.Width; x++)
                    {
                        var color = matrix[x, y] ? black : white;
                        for (var pixelsizeWidth = 0; pixelsizeWidth < pixelsize; pixelsizeWidth++)
                        {
                            var pixel = new TPixel();
                            pixel.FromRgba32(color);
                            result[pixelsize * x + pixelsizeWidth, rowOffset] = pixel;
                        }
                    }
                    for (var x = pixelsize * matrix.Width; x < width; x++)
                    {
                        var pixel = new TPixel();
                        pixel.FromRgba32(white);
                        result[x, rowOffset] = pixel;
                    }
                }
            }

            return(result);
        }
Example #24
0
        internal static string GetH264Encoder(IMediaEncoder mediaEncoder, EncodingJob state, EncodingOptions options)
        {
            var defaultEncoder = "libx264";

            // Only use alternative encoders for video files.
            // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
            // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
            if (state.VideoType == VideoType.VideoFile)
            {
                var hwType = options.HardwareAccelerationType;

                if (string.Equals(hwType, "qsv", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(hwType, "h264_qsv", StringComparison.OrdinalIgnoreCase))
                {
                    return(GetAvailableEncoder(mediaEncoder, "h264_qsv", defaultEncoder));
                }

                if (string.Equals(hwType, "nvenc", StringComparison.OrdinalIgnoreCase))
                {
                    return(GetAvailableEncoder(mediaEncoder, "h264_nvenc", defaultEncoder));
                }
                if (string.Equals(hwType, "h264_omx", StringComparison.OrdinalIgnoreCase))
                {
                    return(GetAvailableEncoder(mediaEncoder, "h264_omx", defaultEncoder));
                }
                if (string.Equals(hwType, "vaapi", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(options.VaapiDevice))
                {
                    if (IsVaapiSupported(state))
                    {
                        return(GetAvailableEncoder(mediaEncoder, "h264_vaapi", defaultEncoder));
                    }
                }
            }

            return(defaultEncoder);
        }
Example #25
0
        /// <summary>
        /// Renders the specified matrix.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="format">The format.</param>
        /// <param name="content">The content.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        virtual public Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            int  width         = matrix.Width;
            int  height        = matrix.Height;
            bool outputContent = (options == null || !options.PureBarcode) &&
                                 !String.IsNullOrEmpty(content) && (format == BarcodeFormat.CODE_39 ||
                                                                    format == BarcodeFormat.CODE_128 ||
                                                                    format == BarcodeFormat.EAN_13 ||
                                                                    format == BarcodeFormat.EAN_8 ||
                                                                    format == BarcodeFormat.CODABAR ||
                                                                    format == BarcodeFormat.ITF ||
                                                                    format == BarcodeFormat.UPC_A ||
                                                                    format == BarcodeFormat.MSI ||
                                                                    format == BarcodeFormat.PLESSEY);
            int emptyArea = outputContent ? 16 : 0;
            int pixelsize = 1;

            if (options != null)
            {
                if (options.Width > width)
                {
                    width = options.Width;
                }
                if (options.Height > height)
                {
                    height = options.Height;
                }
                // calculating the scaling factor
                pixelsize = width / matrix.Width;
                if (pixelsize > height / matrix.Height)
                {
                    pixelsize = height / matrix.Height;
                }
            }

            // create the bitmap and lock the bits because we need the stride
            // which is the width of the image and possible padding bytes
            var bmp     = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

            try
            {
                var pixels  = new byte[bmpData.Stride * height];
                var padding = bmpData.Stride - (3 * width);
                var index   = 0;
                var color   = Background;

                for (int y = 0; y < matrix.Height - emptyArea; y++)
                {
                    for (var pixelsizeHeight = 0; pixelsizeHeight < pixelsize; pixelsizeHeight++)
                    {
                        for (var x = 0; x < matrix.Width; x++)
                        {
                            color = matrix[x, y] ? Foreground : Background;
                            for (var pixelsizeWidth = 0; pixelsizeWidth < pixelsize; pixelsizeWidth++)
                            {
                                pixels[index++] = color.B;
                                pixels[index++] = color.G;
                                pixels[index++] = color.R;
                            }
                        }
                        for (var x = pixelsize * matrix.Width; x < width; x++)
                        {
                            pixels[index++] = Background.B;
                            pixels[index++] = Background.G;
                            pixels[index++] = Background.R;
                        }
                        index += padding;
                    }
                }
                for (int y = matrix.Height * pixelsize - emptyArea; y < height; y++)
                {
                    for (var x = 0; x < width; x++)
                    {
                        pixels[index++] = Background.B;
                        pixels[index++] = Background.G;
                        pixels[index++] = Background.R;
                    }
                    index += padding;
                }

                //Copy the data from the byte array into BitmapData.Scan0
                Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
            }
            finally
            {
                //Unlock the pixels
                bmp.UnlockBits(bmpData);
            }

            if (outputContent)
            {
                switch (format)
                {
                case BarcodeFormat.EAN_8:
                    if (content.Length < 8)
                    {
                        content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                    }
                    content = content.Insert(4, "   ");
                    break;

                case BarcodeFormat.EAN_13:
                    if (content.Length < 13)
                    {
                        content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                    }
                    content = content.Insert(7, "   ");
                    content = content.Insert(1, "   ");
                    break;
                }
                var font = TextFont ?? DefaultTextFont;
                using (var g = Graphics.FromImage(bmp))
                {
                    var drawFormat = new StringFormat {
                        Alignment = StringAlignment.Center
                    };
#if WindowsCE
                    g.DrawString(content, font, Black, width / 2, height - 14, drawFormat);
#else
                    g.DrawString(content, font, Brushes.Black, width / 2, height - 14, drawFormat);
#endif
                }
            }

            return(bmp);
        }
Example #26
0
        /// <summary>
        /// Renders the specified matrix.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="format">The format.</param>
        /// <param name="content">The content.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        virtual public WriteableBitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            int  width         = matrix.Width;
            int  height        = matrix.Height;
            bool outputContent = (options == null || !options.PureBarcode) &&
                                 !String.IsNullOrEmpty(content) && (format == BarcodeFormat.CODE_39 ||
                                                                    format == BarcodeFormat.CODE_128 ||
                                                                    format == BarcodeFormat.EAN_13 ||
                                                                    format == BarcodeFormat.EAN_8 ||
                                                                    format == BarcodeFormat.CODABAR ||
                                                                    format == BarcodeFormat.ITF ||
                                                                    format == BarcodeFormat.UPC_A ||
                                                                    format == BarcodeFormat.MSI ||
                                                                    format == BarcodeFormat.PLESSEY);
            int emptyArea = outputContent ? 16 : 0;

#if NETFX_CORE
            var foreground = new byte[] { Foreground.B, Foreground.G, Foreground.R, Foreground.A };
            var background = new byte[] { Background.B, Background.G, Background.R, Background.A };
            var bmp        = new WriteableBitmap(width, height);
            var length     = width * height;

            // Copy data back
            using (var stream = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.AsStream(bmp.PixelBuffer))
            {
                for (int y = 0; y < height - emptyArea; y++)
                {
                    for (var x = 0; x < width; x++)
                    {
                        var color = matrix[x, y] ? foreground : background;
                        stream.Write(color, 0, 4);
                    }
                }
            }
            bmp.Invalidate();
#else
            int foreground = Foreground.A << 24 | Foreground.B << 16 | Foreground.G << 8 | Foreground.R;
            int background = Background.A << 24 | Background.B << 16 | Background.G << 8 | Background.R;
            var bmp        = new WriteableBitmap(width, height);
            var pixels     = bmp.Pixels;
            var index      = 0;

            for (int y = 0; y < height - emptyArea; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    var color = matrix[x, y] ? foreground : background;
                    pixels[index++] = color;
                }
            }
            bmp.Invalidate();
#endif

            if (outputContent)
            {
                switch (format)
                {
                case BarcodeFormat.EAN_8:
                    if (content.Length < 8)
                    {
                        content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                    }
                    content = content.Insert(4, "   ");
                    break;

                case BarcodeFormat.EAN_13:
                    if (content.Length < 13)
                    {
                        content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                    }
                    content = content.Insert(7, "   ");
                    content = content.Insert(1, "   ");
                    break;
                }

                /* doesn't correctly work at the moment
                 * renders at the wrong position
                 * var txt1 = new TextBlock {Text = content, FontSize = 10, Foreground = new SolidColorBrush(Colors.Black)};
                 * bmp.Render(txt1, new RotateTransform { Angle = 0, CenterX = width / 2, CenterY = height - 14});
                 * bmp.Invalidate();
                 * */
            }

            return(bmp);
        }
Example #27
0
        private void Create(SvgImage image, BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            if (matrix == null)
            {
                return;
            }

            const int spaceBetweenMatrixAndText = 3;
            int       width         = matrix.Width;
            int       height        = matrix.Height;
            var       outputContent = (options == null || !options.PureBarcode) &&
                                      !String.IsNullOrEmpty(content) &&
                                      (format == BarcodeFormat.CODE_39 ||
                                       format == BarcodeFormat.CODE_93 ||
                                       format == BarcodeFormat.CODE_128 ||
                                       format == BarcodeFormat.EAN_13 ||
                                       format == BarcodeFormat.EAN_8 ||
                                       format == BarcodeFormat.CODABAR ||
                                       format == BarcodeFormat.ITF ||
                                       format == BarcodeFormat.UPC_A ||
                                       format == BarcodeFormat.UPC_E ||
                                       format == BarcodeFormat.MSI ||
                                       format == BarcodeFormat.PLESSEY);

            if (outputContent)
            {
                var fontSize = FontSize < 1 ? DefaultFontSize : FontSize;
                height += fontSize + spaceBetweenMatrixAndText;
            }

            image.AddHeader();
            image.AddTag(0, 0, width, height, Background, Foreground);
            AppendDarkCell(image, matrix, 0, 0);

            if (outputContent)
            {
                var fontName = String.IsNullOrEmpty(FontName) ? DefaultFontName : FontName;
                var fontSize = FontSize < 1 ? DefaultFontSize : FontSize;

                content = ModifyContentDependingOnBarcodeFormat(format, content);

                image.AddText(content, fontName, fontSize);
            }

            image.AddEnd();
        }
Example #28
0
 protected override string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding)
 {
     return(EncodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, outputPath, GetDefaultH264Preset()));
 }
        private void ValidateInput(EncodingOptions request)
        {
            if (string.IsNullOrWhiteSpace(request.ItemId))
            {
                throw new ArgumentException("ItemId is required.");
            }
            if (string.IsNullOrWhiteSpace(request.OutputPath))
            {
                throw new ArgumentException("OutputPath is required.");
            }
            if (string.IsNullOrWhiteSpace(request.Container))
            {
                throw new ArgumentException("Container is required.");
            }
            if (string.IsNullOrWhiteSpace(request.AudioCodec))
            {
                throw new ArgumentException("AudioCodec is required.");
            }

            var videoRequest = request as VideoEncodingOptions;

            if (videoRequest == null)
            {
                return;
            }
        }
Example #30
0
        public virtual byte[] Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            int width   = matrix.Width;
            int height1 = matrix.Height;
            int num1    = 0;

            if (options != null)
            {
                if (options.Width > width)
                {
                    width = options.Width;
                }
                if (options.Height > height1)
                {
                    height1 = options.Height;
                }
            }

            int num2 = width / matrix.Width;
            int num3 = height1 / matrix.Height;

            using (MemoryStream ms = new MemoryStream())
                using (Bitmap bitmap = new Bitmap(width, height1, PixelFormat.Format24bppRgb))
                    using (Graphics graphics = Graphics.FromImage((Image)bitmap))
                    {
                        BitmapData bitmapdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
                        try
                        {
                            byte[] source = new byte[bitmapdata.Stride * height1];
                            int    num4   = bitmapdata.Stride - (3 * width);
                            int    num5   = 0;
                            for (int index1 = 0; index1 < matrix.Height; ++index1)
                            {
                                for (int index2 = 0; index2 < num3; ++index2)
                                {
                                    for (int index3 = 0; index3 < matrix.Width; ++index3)
                                    {
                                        Color color = matrix[index3, index1] ? this._foreground : this._background;
                                        for (int index4 = 0; index4 < num2; ++index4)
                                        {
                                            byte[] numArray1 = source;
                                            int    index5    = num5;
                                            int    num6      = 1;
                                            int    num7      = index5 + num6;
                                            int    num8      = (int)color.B;
                                            numArray1[index5] = (byte)num8;
                                            byte[] numArray2 = source;
                                            int    index6    = num7;
                                            int    num9      = 1;
                                            int    num10     = index6 + num9;
                                            int    num11     = (int)color.G;
                                            numArray2[index6] = (byte)num11;
                                            byte[] numArray3 = source;
                                            int    index7    = num10;
                                            int    num12     = 1;
                                            num5 = index7 + num12;
                                            int num13 = (int)color.R;
                                            numArray3[index7] = (byte)num13;
                                        }
                                    }

                                    for (int index3 = num2 * matrix.Width; index3 < width; ++index3)
                                    {
                                        byte[] numArray1 = source;
                                        int    index4    = num5;
                                        int    num6      = 1;
                                        int    num7      = index4 + num6;
                                        int    num8      = (int)this._background.B;
                                        numArray1[index4] = (byte)num8;
                                        byte[] numArray2 = source;
                                        int    index5    = num7;
                                        int    num9      = 1;
                                        int    num10     = index5 + num9;
                                        int    num11     = (int)this._background.G;
                                        numArray2[index5] = (byte)num11;
                                        byte[] numArray3 = source;
                                        int    index6    = num10;
                                        int    num12     = 1;
                                        num5 = index6 + num12;
                                        int num13 = (int)this._background.R;
                                        numArray3[index6] = (byte)num13;
                                    }

                                    num5 += num4;
                                }
                            }

                            for (int index1 = num3 * matrix.Height; index1 < height1; ++index1)
                            {
                                for (int index2 = 0; index2 < width; ++index2)
                                {
                                    byte[] numArray1 = source;
                                    int    index3    = num5;
                                    int    num6      = 1;
                                    int    num7      = index3 + num6;
                                    int    num8      = (int)this._background.B;
                                    numArray1[index3] = (byte)num8;
                                    byte[] numArray2 = source;
                                    int    index4    = num7;
                                    int    num9      = 1;
                                    int    num10     = index4 + num9;
                                    int    num11     = (int)this._background.G;
                                    numArray2[index4] = (byte)num11;
                                    byte[] numArray3 = source;
                                    int    index5    = num10;
                                    int    num12     = 1;
                                    num5 = index5 + num12;
                                    int num13 = (int)this._background.R;
                                    numArray3[index5] = (byte)num13;
                                }

                                num5 += num4;
                            }

                            if (options != null && !options.PureBarcode)
                            {
                                int height2 = _textFont.Height;
                                num1 = height1 + 10 > height2 ? height2 : 0;
                                if (num1 > 0)
                                {
                                    int num6 = ((width * 3) + num4) * (height1 - num1);
                                    for (int index1 = height1 - num1; index1 < height1; ++index1)
                                    {
                                        for (int index2 = 0; index2 < width; ++index2)
                                        {
                                            byte[] numArray1 = source;
                                            int    index3    = num6;
                                            int    num7      = 1;
                                            int    num8      = index3 + num7;
                                            int    num9      = (int)this._background.B;
                                            numArray1[index3] = (byte)num9;
                                            byte[] numArray2 = source;
                                            int    index4    = num8;
                                            int    num10     = 1;
                                            int    num11     = index4 + num10;
                                            int    num12     = (int)this._background.G;
                                            numArray2[index4] = (byte)num12;
                                            byte[] numArray3 = source;
                                            int    index5    = num11;
                                            int    num13     = 1;
                                            num6 = index5 + num13;
                                            int num14 = (int)this._background.R;
                                            numArray3[index5] = (byte)num14;
                                        }

                                        num6 += num4;
                                    }
                                }
                            }

                            Marshal.Copy(source, 0, bitmapdata.Scan0, source.Length);
                        }
                        finally
                        {
                            bitmap.UnlockBits(bitmapdata);
                        }

                        if (num1 > 0)
                        {
                            switch (format)
                            {
                            case BarcodeFormat.EAN_8:
                                if (content.Length < 8)
                                {
                                    content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                                }
                                content = content.Insert(4, "   ");
                                break;

                            case BarcodeFormat.EAN_13:
                                if (content.Length < 13)
                                {
                                    content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                                }
                                content = content.Insert(7, "   ");
                                content = content.Insert(1, "   ");
                                break;
                            }

                            SolidBrush   solidBrush = new SolidBrush(this._foreground);
                            StringFormat format1    = new StringFormat()
                            {
                                Alignment = StringAlignment.Center
                            };
                            graphics.DrawString(string.IsNullOrEmpty(_displayText) ? content : _displayText, _textFont, (Brush)solidBrush, (float)(num2 * matrix.Width / 2), (float)(height1 - num1), format1);
                        }

                        bitmap.Save(ms, ImageFormat.Gif);
                        return(ms.ToArray());
                    }
        }
Example #31
0
        public static string Encode(IReadOnlyPosition position,
            EncodingOptions options = EncodingOptions.None)
        {
            Debug.Assert(position != null);
            var s = new StringBuilder(80);
            // Encode the chessboard
            var board = Factory.Instance.CreateChessboardArray(position);
            for (int row = Chessboard.ROW_MAX; row >= Chessboard.ROW_MIN; --row)
            {
                int empty_cells = 0;
                for (int column = Chessboard.COLUMN_MIN;
                    column <= Chessboard.COLUMN_MAX; ++column)
                {
                    var cur_cell = new ChessboardCell(row, column);
                    Players player;
                    Pieces piece;
                    if (board.IsPieceAt(cur_cell, out player, out piece))
                    {
                        if (empty_cells != 0)
                        {
                            s.Append(empty_cells);
                            empty_cells = 0;
                        }
                        s.Append(PieceToChar(player, piece));
                    }
                    else
                    {
                        ++empty_cells;
                    }
                }
                if (empty_cells != 0)
                {
                    s.Append(empty_cells);
                    empty_cells = 0;
                }
                if (row != Chessboard.ROW_MIN)
                {
                    s.Append(ROWS_SEPARATOR);
                }
            }

            // Encode player to move
            s.Append(' ');
            s.Append(position.IsWhiteToMove ? FEN_WHITE_TO_MOVE : FEN_BLACK_TO_MOVE);

            // Encode castling availability
            s.Append(' ');
            if (!position.IsCanCastleShort(Players.White)
                && !position.IsCanCastleLong(Players.White)
                && !position.IsCanCastleShort(Players.Black)
                && !position.IsCanCastleLong(Players.Black))
            {
                s.Append(FEN_NO_ONE_CAN_CASTLE);
            }
            else
            {
                if (position.IsCanCastleShort(Players.White))
                {
                    s.Append(FEN_WHITE_CAN_CASTLE_SHORT);
                }
                if (position.IsCanCastleLong(Players.White))
                {
                    s.Append(FEN_WHITE_CAN_CASTLE_LONG);
                }
                if (position.IsCanCastleShort(Players.Black))
                {
                    s.Append(FEN_BLACK_CAN_CASTLE_SHORT);
                }
                if (position.IsCanCastleLong(Players.Black))
                {
                    s.Append(FEN_BLACK_CAN_CASTLE_LONG);
                }
            }

            // Encode en passant caputre possibility
            s.Append(' ');
            int? capture_en_passant_column = position.CaptureEnPassantColumn;
            if (capture_en_passant_column.HasValue)
            {
                var cell = new ChessboardCell(position.IsWhiteToMove ? 5 : 2,
                    capture_en_passant_column.Value);
                s.Append(cell.ToString());
            }
            else
            {
                s.Append(FEN_CANNOT_CAPTURE_EN_PASSANT);
            }

            s.Append(' ').Append(position.HalfmoveClock);

            s.Append(' ').Append(options.HasFlag(EncodingOptions.SetMovesCountToOne)
                ? 1 : position.FullmoveNumber);

            return s.ToString();
        }
Example #32
0
        /// <summary>
        /// Renders the specified matrix.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="format">The format.</param>
        /// <param name="content">The content.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public System.DrawingCore.Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            var width         = matrix.Width;
            var height        = matrix.Height;
            var font          = TextFont ?? DefaultTextFont;
            var emptyArea     = 0;
            var outputContent = font != null &&
                                (options == null || !options.PureBarcode) &&
                                !String.IsNullOrEmpty(content) &&
                                (format == BarcodeFormat.CODE_39 ||
                                 format == BarcodeFormat.CODE_93 ||
                                 format == BarcodeFormat.CODE_128 ||
                                 format == BarcodeFormat.EAN_13 ||
                                 format == BarcodeFormat.EAN_8 ||
                                 format == BarcodeFormat.CODABAR ||
                                 format == BarcodeFormat.ITF ||
                                 format == BarcodeFormat.UPC_A ||
                                 format == BarcodeFormat.UPC_E ||
                                 format == BarcodeFormat.MSI ||
                                 format == BarcodeFormat.PLESSEY);

            if (options != null)
            {
                if (options.Width > width)
                {
                    width = options.Width;
                }
                if (options.Height > height)
                {
                    height = options.Height;
                }
            }

            // calculating the scaling factor
            var pixelsizeWidth  = width / matrix.Width;
            var pixelsizeHeight = height / matrix.Height;

            // create the bitmap and lock the bits because we need the stride
            // which is the width of the image and possible padding bytes
            var bmp = new System.DrawingCore.Bitmap(width, height, System.DrawingCore.Imaging.PixelFormat.Format24bppRgb);

            var dpiX = DpiX ?? DpiY;
            var dpiY = DpiY ?? DpiX;

            if (dpiX != null)
            {
                bmp.SetResolution(dpiX.Value, dpiY.Value);
            }

            using (var g = System.DrawingCore.Graphics.FromImage(bmp))
            {
                var bmpData = bmp.LockBits(new System.DrawingCore.Rectangle(0, 0, bmp.Width, bmp.Height), System.DrawingCore.Imaging.ImageLockMode.WriteOnly,
                                           System.DrawingCore.Imaging.PixelFormat.Format24bppRgb);
                try
                {
                    var pixels  = new byte[bmpData.Stride * height];
                    var padding = bmpData.Stride - (3 * width);
                    var index   = 0;
                    var color   = Background;

                    // going through the lines of the matrix
                    for (int y = 0; y < matrix.Height; y++)
                    {
                        // stretching the line by the scaling factor
                        for (var pixelsizeHeightProcessed = 0;
                             pixelsizeHeightProcessed < pixelsizeHeight;
                             pixelsizeHeightProcessed++)
                        {
                            // going through the columns of the current line
                            for (var x = 0; x < matrix.Width; x++)
                            {
                                color = matrix[x, y] ? Foreground : Background;
                                // stretching the columns by the scaling factor
                                for (var pixelsizeWidthProcessed = 0;
                                     pixelsizeWidthProcessed < pixelsizeWidth;
                                     pixelsizeWidthProcessed++)
                                {
                                    pixels[index++] = color.B;
                                    pixels[index++] = color.G;
                                    pixels[index++] = color.R;
                                }
                            }
                            // fill up to the right if the barcode doesn't fully fit in
                            for (var x = pixelsizeWidth * matrix.Width; x < width; x++)
                            {
                                pixels[index++] = Background.B;
                                pixels[index++] = Background.G;
                                pixels[index++] = Background.R;
                            }
                            index += padding;
                        }
                    }
                    // fill up to the bottom if the barcode doesn't fully fit in
                    for (var y = pixelsizeHeight * matrix.Height; y < height; y++)
                    {
                        for (var x = 0; x < width; x++)
                        {
                            pixels[index++] = Background.B;
                            pixels[index++] = Background.G;
                            pixels[index++] = Background.R;
                        }
                        index += padding;
                    }
                    // fill the bottom area with the background color if the content should be written below the barcode
                    if (outputContent)
                    {
                        var textAreaHeight = font.Height;

                        emptyArea = height > textAreaHeight ? textAreaHeight : 0;

                        if (emptyArea > 0)
                        {
                            index = (width * 3 + padding) * (height - emptyArea);
                            for (int y = height - emptyArea; y < height; y++)
                            {
                                for (var x = 0; x < width; x++)
                                {
                                    pixels[index++] = Background.B;
                                    pixels[index++] = Background.G;
                                    pixels[index++] = Background.R;
                                }
                                index += padding;
                            }
                        }
                    }

                    //Copy the data from the byte array into BitmapData.Scan0
                    Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
                }
                finally
                {
                    //Unlock the pixels
                    bmp.UnlockBits(bmpData);
                }

                // output content text below the barcode
                if (emptyArea > 0)
                {
                    switch (format)
                    {
                    case BarcodeFormat.UPC_E:
                    case BarcodeFormat.EAN_8:
                        if (content.Length < 8)
                        {
                            content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                        }
                        if (content.Length > 4)
                        {
                            content = content.Insert(4, "   ");
                        }
                        break;

                    case BarcodeFormat.EAN_13:
                        if (content.Length < 13)
                        {
                            content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                        }
                        if (content.Length > 7)
                        {
                            content = content.Insert(7, "   ");
                        }
                        if (content.Length > 1)
                        {
                            content = content.Insert(1, "   ");
                        }
                        break;

                    case BarcodeFormat.UPC_A:
                        if (content.Length < 12)
                        {
                            content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                        }
                        if (content.Length > 11)
                        {
                            content = content.Insert(11, "   ");
                        }
                        if (content.Length > 6)
                        {
                            content = content.Insert(6, "   ");
                        }
                        if (content.Length > 1)
                        {
                            content = content.Insert(1, "   ");
                        }
                        break;
                    }
                    var brush      = new System.DrawingCore.SolidBrush(Foreground);
                    var drawFormat = new System.DrawingCore.StringFormat {
                        Alignment = System.DrawingCore.StringAlignment.Center
                    };
                    g.DrawString(content, font, brush, pixelsizeWidth * matrix.Width / 2, height - emptyArea, drawFormat);
                }
            }

            return(bmp);
        }
Example #33
0
        /// <summary>
        /// Gets the name of the output video codec
        /// </summary>
        /// <returns>System.String.</returns>
        internal static string GetVideoEncoder(IMediaEncoder mediaEncoder, EncodingJob state, EncodingOptions options)
        {
            var codec = state.OutputVideoCodec;

            if (!string.IsNullOrEmpty(codec))
            {
                if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
                {
                    return GetH264Encoder(mediaEncoder, state, options);
                }
                if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
                {
                    return "libvpx";
                }
                if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
                {
                    return "wmv2";
                }
                if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
                {
                    return "libtheora";
                }

                return codec.ToLower();
            }

            return "copy";
        }
Example #34
0
        private void Create(SvgImage image, BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            const int quietZone = 5;

            if (matrix == null)
            {
                return;
            }

            int width  = matrix.Width;
            int height = matrix.Height;

            image.AddHeader();
            image.AddTag(0, 0, 2 * quietZone + width, 2 * quietZone + height, Background, Foreground);
            AppendDarkCell(image, matrix, quietZone, quietZone);
            image.AddEnd();
        }
Example #35
0
        protected override string GetVideoArguments(StreamState state, EncodingOptions encodingOptions)
        {
            if (!state.IsOutputVideo)
            {
                return(string.Empty);
            }

            var codec = EncodingHelper.GetVideoEncoder(state, encodingOptions);

            var args = "-codec:v:0 " + codec;

            // if (state.EnableMpegtsM2TsMode)
            // {
            //     args += " -mpegts_m2ts_mode 1";
            // }

            // See if we can save come cpu cycles by avoiding encoding
            if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
            {
                if (state.VideoStream != null && EncodingHelper.IsH264(state.VideoStream) && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
                {
                    args += " -bsf:v h264_mp4toannexb";
                }

                //args += " -flags -global_header";
            }
            else
            {
                var keyFrameArg = string.Format(" -force_key_frames \"expr:gte(t,n_forced*{0})\"",
                                                state.SegmentLength.ToString(UsCulture));

                var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;

                args += " " + EncodingHelper.GetVideoQualityParam(state, codec, encodingOptions, GetDefaultH264Preset()) + keyFrameArg;

                //args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0";

                // Add resolution params, if specified
                if (!hasGraphicalSubs)
                {
                    args += EncodingHelper.GetOutputSizeParam(state, encodingOptions, codec, true);
                }

                // This is for internal graphical subs
                if (hasGraphicalSubs)
                {
                    args += EncodingHelper.GetGraphicalSubtitleParam(state, encodingOptions, codec);
                }

                //args += " -flags -global_header";
            }

            if (args.IndexOf("-copyts", StringComparison.OrdinalIgnoreCase) == -1)
            {
                args += " -copyts";
            }

            if (!string.IsNullOrEmpty(state.OutputVideoSync))
            {
                args += " -vsync " + state.OutputVideoSync;
            }

            args += EncodingHelper.GetOutputFFlags(state);

            return(args);
        }
        /// <summary>
        /// renders the BitMatrix as MagickImage
        /// </summary>
        /// <param name="matrix"></param>
        /// <param name="format"></param>
        /// <param name="content"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public IMagickImage <Byte> Render(BitMatrix matrix, BarcodeFormat format, String content, EncodingOptions options)
        {
            var header = System.Text.Encoding.UTF8.GetBytes($"P4\n{matrix.Width} {matrix.Height}\n");

            var rowBytes = matrix.Width / 8;

            if ((matrix.Width % 8) != 0)
            {
                rowBytes++;
            }

            var totalBuffer = new Byte[header.Length + rowBytes * matrix.Height];

            header.CopyTo(totalBuffer, 0);

            var bufferOffset = header.Length;

            for (var y = 0; y < matrix.Height; y++)
            {
                for (var x = 0; x < matrix.Width; x++)
                {
                    if (matrix[x, y])
                    {
                        totalBuffer[bufferOffset] |= (Byte)(((Byte)1) << 7 - (x % 8));
                    }

                    if (x % 8 == 7)
                    {
                        bufferOffset++;
                    }
                }

                if ((matrix.Width % 8) != 0)
                {
                    bufferOffset++;
                }
            }

            return(magickFactory.Image.Create(totalBuffer));
        }
Example #37
0
        /// <summary>
        /// Gets the number of audio channels to specify on the command line
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="audioStream">The audio stream.</param>
        /// <returns>System.Nullable{System.Int32}.</returns>
        public static int? GetNumAudioChannelsParam(EncodingOptions request, MediaStream audioStream)
        {
            if (audioStream != null)
            {
                var codec = request.AudioCodec ?? string.Empty;

                if (audioStream.Channels > 2 && codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    // wmav2 currently only supports two channel output
                    return 2;
                }
            }

            if (request.MaxAudioChannels.HasValue)
            {
                if (audioStream != null && audioStream.Channels.HasValue)
                {
                    return Math.Min(request.MaxAudioChannels.Value, audioStream.Channels.Value);
                }

                return request.MaxAudioChannels.Value;
            }

            return request.AudioChannels;
        }
Example #38
0
        protected override string GetVideoArguments(StreamState state, EncodingOptions encodingOptions)
        {
            if (!state.IsOutputVideo)
            {
                return(string.Empty);
            }

            var codec = EncodingHelper.GetVideoEncoder(state, encodingOptions);

            var args = "-codec:v:0 " + codec;

            // if (state.EnableMpegtsM2TsMode)
            // {
            //     args += " -mpegts_m2ts_mode 1";
            // }

            // See if we can save come cpu cycles by avoiding encoding
            if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
            {
                if (state.VideoStream != null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
                {
                    string bitStreamArgs = EncodingHelper.GetBitStreamArgs(state.VideoStream);
                    if (!string.IsNullOrEmpty(bitStreamArgs))
                    {
                        args += " " + bitStreamArgs;
                    }
                }

                //args += " -flags -global_header";
            }
            else
            {
                var gopArg      = string.Empty;
                var keyFrameArg = string.Format(
                    CultureInfo.InvariantCulture,
                    " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"",
                    GetStartNumber(state) * state.SegmentLength,
                    state.SegmentLength);

                var framerate = state.VideoStream?.RealFrameRate;

                if (framerate.HasValue)
                {
                    // This is to make sure keyframe interval is limited to our segment,
                    // as forcing keyframes is not enough.
                    // Example: we encoded half of desired length, then codec detected
                    // scene cut and inserted a keyframe; next forced keyframe would
                    // be created outside of segment, which breaks seeking
                    // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe
                    gopArg = string.Format(
                        CultureInfo.InvariantCulture,
                        " -g {0} -keyint_min {0} -sc_threshold 0",
                        Math.Ceiling(state.SegmentLength * framerate.Value)
                        );
                }

                args += " " + EncodingHelper.GetVideoQualityParam(state, codec, encodingOptions, GetDefaultEncoderPreset());

                // Unable to force key frames using these hw encoders, set key frames by GOP
                if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase))
                {
                    args += " " + gopArg;
                }
                else
                {
                    args += " " + keyFrameArg + gopArg;
                }

                //args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0";

                var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;

                // This is for graphical subs
                if (hasGraphicalSubs)
                {
                    args += EncodingHelper.GetGraphicalSubtitleParam(state, encodingOptions, codec);
                }
                // Add resolution params, if specified
                else
                {
                    args += EncodingHelper.GetOutputSizeParam(state, encodingOptions, codec);
                }

                // -start_at_zero is necessary to use with -ss when seeking,
                // otherwise the target position cannot be determined.
                if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
                {
                    args += " -start_at_zero";
                }

                //args += " -flags -global_header";
            }

            if (!string.IsNullOrEmpty(state.OutputVideoSync))
            {
                args += " -vsync " + state.OutputVideoSync;
            }

            args += EncodingHelper.GetOutputFFlags(state);

            return(args);
        }