:- module(download_video, [ save_video_stream/2 % +StreamURL, +File ]). :- use_module(library(http/http_open)). :- use_module(library(xpath)). :- use_module(library(thread_pool)). :- thread_pool_create(stream_download_pool, 5, []). %% save_video_stream(+StreamURL, +File) % % Download video stream and save it to a local file. save_video_stream(URL, File) :- ( exists_file(File) -> debug(stream_download, 'file already exists', []) ; thread_create_in_pool(stream_download_pool, download_video_stream(URL, File), _, []) ). %% download_video_stream(+StreamLocation, +SrcFile) % % Download video at StreamLocation to SrcFile download_video_stream(Stream, File0) :- Prog = path(mplayer), win_relative_path(File, File0), debug(stream_download, 'Downloading video stream ...', []), process_create(Prog, [ '-dumpstream', Stream, '-dumpfile', file(File) ], [ stderr(pipe(Error)), stdout(null), process(PID) ]), read_stream_to_codes(Error, Messages), close(Error), process_wait(PID, Status), ( Status == exit(0) -> debug(stream_download, 'stream: ok', []) ; debug(stream_download, 'stream: status ~w: ~s', [Status, Messages]), %atom_codes(Text, Messages), catch(delete_file(File), _, true) %throw(error(download_video_stream(Status, Text), _)) ). %% win_relative_path(+Path, -RelativePath) is det. % % If Path is an absolute filename, translate it into a relative % one to avoid too long commandlines on Windows. win_relative_path(Path, Local) :- current_prolog_flag(windows, true), is_absolute_file_name(Path), !, relative_path(Path, Local). win_relative_path(Path, Path). %% relative_path(+Path, -Relative) % % Transform an absolute path into a relative one to overcome % limitations of the Windows commandline handling. relative_path(Path, RelPath) :- working_directory(PWD, PWD), relative_path(Path, PWD, RelPath), !. relative_path(Path, Path). relative_path(Path, RelTo, RelPath) :- concat_atom(PL, /, Path), concat_atom(RL, /, RelTo), delete_common_prefix(PL, RL, PL1, PL2), to_dot_dot(PL2, DotDot, PL1), concat_atom(DotDot, /, RelPath). delete_common_prefix([H|T01], [H|T02], T1, T2) :- !, delete_common_prefix(T01, T02, T1, T2). delete_common_prefix(T1, T2, T1, T2). to_dot_dot([], Tail, Tail). to_dot_dot([_], Tail, Tail) :- !. to_dot_dot([_|T0], ['..'|T], Tail) :- to_dot_dot(T0, T, Tail).