aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Shares/SoulseekFileFactory.cs
blob: e3a9aa54024aadb4eba225cf6be6905703d0ec6b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// <copyright file="SoulseekFileFactory.cs" company="JP Dillingham">
//           ▄▄▄▄     ▄▄▄▄     ▄▄▄▄
//     ▄▄▄▄▄▄█  █▄▄▄▄▄█  █▄▄▄▄▄█  █
//     █__ --█  █__ --█    ◄█  -  █
//     █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
//   ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━  ━┉   ┉     ┉
//   │ Copyright (c) JP Dillingham.
//   │
//   │ This program is free software: you can redistribute it and/or modify
//   │ it under the terms of the GNU Affero General Public License as published
//   │ by the Free Software Foundation, version 3.
//   │
//   │ This program is distributed in the hope that it will be useful,
//   │ but WITHOUT ANY WARRANTY; without even the implied warranty of
//   │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   │ GNU Affero General Public License for more details.
//   │
//   │ You should have received a copy of the GNU Affero General Public License
//   │ along with this program.  If not, see https://www.gnu.org/licenses/.
//   │
//   │ This program is distributed with Additional Terms pursuant to Section 7
//   │ of the AGPLv3.  See the LICENSE file in the root directory of this
//   │ project for the complete terms and conditions.
//   │
//   │ https://slskd.org
//   │
//   ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
//   │ SPDX-FileCopyrightText: JP Dillingham
//   │ SPDX-License-Identifier: AGPL-3.0-only
//   ╰───────────────────────────────────────────╶──── ─ ─── ─  ── ──┈  ┈
// </copyright>

using System.IO;
using slskd.Files;

namespace slskd.Shares
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Serilog;
    using Soulseek;

    /// <summary>
    ///     Creates instances of <see cref="Soulseek.File"/>.
    /// </summary>
    public interface ISoulseekFileFactory
    {
        /// <summary>
        ///     Creates an instance of <see cref="Soulseek.File"/> from the given path.
        /// </summary>
        /// <param name="filename">The fully qualified path to the file.</param>
        /// <param name="maskedFilename">The masked filename.</param>
        /// <returns>The created instance.</returns>
        File Create(string filename, string maskedFilename);
    }

    /// <summary>
    ///     Creates instances of <see cref="Soulseek.File"/>.
    /// </summary>
    public class SoulseekFileFactory : ISoulseekFileFactory
    {
        private static readonly string[] AudioExtensions = { "aa", "aax", "aac", "aiff", "ape", "dsf", "flac", "m4a", "m4b", "m4p", "mp3", "mpc", "mpp", "ogg", "oga", "wav", "wma", "wv", "webm" };
        private static readonly string[] VideoExtensions = { "mkv", "ogv", "avi", "wmv", "asf", "mp4", "m4p", "m4v", "mpg", "mpe", "mpv", "mpg", "m2v" };
        private static readonly HashSet<string> SupportedExtensions = AudioExtensions.Concat(VideoExtensions).ToHashSet();

        /// <summary>
        ///     Initializes a new instance of the <see cref="SoulseekFileFactory"/> class.
        /// </summary>
        /// <param name="fileService"></param>
        public SoulseekFileFactory(FileService fileService)
        {
            Files = fileService;
        }

        private FileService Files { get; }
        private ILogger Log { get; } = Serilog.Log.ForContext<SoulseekFileFactory>();

        /// <summary>
        ///     Creates an instance of <see cref="Soulseek.File"/> from the given path.
        /// </summary>
        /// <param name="filename">The fully qualified path to the file.</param>
        /// <param name="maskedFilename">The masked filename.</param>
        /// <returns>The created instance.</returns>
        public File Create(string filename, string maskedFilename)
        {
            var code = 1;
            var size = Files.ResolveFileInfo(filename).Length;
            var extension = Path.GetExtension(filename).TrimStart('.').ToLowerInvariant();
            List<FileAttribute> attributeList = default;

            if (SupportedExtensions.Contains(extension))
            {
                attributeList = new List<FileAttribute>();
                TagLib.File file = default;

                try
                {
                    file = TagLib.File.Create(filename, TagLib.ReadStyle.Average | TagLib.ReadStyle.PictureLazy);

                    // try to mimic the behavior of existing clients by providing attributes selectively and in a specific order,
                    // depending on whether files use a lossless or lossy codec. lossless files should have BitsPerSample, while lossy
                    // will not. this may not be the best way to determine this.
                    bool isLossless = file.Properties.BitsPerSample > 0;

                    if (!isLossless)
                    {
                        // per Nicotine+ docs, Soulseek NS, Nicotine+, Museek+, SoulSeeX all send bit rate, length, then VBR
                        attributeList.Add(new FileAttribute(FileAttributeType.BitRate, file.Properties.AudioBitrate));
                        attributeList.Add(new FileAttribute(FileAttributeType.Length, (int)file.Properties.Duration.TotalSeconds));
                        attributeList.Add(new FileAttribute(FileAttributeType.VariableBitRate, IsVBR(file) ? 1 : 0));
                    }
                    else
                    {
                        // SoulseekQt 2015-6-12 and later provides the length, sample rate and bit depth for lossless files
                        // bitrate can be deduced from this information
                        attributeList.Add(new FileAttribute(FileAttributeType.Length, (int)file.Properties.Duration.TotalSeconds));
                        attributeList.Add(new FileAttribute(FileAttributeType.SampleRate, file.Properties.AudioSampleRate));
                        attributeList.Add(new FileAttribute(FileAttributeType.BitDepth, file.Properties.BitsPerSample));
                    }
                }
                catch (Exception ex)
                {
                    Log.Debug("Failed to read metadata from file '{Filename}'; the file is an unsupported format or may be corrupt ({ExceptionType})", filename, ex.GetType().Name);
                }
                finally
                {
                    file?.Dispose();
                }
            }

            return new File(code, maskedFilename, size, extension, attributeList);
        }

        private bool IsVBR(TagLib.File file)
        {
            static bool HasVBRIHeader(TagLib.Mpeg.AudioHeader header) => header.VBRIHeader.Present && header.VBRIHeader.TotalSize > 0;
            static bool HasXingHeader(TagLib.Mpeg.AudioHeader header) => header.XingHeader.Present && header.XingHeader.TotalSize > 0;

            return file.Properties.Codecs.Any(c =>
                (c is TagLib.Mpeg.AudioHeader h && (HasVBRIHeader(h) || HasXingHeader(h)))
                || c is TagLib.Aac.AudioHeader
                || c is TagLib.Ogg.Codec);
        }
    }
}