Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Opening Devices #157

Merged
merged 2 commits into from
Feb 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions Unosquare.FFME.Common/Commands/OpenCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,42 @@ internal override void ExecuteInternal()

// Create the stream container
// the async protocol prefix allows for increased performance for local files.
var streamOptions = new StreamOptions
var streamOptions = new StreamOptions();

// Set the default protocol Prefix
try { streamOptions.ProtocolPrefix = Source.IsFile ? "async" : null; }
catch { }

// GDIGRAB: Example URI: format://gdigrab?desktop
if (string.IsNullOrWhiteSpace(Source.Scheme) == false
&& (Source.Scheme.Equals("format") || Source.Scheme.Equals("device"))
&& string.IsNullOrWhiteSpace(Source.Host) == false
&& string.IsNullOrWhiteSpace(streamOptions.Input.ForcedInputFormat)
&& string.IsNullOrWhiteSpace(Source.Query) == false)
{
ProtocolPrefix = Source.IsFile ? "async" : null
};
// Update the Input format and container input URL
// It is also possible to set some input options as follows:
// streamOptions.Input.Add(StreamInputOptions.Names.FrameRate, "20");
streamOptions.Input.ForcedInputFormat = Source.Host;
mediaUrl = Uri.UnescapeDataString(Source.Query).TrimStart('?');
m.Log(MediaLogMessageType.Info, $"Media URI will be updated. Input Format: {Source.Host}, Input Argument: {mediaUrl}");
}

// Allow the stream input options to be changed
m.SendOnMediaInitializing(streamOptions, mediaUrl);

// Instantiate the internal container
m.Container = new MediaContainer(mediaUrl, streamOptions, m);

// Notify the user media is opening and allow for media options to be modified
// Stuff like audio and video filters and stream selection can be performed here.
m.SendOnMediaOpening();

// Notify Media will start opening
m.Log(MediaLogMessageType.Debug, $"{nameof(OpenCommand)}: Entered");
m.Container.Open();

// Reset buffering properties
m.State.InitializeBufferingProperties();

// Charge! Fire up the worker threads!
Expand Down
4 changes: 2 additions & 2 deletions Unosquare.FFME.Common/Commands/SeekCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ internal override void ExecuteInternal()
var adjustedSeekTarget = TargetPosition;
if (main == MediaType.Video && m.Blocks[main].IsMonotonic)
{
var targetSkewTicks = (long)Math.Round(
m.Blocks[main][0].Duration.Ticks * (m.Blocks[main].Capacity / 2d), 2);
var targetSkewTicks = Convert.ToInt64(
m.Blocks[main][0].Duration.Ticks * (m.Blocks[main].Capacity / 2d));
adjustedSeekTarget = TimeSpan.FromTicks(adjustedSeekTarget.Ticks - targetSkewTicks);
}

Expand Down
2 changes: 1 addition & 1 deletion Unosquare.FFME.Common/Core/FFAudioParams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ internal static FFAudioParams CreateTarget(AVFrame* frame)
};

// The target transform is just a ratio of the source frame's sample. This is how many samples we desire
spec.SamplesPerChannel = (int)Math.Round((double)frame->nb_samples * spec.SampleRate / frame->sample_rate, 0);
spec.SamplesPerChannel = Convert.ToInt32(Convert.ToDouble(frame->nb_samples) * spec.SampleRate / frame->sample_rate);
spec.BufferLength = ffmpeg.av_samples_get_buffer_size(
null, spec.ChannelCount, spec.SamplesPerChannel + Constants.Audio.BufferPadding, spec.Format, 1);
return spec;
Expand Down
4 changes: 2 additions & 2 deletions Unosquare.FFME.Common/Core/LoggingWorker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ static LoggingWorker()
}
},
LogQueue, // the state argument passed on to the ticker
(int)Constants.Interval.LowPriority.TotalMilliseconds,
(int)Constants.Interval.LowPriority.TotalMilliseconds);
Convert.ToInt32(Constants.Interval.LowPriority.TotalMilliseconds),
Convert.ToInt32(Constants.Interval.LowPriority.TotalMilliseconds));
}

#endregion
Expand Down
2 changes: 1 addition & 1 deletion Unosquare.FFME.Common/Core/RealtimeClock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public TimeSpan Position
using (Locker.AcquireReaderLock())
{
return TimeSpan.FromTicks(
OffsetTicks + (long)Math.Round(Chrono.Elapsed.Ticks * SpeedRatio, 0));
OffsetTicks + Convert.ToInt64(Chrono.Elapsed.Ticks * SpeedRatio));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Unosquare.FFME.Common/Decoding/AudioFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ internal AudioFrame(AVFrame* frame, MediaComponent component)
if (frame->pkt_duration != 0)
Duration = frame->pkt_duration.ToTimeSpan(StreamTimeBase);
else
Duration = TimeSpan.FromTicks((long)Math.Round(TimeSpan.TicksPerMillisecond * 1000d * frame->nb_samples / frame->sample_rate, 0));
Duration = TimeSpan.FromTicks(Convert.ToInt64(TimeSpan.TicksPerMillisecond * 1000d * frame->nb_samples / frame->sample_rate));

EndTime = TimeSpan.FromTicks(StartTime.Ticks + Duration.Ticks);
}
Expand Down
4 changes: 2 additions & 2 deletions Unosquare.FFME.Common/Decoding/MediaComponent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ protected MediaComponent(MediaContainer container, int streamIndex)

CodecId = Stream->codec->codec_id;
CodecName = ffmpeg.avcodec_get_name(CodecId);
Bitrate = (int)Stream->codec->bit_rate;
Bitrate = Stream->codec->bit_rate;
Container.Parent?.Log(MediaLogMessageType.Debug,
$"COMP {MediaType.ToString().ToUpperInvariant()}: Start Offset: {StartTimeOffset.Format()}; Duration: {Duration.Format()}");
}
Expand Down Expand Up @@ -255,7 +255,7 @@ public ulong LifetimeBytesRead
/// Gets the bitrate of this component as reported by the codec context.
/// Returns 0 for unknown.
/// </summary>
public int Bitrate { get; }
public long Bitrate { get; }

/// <summary>
/// Gets the stream information.
Expand Down
16 changes: 10 additions & 6 deletions Unosquare.FFME.Common/Decoding/MediaContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -529,8 +529,11 @@ private void StreamInitialize()
if (string.IsNullOrWhiteSpace(StreamOptions.Input.ForcedInputFormat) == false)
{
inputFormat = ffmpeg.av_find_input_format(StreamOptions.Input.ForcedInputFormat);
Parent?.Log(MediaLogMessageType.Warning,
$"Format '{StreamOptions.Input.ForcedInputFormat}' not found. Will use automatic format detection.");
if (inputFormat == null)
{
Parent?.Log(MediaLogMessageType.Warning,
$"Format '{StreamOptions.Input.ForcedInputFormat}' not found. Will use automatic format detection.");
}
}

try
Expand Down Expand Up @@ -599,7 +602,8 @@ private void StreamInitialize()
IsNetworkStream = InputContext->iformat->read_play.Pointer != IntPtr.Zero;
if (IsNetworkStream == false && Uri.TryCreate(MediaUrl, UriKind.RelativeOrAbsolute, out var uri))
{
IsNetworkStream = uri.IsFile == false || uri.IsUnc;
try { IsNetworkStream = uri.IsFile == false || uri.IsUnc; }
catch { }
}

// Unsure how this works. Ported from ffplay
Expand Down Expand Up @@ -675,7 +679,7 @@ private void StreamInitializeInputContext()

// Apply the options
if (opts.EnableReducedBuffering) InputContext->avio_flags |= ffmpeg.AVIO_FLAG_DIRECT;
if (opts.PacketSize != default(int)) InputContext->packet_size = (uint)opts.PacketSize;
if (opts.PacketSize != default(int)) InputContext->packet_size = System.Convert.ToUInt32(opts.PacketSize);
if (opts.ProbeSize != default(int)) InputContext->probesize = StreamOptions.Format.ProbeSize <= 32 ? 32 : opts.ProbeSize;

// Flags
Expand All @@ -697,7 +701,7 @@ private void StreamInitializeInputContext()
if (opts.MaxAnalyzeDuration != default(TimeSpan))
{
InputContext->max_analyze_duration = opts.MaxAnalyzeDuration <= TimeSpan.Zero ? 0 :
(int)Math.Round(opts.MaxAnalyzeDuration.TotalSeconds * ffmpeg.AV_TIME_BASE, 0);
System.Convert.ToInt64(opts.MaxAnalyzeDuration.TotalSeconds * ffmpeg.AV_TIME_BASE);
}

if (string.IsNullOrEmpty(opts.CryptoKey) == false)
Expand Down Expand Up @@ -805,7 +809,7 @@ private MediaType StreamRead()
if (RequiresReadDelay)
{
// in ffplay.c this is referenced via CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
var millisecondsDifference = (int)Math.Round(DateTime.UtcNow.Subtract(StreamLastReadTimeUtc).TotalMilliseconds, 2);
var millisecondsDifference = System.Convert.ToInt32(DateTime.UtcNow.Subtract(StreamLastReadTimeUtc).TotalMilliseconds);
var sleepMilliseconds = 10 - millisecondsDifference;

// wait at least 10 ms to avoid trying to get another packet
Expand Down
4 changes: 2 additions & 2 deletions Unosquare.FFME.Common/Decoding/SubtitleFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ internal SubtitleFrame(AVSubtitle* frame, MediaComponent component)
var timeOffset = TimeSpan.FromTicks(frame->pts.ToTimeSpan(ffmpeg.AV_TIME_BASE).Ticks - component.Container.MediaStartTimeOffset.Ticks);

// start_display_time and end_display_time are relative to timeOffset
StartTime = TimeSpan.FromTicks(timeOffset.Ticks + ((long)frame->start_display_time).ToTimeSpan(StreamTimeBase).Ticks);
EndTime = TimeSpan.FromTicks(timeOffset.Ticks + ((long)frame->end_display_time).ToTimeSpan(StreamTimeBase).Ticks);
StartTime = TimeSpan.FromTicks(timeOffset.Ticks + Convert.ToInt64(frame->start_display_time).ToTimeSpan(StreamTimeBase).Ticks);
EndTime = TimeSpan.FromTicks(timeOffset.Ticks + Convert.ToInt64(frame->end_display_time).ToTimeSpan(StreamTimeBase).Ticks);
Duration = TimeSpan.FromTicks(EndTime.Ticks - StartTime.Ticks);

// Extract text strings
Expand Down
4 changes: 2 additions & 2 deletions Unosquare.FFME.Common/Decoding/VideoFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,12 @@ internal VideoFrame(AVFrame* frame, MediaComponent component)
/// If not set by the decoder, this attempts to obtain it by dividing the start time by the
/// frame duration
/// </summary>
public int DisplayPictureNumber { get; }
public long DisplayPictureNumber { get; }

/// <summary>
/// Gets the coded picture number set by the decoder.
/// </summary>
public int CodedPictureNumber { get; }
public long CodedPictureNumber { get; }

/// <summary>
/// Gets the SMTPE time code.
Expand Down
2 changes: 1 addition & 1 deletion Unosquare.FFME.Common/MediaEngine.Workers.Decoding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ internal void RunFrameDecodingWorker()
blocks = Blocks[main];

// Handle the main component decoding; Start by checking we have some packets
while (comp.PacketBufferCount <= 0 && CanReadMorePackets)
while (comp.PacketBufferCount <= 0 && CanReadMorePackets && ShouldReadMorePackets)
PacketReadingCycle.Wait(Constants.Interval.LowPriority);

if (comp.PacketBufferCount > 0)
Expand Down
2 changes: 1 addition & 1 deletion Unosquare.FFME.Common/MediaEngine.Workers.Rendering.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ private void StartBlockRenderingWorker()
},
this, // the state argument passed on to the ticker
0,
(int)Constants.Interval.HighPriority.TotalMilliseconds);
Convert.ToInt32(Constants.Interval.HighPriority.TotalMilliseconds));
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions Unosquare.FFME.Common/Primitives/CircularBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public CircularBuffer(int bufferLength)
{
m_Length = bufferLength;
Buffer = Marshal.AllocHGlobal(m_Length);
MediaEngine.Platform.NativeMethods.FillMemory(Buffer, (uint)m_Length, 0);
MediaEngine.Platform.NativeMethods.FillMemory(Buffer, Convert.ToUInt32(m_Length), 0);
}

/// <summary>
Expand Down Expand Up @@ -286,7 +286,7 @@ public void Write(IntPtr source, int length, TimeSpan writeTag, bool overwrite)
var copyLength = Math.Min(m_Length - m_WriteIndex, length - writeCount);
var sourcePtr = source + writeCount;
var targetPtr = Buffer + m_WriteIndex;
MediaEngine.Platform.NativeMethods.CopyMemory(targetPtr, sourcePtr, (uint)copyLength);
MediaEngine.Platform.NativeMethods.CopyMemory(targetPtr, sourcePtr, Convert.ToUInt32(copyLength));

writeCount += copyLength;
m_WriteIndex += copyLength;
Expand Down
6 changes: 3 additions & 3 deletions Unosquare.FFME.Common/Primitives/MediaBlockBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public TimeSpan AverageBlockDuration
using (Locker.AcquireReaderLock())
{
if (PlaybackBlocks.Count <= 0) return TimeSpan.Zero;
return TimeSpan.FromTicks((long)PlaybackBlocks.Average(b => Convert.ToDouble(b.Duration.Ticks)));
return TimeSpan.FromTicks(Convert.ToInt64(PlaybackBlocks.Average(b => Convert.ToDouble(b.Duration.Ticks))));
}
}
}
Expand Down Expand Up @@ -165,7 +165,7 @@ public double CapacityPercent
{
using (Locker.AcquireReaderLock())
{
return (double)Count / Capacity;
return Convert.ToDouble(Count) / Capacity;
}
}
}
Expand Down Expand Up @@ -242,7 +242,7 @@ public double GetRangePercent(TimeSpan position)
using (Locker.AcquireReaderLock())
{
return RangeDuration.Ticks != 0 ?
((double)position.Ticks - RangeStartTime.Ticks) / RangeDuration.Ticks : 0d;
Convert.ToDouble(position.Ticks - RangeStartTime.Ticks) / RangeDuration.Ticks : 0d;
}
}

Expand Down
Loading