Skip to content

Commit

Permalink
Reduce the amount of exceptions thrown
Browse files Browse the repository at this point in the history
  • Loading branch information
Bond-009 committed Mar 7, 2019
1 parent 10a0d6b commit 37ea50a
Show file tree
Hide file tree
Showing 13 changed files with 630 additions and 80 deletions.
9 changes: 6 additions & 3 deletions Emby.Dlna/PlayTo/Device.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1126,6 +1126,11 @@ private void UpdateMediaInfo(uBaseObject mediaInfo, TRANSPORTSTATE state)

private void OnPlaybackStart(uBaseObject mediaInfo)
{
if (string.IsNullOrWhiteSpace(mediaInfo.Url))
{
return;
}

PlaybackStart?.Invoke(this, new PlaybackStartEventArgs
{
MediaInfo = mediaInfo
Expand All @@ -1134,8 +1139,7 @@ private void OnPlaybackStart(uBaseObject mediaInfo)

private void OnPlaybackProgress(uBaseObject mediaInfo)
{
var mediaUrl = mediaInfo.Url;
if (string.IsNullOrWhiteSpace(mediaUrl))
if (string.IsNullOrWhiteSpace(mediaInfo.Url))
{
return;
}
Expand All @@ -1148,7 +1152,6 @@ private void OnPlaybackProgress(uBaseObject mediaInfo)

private void OnPlaybackStop(uBaseObject mediaInfo)
{

PlaybackStopped?.Invoke(this, new PlaybackStoppedEventArgs
{
MediaInfo = mediaInfo
Expand Down
2 changes: 1 addition & 1 deletion Emby.Server.Implementations/Diagnostics/CommonProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public Task<bool> WaitForExitAsync(int timeMs)

public void Dispose()
{
_process.Dispose();
_process?.Dispose();
}
}
}
27 changes: 9 additions & 18 deletions Emby.Server.Implementations/Library/LibraryManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,25 +278,15 @@ public void RegisterItem(BaseItem item)
{
throw new ArgumentNullException(nameof(item));
}

if (item is IItemByName)
{
if (!(item is MusicArtist))
{
return;
}
}

else if (item.IsFolder)
{
//if (!(item is ICollectionFolder) && !(item is UserView) && !(item is Channel) && !(item is AggregateFolder))
//{
// if (item.SourceType != SourceType.Library)
// {
// return;
// }
//}
}
else
else if (!item.IsFolder)
{
if (!(item is Video) && !(item is LiveTvChannel))
{
Expand Down Expand Up @@ -371,19 +361,20 @@ public void DeleteItem(BaseItem item, DeleteOptions options, BaseItem parent, bo

foreach (var metadataPath in GetMetadataPaths(item, children))
{
_logger.LogDebug("Deleting path {0}", metadataPath);
if (!Directory.Exists(metadataPath))
{
continue;
}

_logger.LogDebug("Deleting path {MetadataPath}", metadataPath);

try
{
Directory.Delete(metadataPath, true);
}
catch (IOException)
{

}
catch (Exception ex)
{
_logger.LogError(ex, "Error deleting {metadataPath}", metadataPath);
_logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
}
}

Expand Down
4 changes: 2 additions & 2 deletions Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,8 @@ public EmbyTV(IServerApplicationHost appHost,
_mediaSourceManager = mediaSourceManager;
_streamHelper = streamHelper;

_seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
_timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger);
_seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers.json"));
_timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers.json"), _logger);
_timerProvider.TimerFired += _timerProvider_TimerFired;

_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
Expand Down
26 changes: 10 additions & 16 deletions Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;

Expand Down Expand Up @@ -32,32 +31,28 @@ public IReadOnlyList<T> GetAll()
{
if (_items == null)
{
if (!File.Exists(_dataPath))
{
return new List<T>();
}

Logger.LogInformation("Loading live tv data from {0}", _dataPath);
_items = GetItemsFromFile(_dataPath);
}

return _items.ToList();
}
}

private List<T> GetItemsFromFile(string path)
{
var jsonFile = path + ".json";

if (!File.Exists(jsonFile))
{
return new List<T>();
}

try
{
return _jsonSerializer.DeserializeFromFile<List<T>>(jsonFile) ?? new List<T>();
}
catch (IOException)
{
return _jsonSerializer.DeserializeFromFile<List<T>>(path);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile);
Logger.LogError(ex, "Error deserializing {Path}", path);
}

return new List<T>();
Expand All @@ -70,12 +65,11 @@ private void UpdateList(List<T> newList)
throw new ArgumentNullException(nameof(newList));
}

var file = _dataPath + ".json";
Directory.CreateDirectory(Path.GetDirectoryName(file));
Directory.CreateDirectory(Path.GetDirectoryName(_dataPath));

lock (_fileDataLock)
{
_jsonSerializer.SerializeToFile(newList, file);
_jsonSerializer.SerializeToFile(newList, _dataPath);
_items = newList;
}
}
Expand Down
4 changes: 4 additions & 0 deletions Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,10 @@ private string GetChapterImagePath(Video video, long chapterPositionTicks)
private static List<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
{
var path = GetChapterImagesPath(video);
if (!Directory.Exists(path))
{
return new List<string>();
}

try
{
Expand Down
5 changes: 5 additions & 0 deletions MediaBrowser.Api/ApiEntryPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,11 @@ private void DeleteEncodedMediaCache()
{
var path = _config.ApplicationPaths.GetTranscodingTempPath();

if (!Directory.Exists(path))
{
return;
}

foreach (var file in _fileSystem.GetFilePaths(path, true))
{
_fileSystem.DeleteFile(file);
Expand Down
2 changes: 1 addition & 1 deletion MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Task ExtractVideoImagesOnInterval(string[] inputFiles,
/// <param name="inputFiles">The input files.</param>
/// <param name="protocol">The protocol.</param>
/// <returns>System.String.</returns>
string GetInputArgument(string[] inputFiles, MediaProtocol protocol);
string GetInputArgument(IReadOnlyList<string> inputFiles, MediaProtocol protocol);

/// <summary>
/// Gets the time parameter.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,24 @@
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;

namespace MediaBrowser.LocalMetadata.Images
{
public class InternalMetadataFolderImageProvider : ILocalImageFileProvider, IHasOrder
{
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
private readonly ILogger _logger;

public InternalMetadataFolderImageProvider(IServerConfigurationManager config, IFileSystem fileSystem)
public InternalMetadataFolderImageProvider(
IServerConfigurationManager config,
IFileSystem fileSystem,
ILogger<InternalMetadataFolderImageProvider> logger)
{
_config = config;
_fileSystem = fileSystem;
_logger = logger;
}

public string Name => "Internal Images";
Expand Down Expand Up @@ -53,12 +59,18 @@ public List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directory
{
var path = item.GetInternalMetadataPath();

if (!Directory.Exists(path))
{
return new List<LocalImageInfo>();
}

try
{
return new LocalImageProvider(_fileSystem).GetImages(item, path, false, directoryService);
}
catch (IOException)
catch (IOException ex)
{
_logger.LogError(ex, "Error while getting images for {Library}", item.Name);
return new List<LocalImageInfo>();
}
}
Expand Down
6 changes: 3 additions & 3 deletions MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
public static class EncodingUtils
{
public static string GetInputArgument(List<string> inputFiles, MediaProtocol protocol)
public static string GetInputArgument(IReadOnlyList<string> inputFiles, MediaProtocol protocol)
{
if (protocol != MediaProtocol.File)
{
var url = inputFiles.First();
var url = inputFiles[0];

return string.Format("\"{0}\"", url);
}
Expand All @@ -29,7 +29,7 @@ private static string GetConcatInputArgument(IReadOnlyList<string> inputFiles)
// If there's more than one we'll need to use the concat command
if (inputFiles.Count > 1)
{
var files = string.Join("|", inputFiles.Select(NormalizePath).ToArray());
var files = string.Join("|", inputFiles.Select(NormalizePath));

return string.Format("concat:\"{0}\"", files);
}
Expand Down
64 changes: 33 additions & 31 deletions MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -334,10 +334,8 @@ public Task<MediaInfo> GetMediaInfo(MediaInfoRequest request, CancellationToken
/// <param name="protocol">The protocol.</param>
/// <returns>System.String.</returns>
/// <exception cref="ArgumentException">Unrecognized InputType</exception>
public string GetInputArgument(string[] inputFiles, MediaProtocol protocol)
{
return EncodingUtils.GetInputArgument(inputFiles.ToList(), protocol);
}
public string GetInputArgument(IReadOnlyList<string> inputFiles, MediaProtocol protocol)
=> EncodingUtils.GetInputArgument(inputFiles, protocol);

/// <summary>
/// Gets the media info internal.
Expand All @@ -354,8 +352,9 @@ private async Task<MediaInfo> GetMediaInfoInternal(string inputPath,
CancellationToken cancellationToken)
{
var args = extractChapters
? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
: "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
? "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_chapters -show_format"
: "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_format";
args = string.Format(args, probeSizeArgument, inputPath).Trim();

var process = _processFactory.Create(new ProcessOptions
{
Expand All @@ -364,8 +363,10 @@ private async Task<MediaInfo> GetMediaInfoInternal(string inputPath,

// Must consume both or ffmpeg may hang due to deadlocks. See comments below.
RedirectStandardOutput = true,

FileName = FFprobePath,
Arguments = string.Format(args, probeSizeArgument, inputPath).Trim(),
Arguments = args,


IsHidden = true,
ErrorDialog = false,
Expand All @@ -383,43 +384,44 @@ private async Task<MediaInfo> GetMediaInfoInternal(string inputPath,

using (var processWrapper = new ProcessWrapper(process, this, _logger))
{
_logger.LogDebug("Starting ffprobe with args {Args}", args);
StartProcess(processWrapper);

InternalMediaInfoResult result;
try
{
//process.BeginErrorReadLine();
result = await _jsonSerializer.DeserializeFromStreamAsync<InternalMediaInfoResult>(process.StandardOutput.BaseStream).ConfigureAwait(false);
}
catch
{
StopProcess(processWrapper, 100);

var result = await _jsonSerializer.DeserializeFromStreamAsync<InternalMediaInfoResult>(process.StandardOutput.BaseStream).ConfigureAwait(false);
throw;
}

if (result == null || (result.streams == null && result.format == null))
{
throw new Exception("ffprobe failed - streams and format are both null.");
}
if (result == null || (result.streams == null && result.format == null))
{
throw new Exception("ffprobe failed - streams and format are both null.");
}

if (result.streams != null)
if (result.streams != null)
{
// Normalize aspect ratio if invalid
foreach (var stream in result.streams)
{
// Normalize aspect ratio if invalid
foreach (var stream in result.streams)
if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
{
if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
{
stream.display_aspect_ratio = string.Empty;
}
if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
{
stream.sample_aspect_ratio = string.Empty;
}
stream.display_aspect_ratio = string.Empty;
}
}

return new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);
if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
{
stream.sample_aspect_ratio = string.Empty;
}
}
}
catch
{
StopProcess(processWrapper, 100);

throw;
}
return new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);
}
}

Expand Down
Loading

0 comments on commit 37ea50a

Please sign in to comment.