{"record":{"id":"52dac2dc7a72ef56","repo":"nilaoda/N_m3u8DL-RE","slug":"download-first-segment-failed","errorCode":null,"errorMessage":"Download first segment failed!","messagePattern":"Download first segment failed!","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"src/N_m3u8DL-RE/DownloadManager/SimpleDownloadManager.cs","lineNumber":236,"sourceCode":"            }\n        }\n\n        // 计算填零个数\n        var pad = \"0\".PadLeft(segments.Count().ToString().Length, '0');\n\n        // 下载第一个分片\n        if (!readInfo || StreamExtractor.ExtractorType == ExtractorType.MSS)\n        {\n            var seg = segments.First();\n            segments = segments.Skip(1);\n\n            var index = seg.Index;\n            var path = Path.Combine(tmpDir, index.ToString(pad) + $\".{streamSpec.Extension ?? \"clip\"}.tmp\");\n            var result = await Downloader.DownloadSegmentAsync(seg, path, speedContainer, headers);\n            FileDic[seg] = result;\n            if (result is not { Success: true })\n            {\n                throw new Exception(\"Download first segment failed!\");\n            }\n            task.Increment(1);\n            if (result is { Success: true })\n            {\n                // 修复MSS init\n                if (StreamExtractor.ExtractorType == ExtractorType.MSS)\n                {\n                    var processor = new MSSMoovProcessor(streamSpec);\n                    var header = processor.GenHeader(File.ReadAllBytes(result.ActualFilePath));\n                    await File.WriteAllBytesAsync(FileDic[streamSpec.Playlist!.MediaInit!]!.ActualFilePath, header);\n                    if (seg.IsEncrypted && DownloaderConfig.MyOptions.MP4RealTimeDecryption && !string.IsNullOrEmpty(currentKID))\n                    {\n                        // 需要重新解密init\n                        var enc = FileDic[streamSpec.Playlist!.MediaInit!]!.ActualFilePath;\n                        var dec = Path.Combine(Path.GetDirectoryName(enc)!, Path.GetFileNameWithoutExtension(enc) + \"_dec\" + Path.GetExtension(enc));\n                        var dResult = await MP4DecryptUtil.DecryptAsync(decryptEngine, decryptionBinaryPath, DownloaderConfig.MyOptions.Keys, enc, dec, currentKID);\n                        if (dResult)\n                        {","sourceCodeStart":218,"sourceCodeEnd":254,"githubUrl":"https://github.com/nilaoda/N_m3u8DL-RE/blob/e113dee70c924ee08dae5460624909b04d84cb76/src/N_m3u8DL-RE/DownloadManager/SimpleDownloadManager.cs#L218-L254","documentation":"SimpleDownloadManager.DownloadStreamAsync throws when the first media segment download fails (Success != false check on the DownloadResult). It is a hard stop because subsequent segment handling (indexing, MSS init repair) depends on the first segment.","triggerScenarios":"Downloader.DownloadSegmentAsync returns a result with Success == false for the first segment (seg.Index == first) — HTTP error, timeout, disk write failure at the tmp path.","commonSituations":"Segment URL expired or CDN 403/404, network interruption at download start, disk full in tmp directory, wrong extension handling causing path errors.","solutions":["Retry the command — first failure is often transient network error","Check the first segment URL with curl (signed URL may have expired)","Ensure the temp directory has free disk space and write permissions","Re-fetch the playlist to get fresh segment URLs"],"exampleFix":null,"handlingStrategy":"retry","validationCode":"// check disk and first-segment URL before downloading\nif (new DriveInfo(tmpDir).AvailableFreeSpace < 500_000_000) throw new IOException(\"low disk space\");","typeGuard":"static bool IsSuccess(DownloadResult r) => r is { Success: true };","tryCatchPattern":"try { await DownloadStreamAsync(...); }\ncatch (Exception ex) when (ex.Message == \"Download first segment failed!\")\n{\n    logger.Warn(\"first segment failed; refreshing playlist and retrying\");\n    playlist = await RefreshPlaylistAsync();\n    await DownloadStreamAsync(...);\n}","preventionTips":["Re-fetch the playlist close to download time so segment URLs are fresh","Keep enough free disk space in the temp directory","Check first-segment URL reachability when downloads consistently fail at start"],"tags":["csharp","hls","dash","download","segment"],"backgroundTag":"http-request-failed","analyzedSha":"e113dee70c924ee08dae5460624909b04d84cb76","analyzedAt":"2026-09-13T02:43:21.078Z","contentChangedAt":"2026-09-13T02:43:21.078Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}