-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: HLS 세그먼트를 앞부분부터 잘라서 로드시킬 수 있는 커스텀 리소스 로더 구현 #330
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
// | ||
// URL+.swift | ||
// Layover | ||
// | ||
// Created by 김인환 on 12/14/23. | ||
// Copyright © 2023 CodeBomber. All rights reserved. | ||
// | ||
|
||
import Foundation | ||
|
||
extension URL { | ||
func changeScheme(to: String) -> URL { | ||
var components = URLComponents(url: self, resolvingAgainstBaseURL: false) | ||
components?.scheme = to | ||
return components?.url ?? self | ||
} | ||
|
||
var customHLS_URL: URL { | ||
changeScheme(to: "lhls") | ||
} | ||
|
||
var originHLS_URL: URL { | ||
changeScheme(to: "https") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
65 changes: 65 additions & 0 deletions
65
iOS/Layover/Layover/Services/HLSResourceLoader/HLSAssetResourceLoaderDelegate.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
// | ||
// HLSAssetResourceLoaderDelegate.swift | ||
// Layover | ||
// | ||
// Created by 김인환 on 12/14/23. | ||
// Copyright © 2023 CodeBomber. All rights reserved. | ||
// | ||
|
||
import Foundation | ||
import AVFoundation | ||
|
||
class HLSAssetResourceLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate { | ||
|
||
// MARK: - Properties | ||
|
||
let resourceLoader: ResourceLoader | ||
|
||
// MARK: - Initializer | ||
|
||
init(resourceLoader: ResourceLoader) { | ||
self.resourceLoader = resourceLoader | ||
} | ||
|
||
// MARK: - Delegate Methods | ||
|
||
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, | ||
shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { | ||
loadRequestedResource(loadingRequest) | ||
} | ||
|
||
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, | ||
shouldWaitForRenewalOfRequestedResource renewalRequest: AVAssetResourceRenewalRequest) -> Bool { | ||
loadRequestedResource(renewalRequest) | ||
} | ||
|
||
// MARK: - Methods | ||
|
||
// 공통으로 처리 | ||
func loadRequestedResource(_ loadingRequest: AVAssetResourceLoadingRequest) -> Bool { | ||
guard let url = loadingRequest.request.url?.originHLS_URL else { return false } | ||
|
||
if url.pathExtension.contains("ts") { // ts 파일은 리디렉션 시킨다. | ||
loadingRequest.redirect = URLRequest(url: url) | ||
loadingRequest.response = HTTPURLResponse(url: url, | ||
statusCode: 302, | ||
httpVersion: nil, | ||
headerFields: nil) | ||
loadingRequest.finishLoading() | ||
} else { | ||
Task { | ||
guard let data = await resourceLoader.loadResource(from: url) else { | ||
loadingRequest.finishLoading(with: NSError(domain: "Failed to load resource from \(url.absoluteString)", | ||
code: 0, | ||
userInfo: nil)) | ||
return | ||
} | ||
|
||
loadingRequest.dataRequest?.respond(with: data) | ||
loadingRequest.finishLoading() | ||
} | ||
} | ||
|
||
return true | ||
} | ||
} |
84 changes: 84 additions & 0 deletions
84
iOS/Layover/Layover/Services/HLSResourceLoader/HLSSliceResourceLoader.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
// | ||
// HLSResourceLoader.swift | ||
// Layover | ||
// | ||
// Created by 김인환 on 12/14/23. | ||
// Copyright © 2023 CodeBomber. All rights reserved. | ||
// | ||
|
||
import Foundation | ||
import OSLog | ||
|
||
protocol ResourceLoader { | ||
func loadResource(from url: URL) async -> Data? | ||
} | ||
|
||
// 앞부분부터 원하는 duration만큼 잘라서 load시켜주는 Resource Loader | ||
final class HLSSliceResourceLoader: ResourceLoader { | ||
|
||
enum M3U8Tag: String { | ||
case extm3u = "#EXTM3U" // m3u8 파일의 시작 | ||
case extend = "#EXT-X-ENDLIST" // 마지막 태그 | ||
case extinf = "#EXTINF:" // 재생시간 -> 미디어 m3u8 파일에 포함 | ||
case extxstreaminf = "#EXT-X-STREAM-INF" // 마스터 m3u8 파일 | ||
} | ||
|
||
// MARK: - Properties | ||
|
||
private let session: URLSession | ||
|
||
// MARK: - Initializer | ||
|
||
init(session: URLSession = URLSession(configuration: .default)) { | ||
self.session = session | ||
} | ||
|
||
// MARK: - ResourceLoader | ||
|
||
func loadResource(from url: URL) async -> Data? { | ||
let urlRequest = URLRequest(url: url.originHLS_URL) // 원래 url scheme 으로 변경 | ||
|
||
guard let (data, response) = try? await session.data(for: urlRequest), | ||
let httpResponse = response as? HTTPURLResponse, | ||
(200...399) ~= httpResponse.statusCode else { | ||
os_log(.error, log: .data, "Failed to load resource from %{public}@", url.absoluteString) | ||
return nil | ||
} | ||
|
||
guard let m3u8Playlist = String(data: data, encoding: .utf8) else { | ||
os_log(.error, log: .data, "Failed to decode data to String") | ||
return nil | ||
} | ||
|
||
guard isMediaM3U8(m3u8Playlist) else { return data } | ||
return sliceM3U8Playlist(m3u8Playlist, duration: 4).data(using: .utf8) ?? data // 3초보다는 약간 여유있게 잡는다. | ||
} | ||
|
||
// MARK: - Methods | ||
|
||
private func isMediaM3U8(_ m3u8Playlist: String) -> Bool { | ||
m3u8Playlist.contains(M3U8Tag.extinf.rawValue) | ||
} | ||
|
||
// m3u8 미디어 플레이리스트를 받아서 duration만큼 잘라서 반환 | ||
private func sliceM3U8Playlist(_ m3u8Playlist: String, duration: TimeInterval) -> String { | ||
var duration = duration | ||
var playlist = m3u8Playlist.components(separatedBy: M3U8Tag.extinf.rawValue) | ||
.compactMap { | ||
if $0.contains(M3U8Tag.extm3u.rawValue) { return $0 } // 시작부분 | ||
else if let tsDuration = $0.components(separatedBy: ",").compactMap({ Double($0) }).first, | ||
duration > .zero { | ||
duration -= tsDuration | ||
return $0 | ||
} else { | ||
return nil | ||
} | ||
}.joined(separator: M3U8Tag.extinf.rawValue) | ||
|
||
if !playlist.contains(M3U8Tag.extend.rawValue) { | ||
playlist.append("\n\(M3U8Tag.extend.rawValue)") | ||
} | ||
|
||
return playlist | ||
} | ||
Comment on lines
+64
to
+83
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pdf로만 봤었는데 m3u8파일 내부를 까서 시작 부분부터 재생할 duration까지만 ts 세그먼트를 합치는 고런 로직이군요.. 좋습니당
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
맞아요 간단한...3초 3겹살...