BililiveRecorder/BililiveRecorder.ToolBox/Tool/Analyze/AnalyzeHandler.cs

226 lines
9.9 KiB
C#
Raw Normal View History

2021-04-14 23:46:24 +08:00
using System;
using System.Collections.Generic;
using System.IO;
2021-04-19 18:20:14 +08:00
using System.IO.Compression;
2021-04-14 23:46:24 +08:00
using System.IO.Pipelines;
using System.Linq;
using System.Text;
2021-05-02 21:34:27 +08:00
using System.Threading;
2021-04-14 23:46:24 +08:00
using System.Threading.Tasks;
using BililiveRecorder.Flv;
using BililiveRecorder.Flv.Amf;
using BililiveRecorder.Flv.Grouping;
using BililiveRecorder.Flv.Parser;
using BililiveRecorder.Flv.Pipeline;
using BililiveRecorder.Flv.Pipeline.Actions;
2021-04-14 23:46:24 +08:00
using BililiveRecorder.Flv.Writer;
2021-04-19 18:20:14 +08:00
using BililiveRecorder.Flv.Xml;
2021-04-23 18:51:27 +08:00
using BililiveRecorder.ToolBox.ProcessingRules;
2021-04-14 23:46:24 +08:00
using Microsoft.Extensions.DependencyInjection;
using Serilog;
2021-07-15 12:58:50 +08:00
namespace BililiveRecorder.ToolBox.Tool.Analyze
2021-04-14 23:46:24 +08:00
{
public class AnalyzeHandler : ICommandHandler<AnalyzeRequest, AnalyzeResponse>
{
private static readonly ILogger logger = Log.ForContext<AnalyzeHandler>();
public string Name => "Analyze";
2021-04-14 23:46:24 +08:00
public async Task<CommandResponse<AnalyzeResponse>> Handle(AnalyzeRequest request, CancellationToken cancellationToken, ProgressCallback? progress)
2021-04-14 23:46:24 +08:00
{
2021-04-20 20:41:26 +08:00
FileStream? flvFileStream = null;
2021-04-19 18:20:14 +08:00
try
{
2021-05-02 22:24:57 +08:00
XmlFlvFile.XmlFlvFileMeta? meta = null;
var memoryStreamProvider = new RecyclableMemoryStreamProvider();
2021-04-19 18:20:14 +08:00
var comments = new List<ProcessingComment>();
var context = new FlvProcessingContext();
var session = new Dictionary<object, object?>();
2021-04-14 23:46:24 +08:00
2021-04-20 20:41:26 +08:00
// Input
2021-04-19 18:20:14 +08:00
string? inputPath;
IFlvTagReader tagReader;
try
{
inputPath = Path.GetFullPath(request.Input);
if (inputPath.EndsWith(".gz", StringComparison.OrdinalIgnoreCase))
tagReader = await Task.Run(() =>
{
using var stream = new GZipStream(File.Open(inputPath, FileMode.Open, FileAccess.Read, FileShare.Read), CompressionMode.Decompress);
var xmlFlvFile = (XmlFlvFile)XmlFlvFile.Serializer.Deserialize(stream);
2021-05-02 22:24:57 +08:00
meta = xmlFlvFile.Meta;
2021-04-19 18:20:14 +08:00
return new FlvTagListReader(xmlFlvFile.Tags);
});
else if (inputPath.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
tagReader = await Task.Run(() =>
{
using var stream = File.Open(inputPath, FileMode.Open, FileAccess.Read, FileShare.Read);
var xmlFlvFile = (XmlFlvFile)XmlFlvFile.Serializer.Deserialize(stream);
2021-05-02 22:24:57 +08:00
meta = xmlFlvFile.Meta;
2021-04-19 18:20:14 +08:00
return new FlvTagListReader(xmlFlvFile.Tags);
});
else if (inputPath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
tagReader = await Task.Run(() =>
{
using var zip = new ZipArchive(File.Open(inputPath, FileMode.Open, FileAccess.Read, FileShare.Read), ZipArchiveMode.Read, false, Encoding.UTF8);
var entry = zip.Entries.First(x => x.Name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase));
var xmlFlvFile = (XmlFlvFile)XmlFlvFile.Serializer.Deserialize(entry.Open());
meta = xmlFlvFile.Meta;
return new FlvTagListReader(xmlFlvFile.Tags);
});
2021-04-19 18:20:14 +08:00
else
{
2021-04-20 20:41:26 +08:00
flvFileStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan);
2021-04-19 18:20:14 +08:00
tagReader = new FlvTagPipeReader(PipeReader.Create(flvFileStream), memoryStreamProvider, skipData: false, logger: logger);
}
}
catch (Exception ex) when (ex is not FlvException)
{
return new CommandResponse<AnalyzeResponse>
{
Status = ResponseStatus.InputIOError,
Exception = ex,
ErrorMessage = ex.Message
};
}
2021-04-14 23:46:24 +08:00
2021-04-20 20:41:26 +08:00
// Output
var tagWriter = new AnalyzeMockFlvTagWriter();
// Pipeline
2021-04-19 18:20:14 +08:00
using var grouping = new TagGroupReader(tagReader);
using var writer = new FlvProcessingContextWriter(tagWriter: tagWriter, allowMissingHeader: true, disableKeyframes: true, logger: logger);
2021-04-23 18:51:27 +08:00
var statsRule = new StatsRule();
var pipeline = new ProcessingPipelineBuilder(new ServiceCollection().BuildServiceProvider()).Add(statsRule).AddDefault().AddRemoveFillerData().Build();
2021-04-14 23:46:24 +08:00
2021-04-20 20:41:26 +08:00
// Run
await Task.Run(async () =>
2021-04-14 23:46:24 +08:00
{
2021-04-20 20:41:26 +08:00
var count = 0;
2021-05-02 21:34:27 +08:00
while (!cancellationToken.IsCancellationRequested)
2021-04-20 20:41:26 +08:00
{
2021-05-02 21:34:27 +08:00
var group = await grouping.ReadGroupAsync(cancellationToken).ConfigureAwait(false);
2021-04-20 20:41:26 +08:00
if (group is null)
break;
2021-04-14 23:46:24 +08:00
2021-04-20 20:41:26 +08:00
context.Reset(group, session);
pipeline(context);
2021-04-14 23:46:24 +08:00
2021-04-20 20:41:26 +08:00
if (context.Comments.Count > 0)
{
comments.AddRange(context.Comments);
logger.Debug("分析逻辑输出 {@Comments}", context.Comments);
}
2021-04-14 23:46:24 +08:00
2021-04-20 20:41:26 +08:00
await writer.WriteAsync(context).ConfigureAwait(false);
2021-04-14 23:46:24 +08:00
2021-04-20 20:41:26 +08:00
foreach (var action in context.Actions)
if (action is PipelineDataAction dataAction)
foreach (var tag in dataAction.Tags)
tag.BinaryData?.Dispose();
2021-04-14 23:46:24 +08:00
2021-04-20 20:41:26 +08:00
if (count++ % 10 == 0 && flvFileStream is not null && progress is not null)
await progress((double)flvFileStream.Position / flvFileStream.Length);
}
}).ConfigureAwait(false);
2021-04-14 23:46:24 +08:00
2021-05-02 21:34:27 +08:00
if (cancellationToken.IsCancellationRequested)
return new CommandResponse<AnalyzeResponse> { Status = ResponseStatus.Cancelled };
2021-05-02 22:24:57 +08:00
if (meta is not null)
logger.Information("Xml meta: {@Meta}", meta);
2021-04-20 20:41:26 +08:00
// Result
2021-04-19 18:20:14 +08:00
var response = await Task.Run(() =>
{
2021-04-23 18:51:27 +08:00
var (videoStats, audioStats) = statsRule.GetStats();
var countableComments = comments.Where(x => x.ActionRequired).ToArray();
2021-04-19 18:20:14 +08:00
return new AnalyzeResponse
{
InputPath = inputPath,
2021-04-14 23:46:24 +08:00
2021-04-19 18:20:14 +08:00
NeedFix = tagWriter.OutputFileCount != 1 || countableComments.Any(),
2022-06-17 17:42:50 +08:00
Unrepairable = countableComments.Any(x => x.Type == CommentType.Unrepairable),
2021-04-14 23:46:24 +08:00
2021-04-19 18:20:14 +08:00
OutputFileCount = tagWriter.OutputFileCount,
2021-04-14 23:46:24 +08:00
2021-04-23 18:51:27 +08:00
VideoStats = videoStats,
AudioStats = audioStats,
2022-06-17 17:42:50 +08:00
IssueTypeOther = countableComments.Count(x => x.Type == CommentType.Other),
IssueTypeUnrepairable = countableComments.Count(x => x.Type == CommentType.Unrepairable),
IssueTypeTimestampJump = countableComments.Count(x => x.Type == CommentType.TimestampJump),
IssueTypeTimestampOffset = countableComments.Count(x => x.Type == CommentType.TimestampOffset),
IssueTypeDecodingHeader = countableComments.Count(x => x.Type == CommentType.DecodingHeader),
IssueTypeRepeatingData = countableComments.Count(x => x.Type == CommentType.RepeatingData)
2021-04-19 18:20:14 +08:00
};
});
2021-04-14 23:46:24 +08:00
2021-04-19 18:20:14 +08:00
return new CommandResponse<AnalyzeResponse>
{
Status = ResponseStatus.OK,
Data = response
2021-04-19 18:20:14 +08:00
};
}
2021-05-02 21:34:27 +08:00
catch (TaskCanceledException) when (cancellationToken.IsCancellationRequested)
{
return new CommandResponse<AnalyzeResponse> { Status = ResponseStatus.Cancelled };
}
2021-04-19 18:20:14 +08:00
catch (NotFlvFileException ex)
{
return new CommandResponse<AnalyzeResponse>
{
Status = ResponseStatus.NotFlvFile,
Exception = ex,
ErrorMessage = ex.Message
};
}
catch (UnknownFlvTagTypeException ex)
{
return new CommandResponse<AnalyzeResponse>
{
Status = ResponseStatus.UnknownFlvTagType,
Exception = ex,
ErrorMessage = ex.Message
};
}
catch (Exception ex)
{
return new CommandResponse<AnalyzeResponse>
{
Status = ResponseStatus.Error,
Exception = ex,
ErrorMessage = ex.Message
};
}
2021-04-20 20:41:26 +08:00
finally
{
flvFileStream?.Dispose();
}
2021-04-14 23:46:24 +08:00
}
private class AnalyzeMockFlvTagWriter : IFlvTagWriter
{
public long FileSize => 0;
public object? State => null;
public int OutputFileCount { get; private set; }
public bool CloseCurrentFile() => true;
public Task CreateNewFile()
{
this.OutputFileCount++;
return Task.CompletedTask;
}
public void Dispose() { }
public Task OverwriteMetadata(ScriptTagBody metadata) => Task.CompletedTask;
public Task WriteAccompanyingTextLog(double lastTagDuration, string message) => Task.CompletedTask;
2021-04-14 23:46:24 +08:00
public Task WriteTag(Tag tag) => Task.CompletedTask;
}
}
}