总体流程
下载一个媒体文件的流程
1、初始化
2、根据URL下载m3u8文件(即PlayList文件)
3、判断m3u8文件的类型,是Master PlayList还是Media PlayList
4、如果是Master PlayList,那么分析这个PlayList的内容,并选择一个合适的Media PlayList,注意这一步只是分析Master PlayList的内容,并没有下载Media PlayList
5、处理Media PlayList,因为步骤3下载的可能就是一个Media PlayList,因此,在处理之前先把旧的内容释放掉,然后重新下载Media PlayList,再分析Media PlayList里面的内容
6、Media PlayList分析完成之后,就得到TS媒体文件的信息了
7、根据TS媒体文件信息,下载TS文件
8、清理
代码实现
// 下载一个视频
HRESULT HLSDownloader::download_hls_video(std::string surl,std::string filename,bool livestreaming){
curl_global_init(CURL_GLOBAL_ALL);
av_register_all(); // ffmpge的函数,注册所有的编解码器
const char * url = surl.c_str();
char *hlsfile_source;
struct hls_media_playlist media_playlist;
// 从服务器上下载m3u8文件(Master PlayList或者Media PlayList)
if (get_data_from_url(url, &hlsfile_source, NULL, STRING,m_strUserAgent) == 0) {
Log(LogID_MMHLSDownloader, LogLevel_Error, __FUNCTION__,
"");
MSG_ERROR("No result from server.\n");
return E_FAIL;
}
// 获取m3u8文件的类型(是Master PlayList还是Media PlayList)
int playlist_type = get_playlist_type(hlsfile_source);
// 如果是Master PlayList
if (playlist_type == MASTER_PLAYLIST) {
struct hls_master_playlist master_playlist;
master_playlist.source = hlsfile_source;
master_playlist.url = strdup(url);
// 读取Master PlayList中的内容并分析
if (handle_hls_master_playlist(&master_playlist)) {
return E_FAIL;
}
int max = 0;
for (int i = 0; i < master_playlist.count; i++) {
if (master_playlist.media_playlist[i].bitrate > master_playlist.media_playlist[max].bitrate) {
max = i;
}
}
int quality_choice = max;
// 选取一个Media PlayList
media_playlist = master_playlist.media_playlist[quality_choice];
master_playlist_cleanup(&master_playlist);
} else if (playlist_type == MEDIA_PLAYLIST) {
// 如果是Media PlayList
media_playlist.bitrate = 0;
media_playlist.url = strdup(url);
} else {
return E_FAIL;
}
// 处理Media PlayList
if (handle_hls_media_playlist(&media_playlist,m_strUserAgent)) {
return E_FAIL;
}
if (media_playlist.encryption) {
Log(LogID_MMHLSDownloader, LogLevel_Info, __FUNCTION__,
"HLS Stream is %s encrypted.",
media_playlist.encryptiontype == ENC_AES128 ? "AES-128" : "SAMPLE-AES");
}
Log(LogID_MMHLSDownloader, LogLevel_Info, __FUNCTION__,
"Media Playlist parsed successfully");
// 下载HLS视频
if (download_hls(&media_playlist,livestreaming,m_iMaxSize,filename.c_str(),m_strUserAgent,true)) {
Log(LogID_MMHLSDownloader, LogLevel_Error, __FUNCTION__,
"Download HLS Failed");
return E_FAIL;
}
media_playlist_cleanup(&media_playlist);
curl_global_cleanup();
return S_OK;
}