diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs
index 05a7b7896f..414488853f 100644
--- a/MediaBrowser.Controller/Entities/BaseItem.cs
+++ b/MediaBrowser.Controller/Entities/BaseItem.cs
@@ -1087,12 +1087,7 @@ namespace MediaBrowser.Controller.Entities
return 1;
}).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
- .ThenByDescending(i =>
- {
- var stream = i.VideoStream;
-
- return stream is null || stream.Width is null ? 0 : stream.Width.Value;
- })
+ .ThenByDescending(i => i, new MediaSourceWidthComparator())
.ToList();
}
diff --git a/MediaBrowser.Controller/Entities/MediaSourceWidthComparator.cs b/MediaBrowser.Controller/Entities/MediaSourceWidthComparator.cs
new file mode 100644
index 0000000000..0224577a4c
--- /dev/null
+++ b/MediaBrowser.Controller/Entities/MediaSourceWidthComparator.cs
@@ -0,0 +1,56 @@
+using System;
+using System.Collections.Generic;
+using System.Runtime.Intrinsics.X86;
+using MediaBrowser.Model.Dto;
+
+namespace MediaBrowser.Controller.Entities;
+
+///
+/// Compare MediaSource of the same file by Video width .
+///
+public class MediaSourceWidthComparator : IComparer
+{
+ ///
+ public int Compare(MediaSourceInfo? x, MediaSourceInfo? y)
+ {
+ if (x is null && y is null)
+ {
+ return 0;
+ }
+
+ if (x is null)
+ {
+ return -1;
+ }
+
+ if (y is null)
+ {
+ return 1;
+ }
+
+ if (string.Equals(x.Path, y.Path, StringComparison.OrdinalIgnoreCase))
+ {
+ if (x.VideoStream is null && y.VideoStream is null)
+ {
+ return 0;
+ }
+
+ if (x.VideoStream is null)
+ {
+ return -1;
+ }
+
+ if (y.VideoStream is null)
+ {
+ return 1;
+ }
+
+ var xWidth = x.VideoStream.Width ?? 0;
+ var yWidth = y.VideoStream.Width ?? 0;
+
+ return xWidth - yWidth;
+ }
+
+ return 0;
+ }
+}