예제 #1
0
 public MainWindow()
 {
     InitializeComponent();
     ffmpeg = new FFmpeg();
     ffmpeg.OnProgressChanged += OnFFmpegProgressChanged;
 }
예제 #2
0
        async Task batchEncode()
        {
            if (files.Count < 1)
            {
                dfv.msgERR(com.lang.dat.HaveToAddFile);
                return;
            }

            convertEachRes.Clear();

            var successCount = 0;

            for (var ind = 0; ind < ffs.Count; ind++)
            {
                var f        = ffs[ind];
                var fileName = dfv.getFile2(f.fileName, convert.ext);
                var execRes  = "";
                try
                {
                    var ff = new FFmpeg();
                    progressStart(ff, Path.GetFileName(fileName), (ind + 1) + "/" + ffs.Count + " ");
                    var cmd = ff.muxerCommand(f, FFmpeg.getAllStreams(f), fileName, convert);
                    execRes      = cmd + "\r\n";
                    ff.onResLine = line =>
                    {
                        if (ff.isProcessing(line))
                        {
                            return;
                        }
                        this.BeginInvoke(new Action(() =>
                        {
                            execRes += "\r\n" + line;
                        }));
                    };
                    await ff.exec(cmd);

                    successCount++;
                    listViewFile.Items[ind].ForeColor = Color.Black;
                }
                catch (Exception err)
                {
                    if (err.Message == com.lang.dat.Already_has_a_task)
                    {
                        FFmpeg.getAllStreams(ffs);
                        dfv.msgERR(err.Message);
                        return;
                    }
                    com.shutdown = false;
                    removeEmptyFile(fileName);
                    var str = com.lang.dat.Error + ":" + Path.GetFileName(fileName);
                    listViewFile.Items[ind].ForeColor = Color.Red;
                    if (err is ExceptionFFmpeg)
                    {
                        if ((err as ExceptionFFmpeg).userAbort)
                        {
                            break;
                        }
                    }
                }
                convertEachRes.Add(execRes);
            }
            progressBarProc.Value = 100;
            labelProc.Text        = successCount + " " + com.lang.dat.Complete + " "
                                    + (ffs.Count - successCount) + " " + com.lang.dat.Failed + "!";
            FFmpeg.getAllStreams(ffs);
            if (com.shutdown)
            {
                sys.shutdown();
            }
        }
예제 #3
0
        internal async Task FullProcessPassedWithRetries()
        {
            const OperatingSystem os = OperatingSystem.Linux64;

            var operatingSystemProvider = Substitute.For <IOperatingSystemProvider>();

            operatingSystemProvider.GetOperatingSystem().Returns(x => os);
            OfficialFFmpegDownloader downloader = new OfficialFFmpegDownloader(operatingSystemProvider);

            var ffmpegExecutablesPath = FFmpeg.ExecutablesPath;

            try
            {
                FFmpeg.SetExecutablesPath(_storageFixture.GetTempDirectory());

                string ffmpegPath  = downloader.ComputeFileDestinationPath("ffmpeg", os, FFmpeg.ExecutablesPath);
                string ffprobePath = downloader.ComputeFileDestinationPath("ffprobe", os, FFmpeg.ExecutablesPath);

                // 1- First download

                await downloader.GetLatestVersion(FFmpeg.ExecutablesPath, null, 3);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));

                // 2- Check updates (same version)

                await downloader.GetLatestVersion(FFmpeg.ExecutablesPath, null, 3);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));

                // 3- Check updates (outdated version)

                var fFbinariesVersionInfo = new FFbinariesVersionInfo
                {
                    Version = new Version().ToString() // "0.0"
                };
                downloader.SaveVersion(fFbinariesVersionInfo, FFmpeg.ExecutablesPath);

                await downloader.GetLatestVersion(FFmpeg.ExecutablesPath, null, 3);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));

                // 4- Missing ffmpeg

                File.Delete(ffmpegPath);

                await downloader.GetLatestVersion(FFmpeg.ExecutablesPath, null, 3);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));

                // 5- Missing ffprobe

                File.Delete(ffprobePath);

                await downloader.GetLatestVersion(FFmpeg.ExecutablesPath, null, 3);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));
            }
            finally
            {
                FFmpeg.SetExecutablesPath(ffmpegExecutablesPath);
            }
        }
예제 #4
0
 public async Task SoundFromMovieTest()
 {
     await FFmpeg.SoundFromMovieAsync(ffmpeg, videoFile, @"C:\", "testAudio", "mp3");
 }
예제 #5
0
        public async Task <Stream> ConvertAsync(string filePath)
        {
            var tempFile   = Path.GetTempFileName();
            var outputPath = Path.ChangeExtension(tempFile, ".mp4");

            var ms = new MemoryStream();

            try
            {
                var mediaInfo = await FFmpeg.GetMediaInfo(filePath);

                var watermarkPath = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "watermark.png");

                IStream videoStream = mediaInfo.VideoStreams.FirstOrDefault()
                                      ?.SetCodec(VideoCodec.h264)
                                      ?.SetSize(VideoSize.Hvga)
                                      ?.SetWatermark(watermarkPath, Position.Center);
                IStream audioStream = mediaInfo.AudioStreams.FirstOrDefault()
                                      ?.SetCodec(AudioCodec.aac);

                var streams = new List <IStream>();

                if (videoStream != null)
                {
                    streams.Add(videoStream);
                }
                if (audioStream != null)
                {
                    streams.Add(audioStream);
                }

                if (!streams.Any())
                {
                    throw new Exception("Video and Audio stream not found");
                }

                Console.WriteLine("Start conversion. Output: " + outputPath);
                var result = await FFmpeg.Conversions.New()
                             .AddStream(streams)
                             .SetOutput(outputPath)
                             .Start();

                Console.WriteLine($"Conversion finished. Duration: {result.Duration}");

                using var fs = File.OpenRead(outputPath);
                await fs.CopyToAsync(ms);

                fs.Flush();

                ms.Seek(0, SeekOrigin.Begin);
            }
            catch (Exception e)
            {
                Console.WriteLine("Convert error: " + e.Message);
                throw;
            }
            finally
            {
                File.Delete(outputPath);
            }

            return(ms);
        }
예제 #6
0
 public static AVRational operator -(AVRational a, AVRational b)
 {
     return(FFmpeg.av_sub_q(a, b));
 }
예제 #7
0
 public async Task IncorrectFormatTest()
 {
     await Assert.ThrowsAsync <ArgumentException>(async() => await FFmpeg.GetMediaInfo(Resources.Dll));
 }
예제 #8
0
 /// <summary>
 /// Retrieve a thumbnail image from a video file.
 /// </summary>
 /// <param name="inputFile">Video file.</param>
 /// <param name="outputFile">Image file.</param>
 /// <param name="seekPosition">The seek position.</param>
 /// <param name="cancellationToken">The cancellation token to cancel a running ffmpeg process.</param>
 public static void GetThumbnail(this FFmpeg ffmpeg, string inputFile, string outputFile, TimeSpan seekPosition, CancellationToken cancellationToken = default(CancellationToken))
 {
     ffmpeg.Run(inputFile, outputFile,
                ((FormattableString)$"-ss {seekPosition.TotalSeconds} -i \"{inputFile}\" -vframes 1  \"{outputFile}\"").ToString(CultureInfo.InvariantCulture),
                cancellationToken);
 }
예제 #9
0
 /// <summary>
 /// Cuts the media.
 /// </summary>
 /// <param name="inputFile">The input file.</param>
 /// <param name="outputFile">The output file.</param>
 /// <param name="start">The starttime in seconds.</param>
 /// <param name="end">The endtime in seconds.</param>
 /// <param name="cancellationToken">The cancellation token to cancel a running ffmpeg process.</param>
 public static void CutMedia(this FFmpeg ffmpeg, string inputFile, string outputFile, TimeSpan start, TimeSpan end, CancellationToken cancellationToken = default(CancellationToken))
 {
     ffmpeg.Run(inputFile, outputFile,
                ((FormattableString)$"-ss {start} -to {end} -i \"{inputFile}\" -map 0:v? -c copy  -map 0:a? -c copy -map 0:s? -c copy \"{outputFile}\"").ToString(CultureInfo.InvariantCulture),
                cancellationToken);
 }
예제 #10
0
파일: MediaFile.cs 프로젝트: rvs76/Maranate
        private void SeekToPTS(long pts, bool stopAtKeyframe, bool forceSeek = false)
        {
            if (forceSeek == false)
            {
                if ((_pendingFrame != null) && (_pendingFrame.Fields != null))
                {
                    for (int fieldIndex = 0; fieldIndex < _pendingFrame.Fields.Length; fieldIndex++)
                    {
                        var field = _pendingFrame.Fields[fieldIndex];
                        if ((field.PTS == pts))
                        {
                            _pendingFrame.CurrentIndex = fieldIndex;
                            return;
                        }
                    }
                }
            }

            long seekPTS = pts;

            if (seekPTS < long.MaxValue)
            {
                seekPTS = seekPTS / PTSPerField / _videoCodecContext.ticks_per_frame * _videoCodecContext.ticks_per_frame * PTSPerField;
                if (long.MaxValue - seekPTS > _videoFrameFirstDTS.Value)
                {
                    seekPTS += _videoFrameFirstDTS.Value;
                }
            }

            var  originalPendingFrame = _pendingFrame;
            long lastSeekFilePosition = -1L;

            while (true)
            {
                if (seekPTS < 0)
                {
                    seekPTS = 0;
                }

                int ret = FFmpeg.avformat_seek_file(_pFormatContext, _videoStreamIndex, 0, seekPTS, seekPTS, FFmpeg.AVSEEK_FLAG.AVSEEK_FLAG_NONE);
                if (ret < 0)
                {
                    throw new Exception("Failed to seek to first frame: " + ret.ToString());
                }
                FFmpeg.avcodec_flush_buffers(_pVideoCodecContext);

                var pb = (FFmpeg.ByteIOContext)Marshal.PtrToStructure(_formatContext.pb, typeof(FFmpeg.ByteIOContext));
                if (lastSeekFilePosition != -1L)
                {
                    if ((lastSeekFilePosition == pb.pos) && (seekPTS != 0))
                    {
                        seekPTS -= (PTSPerField * _videoCodecContext.ticks_per_frame);
                        continue;
                    }
                }
                lastSeekFilePosition = pb.pos;

                if (_pendingFrame != originalPendingFrame)
                {
                    DisposeFrame(ref _pendingFrame);
                }

                _pendingFrame = ReadVideoFrame();

                if (_pendingFrame != null)
                {
                    if (_pendingFrame.Fields.First().PTS == pts)
                    {
                        return;
                    }

                    if (_pendingFrame.Fields.First().PTS > pts)
                    {
                        if (seekPTS == 0)
                        {
                            return;
                        }

                        seekPTS -= PTSPerField * _videoCodecContext.ticks_per_frame;

                        continue;
                    }

                    while (true)
                    {
                        if (stopAtKeyframe && _pendingFrame.IsKeyFrame)
                        {
                            _pendingFrame.CurrentIndex = 0;
                            return;
                        }

                        for (int fieldIndex = 0; fieldIndex < _pendingFrame.Fields.Length; fieldIndex++)
                        {
                            var field = _pendingFrame.Fields[fieldIndex];

                            if (field.PTS >= pts)
                            {
                                _pendingFrame.CurrentIndex = fieldIndex;
                                return;
                            }
                        }

                        var previousFrame = _pendingFrame;
                        _pendingFrame = ReadVideoFrame();
                        if (_pendingFrame == null)
                        {
                            _pendingFrame = previousFrame;
                            _pendingFrame.CurrentIndex = _pendingFrame.Fields.Length - 1;
                            return;
                        }
                        if (previousFrame != originalPendingFrame)
                        {
                            DisposeFrame(ref previousFrame);
                        }
                    }
                }
            }
        }
예제 #11
0
 /// <summary>
 /// Extracts the subtitle.
 /// </summary>
 /// <param name="inputFile">The input file.</param>
 /// <param name="outputFile">The output file.</param>
 /// <param name="subtitleTrack">The subtitle text stream to extract. This number is zero based. Omit to extract the first subtitle stream.</param>
 /// <param name="cancellationToken">The cancellation token to cancel a running ffmpeg process.</param>
 public static void ExtractSubtitle(this FFmpeg ffmpeg, string inputFile, string outputFile, int subtitleTrack = 0, CancellationToken cancellationToken = default(CancellationToken))
 {
     ffmpeg.Run(inputFile, outputFile, string.Format($"-i \"{inputFile}\" -vn -an -map 0:s:{subtitleTrack} -c:s:0 srt \"{outputFile}\""), cancellationToken);
 }
예제 #12
0
파일: MediaFile.cs 프로젝트: rvs76/Maranate
        public void Open(string filename)
        {
            int ret;

            Reset();

            _filename = filename;

            var dictionary = new FFmpeg.AVDictionary();

            dictionary.count = 0;
            ret = FFmpeg.avformat_open_input(out _pFormatContext, filename, IntPtr.Zero, dictionary);
            if (ret < 0)
            {
                throw new Exception("Failed to open input file: " + ret.ToString());
            }

            ret = FFmpeg.av_find_stream_info(_pFormatContext);
            if (ret < 0)
            {
                throw new Exception("Failed to find stream information: " + ret.ToString());
            }

            _formatContext = (FFmpeg.AVFormatContext)Marshal.PtrToStructure(_pFormatContext, typeof(FFmpeg.AVFormatContext));

            for (int streamIndex = 0; streamIndex < _formatContext.nb_streams; ++streamIndex)
            {
                //IntPtr pStream = _formatContext.streams[streamIndex];
                IntPtr pStream      = Marshal.ReadIntPtr(_formatContext.streams, streamIndex * 4);
                var    stream       = (FFmpeg.AVStream)Marshal.PtrToStructure(pStream, typeof(FFmpeg.AVStream));
                var    codecContext = (FFmpeg.AVCodecContext)Marshal.PtrToStructure(stream.codec, typeof(FFmpeg.AVCodecContext));

                if (codecContext.codec_type == FFmpeg.CodecType.CODEC_TYPE_VIDEO)
                {
                    _videoStreamIndex   = streamIndex;
                    _pVideoStream       = pStream;
                    _videoStream        = stream;
                    _pVideoCodecContext = stream.codec;
                    _videoCodecContext  = codecContext;

                    if (Resolution != ResolutionOption.Full)
                    {
                        Marshal.WriteInt32(_pVideoCodecContext, Marshal.OffsetOf(typeof(FFmpeg.AVCodecContext), "lowres").ToInt32(), (int)Resolution);
                    }

                    _pVideoCodecDecoder = FFmpeg.avcodec_find_decoder(_videoCodecContext.codec_id);
                    if (_pVideoCodecDecoder == IntPtr.Zero)
                    {
                        throw new Exception("Failed to find decoder");
                    }

                    ret = FFmpeg.avcodec_open(stream.codec, _pVideoCodecDecoder);
                    if (ret < 0)
                    {
                        throw new Exception("Failed to open codec: " + ret.ToString());
                    }

                    _videoCodecContext = (FFmpeg.AVCodecContext)Marshal.PtrToStructure(stream.codec, typeof(FFmpeg.AVCodecContext));

                    //Allocate buffers for original frame
                    _pFrameOrig = FFmpeg.avcodec_alloc_frame();

                    //Allocate buffers for RGB frame
                    _scalerY = new SwsScaler(_videoCodecContext);
                    _scalerY.DstPixelFormat = SwsScaler.PixelFormat.Y;

                    //Allocate buffers for RGB frame
                    _scalerRGB = new SwsScaler(_videoCodecContext);

                    // Allocate packet memory
                    int sizeOfPacket = Marshal.SizeOf(typeof(FFmpeg.AVPacket));
                    _pPacket = Marshal.AllocHGlobal(sizeOfPacket);
                    RtlZeroMemory(_pPacket, sizeOfPacket);
                }
                //else if (codecContext.codec_type == FFmpeg.CodecType.CODEC_TYPE_AUDIO)
                //{
                //    _audioStreamIndex = i;
                //    _pAudioStream = _formatContext.streams[i];
                //    _audioStream = stream;
                //    _pAudioCodec = stream.codec;
                //    _audioCodecContext = codecContext;
                //}
            }

            // Seek to the start of the file to reset dts values.
            ret = FFmpeg.avformat_seek_file(_pFormatContext, _videoStreamIndex, 0, 0, Int64.MaxValue, FFmpeg.AVSEEK_FLAG.AVSEEK_FLAG_NONE);
            if (ret < 0)
            {
                throw new Exception("Failed to seek to first frame: " + ret.ToString());
            }
            FFmpeg.avcodec_flush_buffers(_pVideoCodecContext);

            // Read the first frame to set initial dts values
            ReadVideoFrame();

            if (_lastFieldNumber == -1)
            {
                if (_filename == @"F:\Convert\ComskipTest\Chuck - 4x02 - Retune\(2012-09-10 03-55) Chuck - 4x02 - Chuck Versus the Suitcase.m2v")
                {
                    _lastFieldNumber = 160295;
                }
                else
                {
                    SeekToPTS(Int64.MaxValue, false);
                    _lastFieldNumber = _pendingFrame.Fields.Last().FieldNumber;
                }
            }

            SeekToPTS(0, false);
            return;
        }
예제 #13
0
파일: MediaFile.cs 프로젝트: rvs76/Maranate
 static MediaFile()
 {
     FFmpeg.av_register_all();
 }
예제 #14
0
		public static void Video(Queue item)
		{
			string file = item.FilePath;

            foreach (var video in GetStream.Video(file))
			{
				// FFmpeg args
				string resolution = string.Equals(item.Picture.Resolution, "auto", IC) ? string.Empty : $"-s {item.Picture.Resolution}";
				string framerate = string.Equals(item.Picture.FrameRate, "auto", IC) ? string.Empty : $"-r {item.Picture.FrameRate}";
				int bitdepth = item.Picture.BitDepth;
				string chroma = $"yuv{item.Picture.Chroma}p{(bitdepth > 8 ? $"{bitdepth}le" : "")}";
				string yadif = item.Picture.YadifEnable ? $"-vf \"yadif={item.Picture.YadifMode}:{item.Picture.YadifField}:{item.Picture.YadifFlag}\"" : "";
				int framecount = item.Picture.FrameCount;
				string ffcmd = item.Picture.Command;

				// Indexing
				if (!item.General.IsAviSynth)
				{
					if (framecount <= 0)
					{
						if (Default.UseFrameAccurate)
						{
							Console.WriteLine("Indexing... This may take very long time.");
							new FFmpeg().FrameCountAccurate(file);
						}
						else
						{
							Console.WriteLine("Indexing... Please Wait.");
							new FFmpeg().FrameCount(file);
						}
					}

					Console.WriteLine("Indexing... Make sure in sync :)");
					TaskManager.Run($"\"{Plugin.FFMS2}\" -f -c \"{file}\" timecode");
				}

				if (!string.IsNullOrEmpty(framerate))
					framecount = (int)Math.Ceiling((item.General.Duration * Convert.ToDouble(item.Picture.FrameRate, CultureInfo.InvariantCulture)));

				if (item.Picture.YadifEnable)
					if (item.Picture.YadifMode == 1)
						framecount *= 2; // make each fields as new frame

				// x265 settings
				string decbin = Plugin.FFMPEG;
                string encbin = Plugin.HEVC08;
				string preset = item.Video.Preset;
				string tune = string.Equals(item.Video.Tune, "off", IC) ? "" : $"--tune {item.Video.Tune}";
				int type = item.Video.Type;
				int pass;
				string value = item.Video.Value;
				string command = item.Video.Command;

				if (bitdepth == 10)
					encbin = Plugin.HEVC10;
				else if (bitdepth == 12)
					encbin = Plugin.HEVC12;

				string decoder = $"\"{decbin}\" -loglevel panic -i \"{file}\" -f yuv4mpegpipe -pix_fmt {chroma} -strict -1 {resolution} {framerate} {yadif} {ffcmd} -";

				string encoder = $"\"{encbin}\" --y4m - -p {preset} {(type == 0 ? "--crf" : type == 1 ? "--qp" : "--bitrate")} {value} {command} -o video0000_{video.Lang}.hevc";

				// Encoding start
				if (type >= 3) // multi pass
				{
					type--; // re-use

					for (int i = 0; i < type; i++)
					{
						if (i == 0)
							pass = 1;
						else if (i == type)
							pass = 2;
						else
							pass = 3;

						if (i == 1) // get actual frame count
						{
							Console.WriteLine("Re-indexing encoded file, make sure no damage.");
							framecount = new FFmpeg().FrameCount(Path.Combine(Default.DirTemp, $"video0000_{video.Lang}.hevc"));
						}

						Console.WriteLine($"Pass {i + 1} of {type}"); // human read no index
						TaskManager.Run($"{decoder} | {encoder} -f {framecount} --pass {pass}");
					}
				}
				else
				{
					TaskManager.Run($"{decoder} | {encoder} -f {framecount}");
				}

				break;
			}
		}
예제 #15
0
        private void SinglePass(string argument)
        {
            _ffmpegProcess = new FFmpeg(argument);

            _ffmpegProcess.ErrorDataReceived += ProcessOnErrorDataReceived;
            _ffmpegProcess.OutputDataReceived += ProcessOnOutputDataReceived;
            _ffmpegProcess.Exited += (o, args) => boxOutput.Invoke((Action)(() =>
            {
                if (_panic) return; //This should stop that one exception when closing the converter
                boxOutput.AppendText("\n--- FFMPEG HAS EXITED ---");
                buttonCancel.Enabled = false;

                _timer = new Timer();
                _timer.Interval = 500;
                _timer.Tick += Exited;
                _timer.Start();
            }));

            _ffmpegProcess.Start();
            StartPipe(_ffmpegProcess);
        }
예제 #16
0
 /// <summary>
 /// Converts the audio to ac-3
 /// </summary>
 /// <param name="inputFile">The input file.</param>
 /// <param name="outputFile">The output file.</param>
 /// <param name="audioTrack">The audio track.</param>
 /// <param name="bitRate">The bit rate.</param>
 /// <param name="samplingRate">The sampling rate.</param>
 /// <param name="cancellationToken">The cancellation token to cancel a running ffmpeg process.</param>
 public static void ConvertAudioToAC3(this FFmpeg ffmpeg, string inputFile, string outputFile, int audioTrack, int bitRate, int samplingRate, CancellationToken cancellationToken = default(CancellationToken))
 {
     ffmpeg.Run(inputFile, outputFile,
                string.Format($" -hwaccel auto -i \"{inputFile}\" -map {audioTrack} -c:s copy -c:v copy -c:a ac3 -b:a {bitRate} -ar {samplingRate} \"{outputFile}\""),
                cancellationToken);
 }
예제 #17
0
파일: rtmp.cs 프로젝트: Shine6Z/GenXSource
    public void CloseConnection()
    {
        if (m_sock != null && m_sock.Connected)
        {/*
          * if (m_writer2 != null)
          *     m_writer2.Close();*/
            if (fAMR != null)
            {
                fAMR.Close();
            }
            if (fPCM != null)
            {
                fPCM.Close();
            }
            if (fPCMRes != null)
            {
                fPCMRes.Close();
            }
            if (fFlv != null)
            {
                fFlv.Close();
            }
            if (fVideoSource != null)
            {
                fVideoSource.Close();
            }

            m_sock.Shutdown(SocketShutdown.Both);
            System.Threading.Thread.Sleep(10);
            m_sock.Close();
            FFmpeg.av_resample_close(pContextResample);

            if (!global::N2FProxy.Params.Default.UseOflaDemoApp)
            {
                SqlConnection conn = null;
                //SqlDataReader rdr = null;

                try
                {
                    //m_sTitle = null;
                    // create and open a connection object
                    conn = new SqlConnection("server=192.168.3.4;database=Next2Friends;uid=N2FDBLogin8745;password=59c42xMJH03t3fl83dk;Max Pool Size=200; Min Pool Size=20;");
                    conn.Open();
                    // the stored procedure
                    SqlCommand cmd = new SqlCommand("HG_EndLiveStream", conn);
                    // to execute a stored procedure
                    cmd.CommandType = CommandType.StoredProcedure;
                    //    will be passed to the stored procedure

                    //String sParameter = "@WebLiveBroadcastID", m_sStreamName;
                    cmd.Parameters.Add(new SqlParameter("@WebLiveBroadcastID", m_sStreamName));
                    cmd.Parameters.Add(new SqlParameter("@Nickname", m_sUserName));
                    //cmd.Parameters.Add(new SqlParameter("@Title", ??));
                    //cmd.Parameters.Add(new SqlParameter("@Description", ??));

                    // execute the command
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
                catch (Exception ex)
                {
                    LogInfo("Error Updating DB for Close Connection:" + ex.ToString());
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
            }
            m_Errors("Connection Stopped");
        }
    }
예제 #18
0
 /// <summary>
 /// Converts the video to avc/h264
 /// </summary>
 /// <param name="inputFile">The input file.</param>
 /// <param name="outputFile">The output file.</param>
 /// <param name="videoTrack">The video track.</param>
 /// <param name="cancellationToken">The cancellation token to cancel a running ffmpeg process.</param>
 public static void ConvertVideoToAVC(this FFmpeg ffmpeg, string inputFile, string outputFile, int videoTrack, CancellationToken cancellationToken = default(CancellationToken))
 {
     ffmpeg.Run(inputFile, outputFile,
                string.Format($" -hwaccel auto -i \"{inputFile}\" -map {videoTrack} -c:a copy -c:s copy -c:v libx264 \"{outputFile}\""),
                cancellationToken);
 }
예제 #19
0
 public static AVRational FromDouble(double d, int max)
 {
     return(FFmpeg.av_d2q(d, max));
 }
예제 #20
0
        public bool Stream()
        {
            int result;

            //  FFmpeg.AVPacket packet = new FFmpeg.AVPacket();
            IntPtr pPacket = Marshal.AllocHGlobal(56);

            //Marshal.StructureToPtr(packet, pPacket, false);
            //  Marshal.PtrToStructure(

            result = FFmpeg.av_read_frame(pFormatContext, pPacket);
            if (result < 0)
            {
                return(false);
            }
            count++;

            int    frameSize = 0;
            IntPtr pSamples  = IntPtr.Zero;

            FFmpeg.AVPacket packet = (FFmpeg.AVPacket)
                                     Marshal.PtrToStructure(pPacket, typeof(FFmpeg.AVPacket));
            Marshal.FreeHGlobal(pPacket);

            if (LivtUpdateEvent != null)
            {
                int    cur   = (int)(packet.dts * timebase.num / timebase.den);
                int    total = (int)(formatContext.duration / TIMESTAMP_BASE);
                string time  = String.Format("{0} out of {1} seconds", cur, total);
                LivtUpdateEvent(time);
            }

            if (packet.stream_index != this.audioStartIndex)
            {
                this.isAudioStream = false;
                return(true);
            }
            this.isAudioStream = true;

            try
            {
                pSamples = Marshal.AllocHGlobal(AUDIO_FRAME_SIZE);
                //int size = FFmpeg.avcodec_decode_audio(pAudioCodecContext, pSamples,
                //        ref frameSize, packet.data, packet.size);

                //FFmpeg.av_free_packet(pPacket);

                this.sampleSize = frameSize;
                Marshal.Copy(pSamples, samples, 0, AUDIO_FRAME_SIZE);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(false);
            }
            finally
            {
                Marshal.FreeHGlobal(pSamples);
            }

            return(true);
        }
예제 #21
0
        public async Task Mp4PropertiesTest()
        {
            IMediaInfo mediaInfo = await FFmpeg.GetMediaInfo(Resources.BunnyMp4);

            Assert.True(mediaInfo.Streams.Any());
        }
예제 #22
0
 public Decoder()
 {
     FFmpeg.av_register_all();
 }
예제 #23
0
 public async Task ImageFromMovieTest()
 {
     await FFmpeg.ImagesFromMovieAsync(ffmpeg, videoFile, @"C:\", "testimage", 23.97, "png");
 }
예제 #24
0
        public bool Open(string path)
        {
            Reset();

            int ret;

            ret = FFmpeg.av_open_input_file(out pFormatContext, path, IntPtr.Zero, 0, IntPtr.Zero);

            if (ret < 0)
            {
                Console.WriteLine("couldn't opne input file");
                return(false);
            }

            ret = FFmpeg.av_find_stream_info(pFormatContext);

            if (ret < 0)
            {
                Console.WriteLine("couldnt find stream informaion");
                return(false);
            }

            formatContext = (FFmpeg.AVFormatContext)
                            Marshal.PtrToStructure(pFormatContext, typeof(FFmpeg.AVFormatContext));

            for (int i = 0; i < formatContext.nb_streams; ++i)
            {
                FFmpeg.AVStream stream = (FFmpeg.AVStream)
                                         Marshal.PtrToStructure(formatContext.streams[i], typeof(FFmpeg.AVStream));

                FFmpeg.AVCodecContext codec = (FFmpeg.AVCodecContext)
                                              Marshal.PtrToStructure(stream.codec, typeof(FFmpeg.AVCodecContext));

                if (codec.codec_type == FFmpeg.CodecType.CODEC_TYPE_AUDIO &&
                    audioStartIndex == -1)
                {
                    //this.pAudioCodecContext = stream.codec;
                    //this.pAudioStream = formatContext.streams[i];
                    this.audioCodecContext = codec;
                    this.audioStartIndex   = i;
                    this.timebase          = stream.time_base;

                    pAudioCodec = FFmpeg.avcodec_find_decoder(this.audioCodecContext.codec_id);
                    if (pAudioCodec == IntPtr.Zero)
                    {
                        Console.WriteLine("couldn't find codec");
                        return(false);
                    }

                    FFmpeg.avcodec_open(stream.codec, pAudioCodec);
                }
            }

            if (audioStartIndex == -1)
            {
                Console.WriteLine("Couldn't find audio streamn");
                return(false);
            }

            audioSampleRate = audioCodecContext.sample_rate;

            if (audioCodecContext.channels == 1)
            {
                //format = Al.AL_FORMAT_MONO16;
            }
            else
            {
                //format = Al.AL_FORMAT_STEREO16;
            }

            return(true);
        }
예제 #25
0
        }// -----------------------------------------

        // --
        public override void start()
        {
            base.start();

            p = (CrushParams)jobData;

            // Working file is already set and points to either TEMP or INPUT folder
            INPUT = track.workingFile;
            // NOTE: OUTPUT path is generated later with the setupfiles() function

            // Before compressing the tracks, get and store the MD5 of the track
            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                using (var str = File.OpenRead(INPUT))
                {
                    track.md5 = BitConverter.ToString(md5.ComputeHash(str)).Replace("-", "").ToLower();
                }
            }

            // --
            if (track.isData)
            {
                var ecm = new EcmTools(CDCRUSH.TOOLS_PATH);
                setupHandlers(ecm);

                // New filename that is going to be generated:
                setupFiles(".bin.ecm");
                ecm.ecm(INPUT, OUTPUT); // old .bin file from wherever it was to temp/bin.ecm
            }
            else                        // AUDIO TRACK :
            {
                // Get Audio Data. (codecID, codecQuality)
                Tuple <string, int> audioQ = p.audioQuality;

                // New filename that is going to be generated:
                setupFiles(AudioMaster.getCodecExt(audioQ.Item1));

                // I need ffmpeg for both occations
                var ffmp = new FFmpeg(CDCRUSH.FFMPEG_PATH);
                setupHandlers(ffmp);

                if (audioQ.Item1 == "TAK")
                {
                    var tak = new Tak(CDCRUSH.TOOLS_PATH);

                    // This will make FFMPEG read the PCM file, convert it to WAV on the fly
                    // and feed it to TAK, which will convert and save it.
                    ffmp.convertPCMStreamToWavStream((ffmpegIn, ffmpegOut) => {
                        var sourceFile = File.OpenRead(INPUT);
                        tak.encodeFromStream(OUTPUT, (takIn) => {
                            ffmpegOut.CopyTo(takIn);
                            takIn.Close();
                        });
                        sourceFile.CopyTo(ffmpegIn);                    // Feed PCM to FFMPEG
                        ffmpegIn.Close();
                    });
                }
                else
                {
                    // It must be FFMPEG
                    ffmp.encodePCM(audioQ.Item1, audioQ.Item2, INPUT, OUTPUT);
                }
            }    //- end if (track.isData)
        }// -----------------------------------------
예제 #26
0
 public int CompareTo(AVRational other)
 {
     return(FFmpeg.av_cmp_q(this, other));
 }
예제 #27
0
 private void FFmpeg_OnInformation(FFmpeg sender, FFmpegInfo FFmpegInfo)
 {
     Debug.WriteLine(FFmpegInfo.Name);
 }
예제 #28
0
 public static AVRational operator *(AVRational a, AVRational b)
 {
     return(FFmpeg.av_mul_q(a, b));
 }
 public virtual void Sync(EnginePtr exeeng, Direct3D exed3d, OpenGL exeogl, Havok exehvk, GuiFactory exegui, Forms exefms, DirectIpt exedip, WinIpt exewip, FFmpeg exeffm, CryptoPP execpp, ID3Lib exeid3, WinAudio exewad, XAudio2 exexa2, WinMidi exemid, WinSock exewsk, AsyncWorkers exeaws, SQLite exesql, HaruPdf exepdf, RayTracer exertr, Pbrt exepbrt, PythonScriptEngine exepse, Console execle)
 {
     IronSightEnginePINVOKE.IDirect3D_Sync(swigCPtr, EnginePtr.getCPtr(exeeng), Direct3D.getCPtr(exed3d), OpenGL.getCPtr(exeogl), Havok.getCPtr(exehvk), GuiFactory.getCPtr(exegui), Forms.getCPtr(exefms), DirectIpt.getCPtr(exedip), WinIpt.getCPtr(exewip), FFmpeg.getCPtr(exeffm), CryptoPP.getCPtr(execpp), ID3Lib.getCPtr(exeid3), WinAudio.getCPtr(exewad), XAudio2.getCPtr(exexa2), WinMidi.getCPtr(exemid), WinSock.getCPtr(exewsk), AsyncWorkers.getCPtr(exeaws), SQLite.getCPtr(exesql), HaruPdf.getCPtr(exepdf), RayTracer.getCPtr(exertr), Pbrt.getCPtr(exepbrt), PythonScriptEngine.getCPtr(exepse), Console.getCPtr(execle));
     if (IronSightEnginePINVOKE.SWIGPendingException.Pending)
     {
         throw IronSightEnginePINVOKE.SWIGPendingException.Retrieve();
     }
 }
예제 #30
0
 public static AVRational operator /(AVRational a, AVRational b)
 {
     return(FFmpeg.av_div_q(a, b));
 }
예제 #31
0
        private void MultiPass(string[] arguments)
        {
            int passes = arguments.Length;

            _ffmpegProcess = new FFmpeg(arguments[_currentPass]);

            _ffmpegProcess.ErrorDataReceived += ProcessOnErrorDataReceived;
            _ffmpegProcess.OutputDataReceived += ProcessOnOutputDataReceived;
            _ffmpegProcess.Exited += (o, args) => boxOutput.Invoke((Action)(() =>
            {
                if (_panic) return; //This should stop that one exception when closing the converter
                boxOutput.AppendText("\n--- FFMPEG HAS EXITED ---");

                _currentPass++;
                if (_currentPass < passes && !_cancelTwopass)
                {
                    boxOutput.AppendText(string.Format("\n--- ENTERING PASS {0} ---", _currentPass + 1));

                    MultiPass(arguments); //Sort of recursion going on here, be careful with stack overflows and shit
                    return;
                }

                buttonCancel.Enabled = false;

                _timer = new Timer();
                _timer.Interval = 500;
                _timer.Tick += Exited;
                _timer.Start();
            }));

            _ffmpegProcess.Start();
            StartPipe(_ffmpegProcess);
        }
예제 #32
0
 public static AVRational operator +(AVRational a, AVRational b)
 {
     return(FFmpeg.av_add_q(a, b));
 }
예제 #33
0
        void StartPipe(FFmpeg ffmpeg)
        {
            if (!_needToPipe)
                return;

            string proxyargs = string.Format(@"-f avisynth -i ""{0}"" -f nut -c copy -v error pipe:1", _infile);
            boxOutput.AppendText("\n--- CREATING AVISYNTH PROXY --- ");

            _pipeFFmpeg = new FFmpeg(proxyargs, true);
            _pipeFFmpeg.ErrorDataReceived += (o, args) =>
            {
                try
                {
                    boxOutput.Invoke((Action) (() =>
                    {
                        boxOutput.AppendText(Environment.NewLine + args.Data);
                    }));
                }
                catch
                {
                    // ignored
                }
            };
            _pipeFFmpeg.Start(false);
            var bw = new BackgroundWorker();
            bw.DoWork += delegate
            {
                try
                {
                    _pipeFFmpeg.StandardOutput.BaseStream.CopyTo(ffmpeg.StandardInput.BaseStream);
                }
                catch
                {
                    // ignored
                }
            };
            _pipeFFmpeg.Exited += delegate
            {
                try
                {
                    _ffmpegProcess.StandardInput.Close();
                }
                catch
                {
                    // ignored
                }
            };
            bw.RunWorkerAsync();
        }
예제 #34
0
파일: rtmp.cs 프로젝트: Shine6Z/GenXSource
    /*
     * private void EncoderToMP3()
     * {
     *  if (!bInitMP3)
     *  {
     *      WaveFormat Format = new WaveFormat(16000, 16, 1);
     *      Format.nAvgBytesPerSec = 88200;
     *      Format.nBlockAlign = 2;
     *      Format.nChannels = 1;
     *      Format.nSamplesPerSec = 16000;
     *      Format.wBitsPerSample = 16;
     *      Format.wFormatTag = 1;
     *      m_Config = new Mp3WriterConfig(Format);
     *      m_writer = new Mp3Writer(new MemoryStream(10000), m_Config);
     *      if (m_bLogInfo)
     *          m_writer2 = new Mp3Writer(new FileStream(m_sStreamName + ".mp3", FileMode.Create), m_Config);
     *      bInitMP3 = true;
     *  }
     *  if (bInitMP3)
     *  {
     *      m_writer.Write(m_byFrameBuff, 0, m_iRxBufFrame);
     *      if (m_bLogInfo)
     *          m_writer2.Write(m_byFrameBuff, 0, m_iRxBufFrame);
     *      if (m_writer.iDataEncoded > 0)
     *      {
     *          SendDataStreamAudio(m_writer.m_OutBuffer, (int)m_writer.iDataEncoded);
     *          Console.WriteLine("mp3 frame size:{0}", m_writer.iDataEncoded);
     *      }
     *  }
     * }
     */
    private void DecoderAudio()
    {
        try
        {
            if (m_bSendAudio)
            {
                int iSize = 0;
                if (m_iAudioType == N2F_CODEC_AMR)
                {
                    byte[] byPcm = new byte[1024];
                    if (m_bLogInfo)
                    {
                        fAMR.Write(m_byFrameBuff, 0, m_iRxBufFrame);
                    }

                    unsafe
                    {
                        fixed(byte *pbyIn = m_byFrameBuff, pbyOut = byPcm)
                        {
                            iSize = MM.AmrDecodeOneFrame(pbyIn, pbyOut);
                            Array.Copy(byPcm, 0, m_byAudioBuff, iSizeAudioBuff, iSize);
                            iSizeAudioBuff += iSize;
                            m_iRxBufFrame   = iSize;
                        }
                    }
                    if (m_bLogInfo)
                    {
                        fPCM.Write(m_byAudioBuff, 0, iSizeAudioBuff);
                    }

                    m_Buffering.PushAudioFrame(m_byAudioBuff);
                    SendFramesBuffering();
                    iSizeAudioBuff = 0;


                    /*if (iSizeAudioBuff >= iSize)
                     * {
                     *  if (m_bLogInfo)
                     *      fPCM.Write(m_byAudioBuff, 0, iSizeAudioBuff);
                     *
                     *  if (global::N2FProxy.Params.Default.SampleRateOut != global::N2FProxy.Params.Default.SampleRateIn)
                     *  {
                     *      IntPtr pin = Marshal.AllocHGlobal(iSizeAudioBuff);
                     *      IntPtr pout = Marshal.AllocHGlobal(iSizeAudioBuff * 10);
                     *      Marshal.Copy(m_byAudioBuff, 0, pin, iSizeAudioBuff);
                     *
                     *      int iSizeS = FFmpeg.audio_resample(pContextResample, pout, pin, iSizeAudioBuff);
                     *      Marshal.Copy(pout, m_byAudioBuff, 0, iSizeS);
                     *      m_iRxBufFrame = iSizeS;
                     *
                     *      //Console.WriteLine("size audio resampled:{0}", iSizeS);
                     *      if (m_bLogInfo)
                     *          fPCMRes.Write(m_byAudioBuff, 0, iSizeS);
                     *  }
                     *
                     *  SendDataStreamAudio(m_byAudioBuff, m_iRxBufFrame);
                     *  iSizeAudioBuff = 0;
                     * }*/
                }
                else if (m_iAudioType == N2F_CODEC_PCM)
                {
                    if (global::N2FProxy.Params.Default.SampleRateOut != global::N2FProxy.Params.Default.SampleRateIn)
                    {
                        IntPtr pin  = Marshal.AllocHGlobal(m_iRxBufFrame);
                        IntPtr pout = Marshal.AllocHGlobal(m_iRxBufFrame * 20);
                        Marshal.Copy(m_byFrameBuff, 0, pin, m_iRxBufFrame);
                        iSize = FFmpeg.audio_resample(pContextResample, pout, pin, m_iRxBufFrame);
                        //Console.WriteLine("size audio resampled:{0}", iSize);
                        m_iRxBufFrame = iSize;
                        Marshal.Copy(pout, m_byFrameBuff, 0, iSize);
                    }
                    SendDataStreamAudio(m_byFrameBuff, m_iRxBufFrame);
                }
            }
        }
        catch (Exception ex)
        {
            LogInfo("Error Resample:" + ex.ToString());
            //m_Errors("Error Resample:" + ex.ToString());
        }
    }