def test_encrypted_hls(self): video = ffmpeg_streaming.input(self.src_video) hls_obj = video.hls(Formats.h264()) hls_obj.encryption(os.path.join(self.src_dir, 'enc.key'), 'https://www.aminyazdanpanah.com/enc.key') self.assertIsNotNone(hls_obj.options.get('hls_key_info_file', None)) with open(hls_obj.options.get('hls_key_info_file', None)) as key_info: key_info = key_info.readlines() self.assertEqual(key_info[0].replace('\n', ''), 'https://www.aminyazdanpanah.com/enc.key') self.assertEqual(key_info[1].replace('\n', ''), os.path.join(self.src_dir, 'enc.key')) hls_obj.auto_generate_representations() hls_obj.output(os.path.join(self.src_dir, 'encrypted_hls', 'test.m3u8'), stderr=False) with open(os.path.join(self.src_dir, 'fixture_test.m3u8')) as test_m3u8: expected_m3u8 = test_m3u8.read() with open(os.path.join(self.src_dir, 'encrypted_hls', 'test.m3u8')) as test_m3u8: actual_encrypted_m3u8 = test_m3u8.read() self.assertEqual(actual_encrypted_m3u8, expected_m3u8)
def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', required=True, help='The path to the video file (required).') parser.add_argument('-o', '--output', default=None, help='The output to write files.') parser.add_argument('-fmp4', '--fragmented', default=False, help='Fragmented mp4 output') parser.add_argument('-k', '--key', default=None, help='The full pathname of the file where a random key will be ' 'created (required). Note: The path of the key should be ' 'accessible from your website(e.g. ' '"/var/www/public_html/keys/enc.key")') parser.add_argument('-u', '--url', default=None, help='A URL (or a path) to access the key on your website (' 'required)') parser.add_argument('-krp', '--key_rotation_period', default=0, help='Use a different key for each set of ' 'segments, rotating to a new key after this ' 'many segments.') args = parser.parse_args() video = ffmpeg_streaming.input(args.input) hls = video.hls(Formats.h264()) hls.auto_generate_representations() if args.fragmented: hls.fragmented_mp4() if args.key is not None and args.url is not None: hls.encryption(args.key, args.url, args.key_rotation_period) hls.output(args.output, monitor=monitor)
def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', required=True, help='The path to the video file (required).') parser.add_argument('-o', '--output', default=None, help='The output to write files.') parser.add_argument('-hls', '--hls_output', default=False, help='publish hls playlists') args = parser.parse_args() video = ffmpeg_streaming.input(args.input) dash = video.dash(Formats.h264()) dash.auto_generate_representations() if args.hls_output: dash.generate_hls_playlist() dash.output(args.output, monitor=monitor)
def stop(request): video = ffmpeg_streaming.input('') hls = video.hls(Formats.h264()) hls.auto_generate_representations() hls.output('/app/static/stream/hls.m3u8') return HttpResponse('<h1>Stream is stopped</h1>')
def play_videos(): page_location = request.args.get("page-location") page_location = page_location if page_location else "" current_path = get_path(basepath, page_location) video = ffmpeg_streaming.input(current_path) dash = video.dash(Formats.h264()) dash.auto_generate_representations() dash.output(f"{basepath}/representation.mpd") details = {"path": f"/videos/representation.mpd", "type": "video/mp4"} return render_template("video.html", details=details)
def videomedia(title, templocation): video = ffmpeg_streaming.input(templocation) os.makedirs(os.path.join("deployproxy", "media", title)) hls = video.hls(Formats.h264(), hls_time=3) os.makedirs("keys/" + title) hls.encryption(os.path.join("keys", title, "key"), "/getkey/?media=" + title) hls.auto_generate_representations() hls.output(os.path.join("deployproxy", "media", title, "media.m3u8")) os.remove(templocation)
def test_dash(self): video = ffmpeg_streaming.input(self.src_video) dash_obj = video.dash(Formats.hevc()) self.assertIsInstance(dash_obj, DASH) self.assertEqual(dash_obj.media.input, self.src_video) dash_obj.auto_generate_representations() dash_obj.output(os.path.join(self.src_dir, 'dash', 'test.mpd'), stderr=False) with open(os.path.join(self.src_dir, 'dash', 'test.mpd')) as test_mpd: actual_mpd = test_mpd.readlines() self.assertEqual(actual_mpd[0].replace('\n', ''), '<?xml version="1.0" encoding="utf-8"?>') self.assertEqual(actual_mpd[1].replace('\n', ''), '<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
def download_stream(link: str, out_path: str = "./dl/") -> bool: video = ffmpeg_streaming.input(link) hls = video.hls(Formats.h264()) _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls = video.hls(Formats.h264(), hls_time=3600) hls.flags('delete_segments') hls.representations(_720p) hls.output("/mnt/c/Users/anael/OneDrive/projets/streamFinder/dl/test.mp4") return True
def convert_video_to_hls(arg): path_root = settings.MEDIA_ROOT + arg.title if not os.path.exists(path_root): os.makedirs(path_root) video = ffmpeg_streaming.input( str(settings.MEDIA_ROOT + arg.video_file.name)) save_to = str(path_root + '/key') # A URL (or a path) to access the key on your website url = settings.MEDIA_URL + arg.title + '/key' # or url = '/"PATH TO THE KEY DIRECTORY"/key'; hls = video.hls(Formats.h264()) hls.encryption(save_to, url) hls.auto_generate_representations() hls.output(str(path_root + '/hls.m3u8'))
def change_it(fn): video = ffmpeg_streaming.input('../simulated_server_storage/' + fn) def monitor(ffmpeg, duration, time_, time_left, process): per = round(time_ / duration * 100) sys.stdout.write( "\rTranscoding...(%s%%) %s left [%s%s]" % (per, datetime.timedelta(seconds=int(time_left)), '#' * per, '-' * (100 - per))) sys.stdout.flush() hls = video.hls(Formats.h264()) thumbnail.extract(fn) hls.auto_generate_representations() os.mkdir('static/media/' + fn[:-4:1]) hls.output('static/media/' + fn[:-4:1] + '/' + fn[:-4:1] + '.m3u8', monitor=monitor)
def async_convert_video_and_extract_meta_data(id): """ Converts the uploaded video into 480 mp4 files that can be streamed using the .m38u file. The duration of the files is then extracted from the file and resaved in the Video object """ print('async convert video running') print(id) instance = Video.objects.get(id=id) video_path = instance.url.path if instance.url.storage.exists(instance.url.name): video = ffmpeg_streaming.input(video_path) hls = video.hls(Formats.h264()) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) hls.representations(_480p) hls.output() duration_in_seconds = int(float(FFProbe(instance.url.path).streams().video().get('duration', 60))) minutes = int(time.strftime('%M', time.gmtime(duration_in_seconds))) Video.objects.filter(pk=instance.pk).update(duration=minutes if minutes > 1 else 1)
def test_hls(self): video = ffmpeg_streaming.input(self.src_video) hls_obj = video.hls(Formats.h264()) self.assertIsInstance(hls_obj, HLS) self.assertEqual(hls_obj.media.input, self.src_video) hls_obj.representations(Representation(Size(256, 144), Bitrate(102400))) rep_1 = hls_obj.reps[0] self.assertIsInstance(rep_1, Representation) self.assertEqual(str(rep_1.size), '256x144') self.assertEqual(rep_1.bitrate.video, '100k') hls_obj.auto_generate_representations() reps = list(hls_obj.reps) self.assertEqual(len(reps), 3) for rep_ in reps: self.assertIsInstance(rep_, Representation) self.assertEqual(str(reps[0].size), '480x270') self.assertEqual(reps[0].bitrate.video, '176k') self.assertEqual(str(reps[1].size), '426x240') self.assertEqual(reps[1].bitrate.video, '88k') self.assertEqual(str(reps[2].size), '256x144') self.assertEqual(reps[2].bitrate.video, '71k') hls_obj.output(os.path.join(self.src_dir, 'hls', 'test.m3u8')) with open(os.path.join(self.src_dir, 'fixture_test.m3u8')) as test_m3u8: expected_m3u8 = test_m3u8.read() with open(os.path.join(self.src_dir, 'hls', 'test.m3u8')) as test_m3u8: actual_m3u8 = test_m3u8.read() self.assertEqual(actual_m3u8, expected_m3u8) with open(os.path.join(self.src_dir, 'hls', 'test_270p.m3u8')) as test_m3u8: actual_270_m3u8 = test_m3u8.readlines() self.assertEqual(actual_270_m3u8[0].replace('\n', ''), '#EXTM3U') self.assertEqual(actual_270_m3u8[1].replace('\n', ''), '#EXT-X-VERSION:3') self.assertEqual(actual_270_m3u8[2].replace('\n', ''), '#EXT-X-ALLOW-CACHE:YES')
def upload(request): if request.method == "POST": uploaded_file = request.FILES['myFile'] name_array = uploaded_file.name.split('.') uploaded_file.name = name_array[0] song = Song.objects.create(title=request.POST.get('title'), description=request.POST.get('description'), artist=request.POST.get('artist'), path=f'{uploaded_file.name}') song.save() song = Song.objects.all().last() song_id = song.id os.mkdir(f'{BASE_DIR}\\media\\{song_id}\\') fs = FileSystemStorage(BASE_DIR) fs.save(uploaded_file.name, uploaded_file) video = ffmpeg_streaming.input(f'{BASE_DIR}\\{uploaded_file.name}') dash = video.dash(Formats.h264()) dash.auto_generate_representations() dash.output(f'{BASE_DIR}\\media\\{song_id}\\{uploaded_file.name}.mpd') os.remove(f'{BASE_DIR}\\{uploaded_file.name}') return HttpResponse("uploaded successfully") return render(request, 'videos/upload.html')
def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', required=True, help='The path to the video file (required).') parser.add_argument('-o', '--output', default=None, help='The output to write files.') parser.add_argument( '-k', '--key', default=None, help='The full pathname of the file where a random key will ' 'be created (required). Note: The path of the key should' 'be accessible from your website(e.g. ' '"/var/www/public_html/keys/enc.key")') parser.add_argument( '-u', '--url', default=None, help='A URL (or a path) to access the key on your website (' 'required)') args = parser.parse_args() video = ffmpeg_streaming.input(args.input) hls = video.hls(Formats.h264()) hls.auto_generate_representations() if args.key is not None and args.url is not None: hls.encryption(args.key, args.url, 10) hls.output(args.output, monitor=monitor)
data = json.loads(response.content) path_lesson = path_section + '/{}_{}'.format( index_lesson, str(data['LessonTitle']).replace('.', '_').replace('/', '') ) if not os.path.exists(path_lesson): os.makedirs(path_lesson) if data['Step']['VideoId']: file_name_video = '{}/{}'.format(path_lesson, data['Step']['VideoName']) if len(data['Step']['VideoId']) >= 10: video_src = "https://techmaster.vn/app/video-new/stream-video/" + data['Step']['VideoId'] + ".m3u8" else: video_src = "https://techmaster.vn/video/stream-video/" + data['Step']['VideoId'] + ".m3u8" video = ffmpeg_streaming.input(video_src) stream = video.stream2file(Formats.h264()) stream.output(file_name_video) file_name_doc = '{}/{}.html'.format(path_lesson, str(data['LessonTitle']).replace('.', '_').replace('/', '')) f = open(file_name_doc, 'w') if data['Step']['VideoId']: f.write(''' <video width="320" height="240" controls> <source src="{}" type="video/mp4"> </video> '''.format(data['Step']['VideoName'])) f.write(data['Step']['Text']) f.close()
import ffmpeg_streaming from ffmpeg_streaming import Formats video = ffmpeg_streaming.input('video.mp4') from ffmpeg_streaming import Formats, Bitrate, Representation, Size _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls = video.hls(Formats.h264()) hls.representations(_360p, _480p, _720p) hls.output('./flask-hls-demo/video/hls.m3u8')
from ffmpeg_streaming import Formats, Bitrate, Representation, Size, input video = input('rtsp://localhost:8554/live'); _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) hls = video.hls(Formats.h264(), hls_list_size=5, hls_time=2) hls.flags('delete_segments') hls.representations(_480p) hls.output('./output/hls1.m3u8')
import ffmpeg_streaming import sys import datetime import logging import os from ffmpeg_streaming import Formats, Bitrate, Representation, Size, GCS, CloudManager logging.basicConfig(filename='streaming.log', level=logging.NOTSET, format='[%(asctime)s] %(levelname)s: %(message)s') os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/vignesh/Vicky/Code/Transcoder/python_transcode/presales.json" gcs = GCS() save_to_gcs = CloudManager().add(gcs, bucket_name="viki_trans_py", folder="transcoded_video") video = ffmpeg_streaming.input('/Users/vignesh/Vicky/Code/Transcoder/python_transcode/sample.mp4') def monitor(ffmpeg, duration, time_, time_left, process): per = round(time_ / duration * 100) sys.stdout.write( "\rTranscoding...(%s%%) %s left [%s%s]" % (per, datetime.timedelta(seconds=int(time_left)), '#' * per, '-' * (100 - per)) ) sys.stdout.flush() _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls = video.hls(Formats.h264()) hls.representations(_360p, _480p, _720p) hls.output(clouds=save_to_gcs, monitor=monitor)
import ffmpeg_streaming video_path = "C:\\Users\\Admin\\Downloads\\Video\\people.mp4" video = ffmpeg_streaming.input(video_path) from ffmpeg_streaming import Formats, Bitrate, Representation, Size _144p = Representation(Size(256, 144), Bitrate(95 * 1024, 64 * 1024)) _240p = Representation(Size(426, 240), Bitrate(150 * 1024, 94 * 1024)) _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) _1080p = Representation(Size(1920, 1080), Bitrate(4096 * 1024, 320 * 1024)) _2k = Representation(Size(2560, 1440), Bitrate(6144 * 1024, 320 * 1024)) _4k = Representation(Size(3840, 2160), Bitrate(17408 * 1024, 320 * 1024)) dash = video.dash(Formats.h264()) dash.representations(_144p, _240p, _360p, _480p, _720p, _1080p, _2k, _4k) dash.output('dash.mpd')
import ffmpeg_streaming from ffmpeg_streaming import Formats, Bitrate, Representation, Size _144p = Representation(Size(256, 144), Bitrate(95 * 1024, 64 * 1024)) _240p = Representation(Size(426, 240), Bitrate(150 * 1024, 94 * 1024)) _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) #video = ffmpeg_streaming.input('./bunny.mp4') video = ffmpeg_streaming.input('./test_input.mp4') dash = video.dash(ffmpeg_streaming.Formats.h264()) #dash.auto_generate_representations() dash.representations(_144p, _240p, _360p, _480p, _720p) dash.output('./dash.mpd')
def convertStreamToMkv(httpPathToM3U8, outputNameAndPath): video = ffmpeg_streaming.input(httpPathToM3U8) stream = video.stream2file(ffmpeg_streaming.Formats.h264()) stream.output(outputNameAndPath)
import ffmpeg_streaming video = ffmpeg_streaming.input('D:\WebVideoPlayerDjango\WebVideoPlayer\media\Borat.Subsequent.Moviefilm.2020.WEBRip.x264-ION10.mp4') from ffmpeg_streaming import Formats import sys import datetime def monitor(ffmpeg, duration, time_, time_left, process): """ Handling proccess. Examples: 1. Logging or printing ffmpeg command logging.info(ffmpeg) or print(ffmpeg) 2. Handling Process object if "something happened": process.terminate() 3. Email someone to inform about the time of finishing process if time_left > 3600 and not already_send: # if it takes more than one hour and you have not emailed them already ready_time = time_left + time.time() Email.send( email='*****@*****.**', subject='Your video will be ready by %s' % datetime.timedelta(seconds=ready_time), message='Your video takes more than %s hour(s) ...' % round(time_left / 3600) ) already_send = True 4. Create a socket connection and show a progress bar(or other parameters) to your users Socket.broadcast( address=127.0.0.1 port=5050
import ffmpeg_streaming capture = ffmpeg_streaming.input('CAMERA NAME OR SCREEN NAME', capture=True)
import ffmpeg_streaming from ffmpeg_streaming import Formats, Bitrate, Representation, Size import sys def monitor(ffmpeg, duration, time_): per = round(time_ / duration * 100) sys.stdout.write("\rTranscoding...(%s%%) [%s%s]" % (per, '#' * per, '-' * (100 - per))) sys.stdout.flush() video = ffmpeg_streaming.input('rtsp://freja.hiof.no:1935/rtplive/_definst_/hessdalen03.stream') _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls_stream = video.hls(Formats.h264(), hls_list_size = 10, hls_time = 60) hls_stream.representations(_480p) hls_stream.output('/var/media/hls_outputs.m3u8')
import sys import ffmpeg_streaming from ffmpeg_streaming import Formats input_path = sys.argv[1] video = ffmpeg_streaming.input(input_path) # from ffmpeg_streaming import Formats # dash = video.dash(Formats.h264()) # dash.auto_generate_representations() # dash.output('/var/media/dash.mpd') hls = video.hls(Formats.h264()) hls.auto_generate_representations() # hls.output('/var/media/hls.m3u8') from ffmpeg_streaming import S3, CloudManager s3 = S3(aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name='us-east-1') save_to_s3 = CloudManager().add(s3, bucket_name="fifteen.pm") hsl.output(clouds=save_to_s3) dash.output(clouds=save_to_s3) #https://docs.videojs.com/docs/guides/setup.html # https://jsfiddle.net/vm4detdy/ """ https://stackoverflow.com/questions/49781878/python-flask-ffmpeg-video-streaming-video-does-not-work-in-firefox
import ffmpeg_streaming from ffmpeg_streaming import Formats, Bitrate, Representation, Size import sys def monitor(ffmpeg, duration, time_): per = round(time_ / duration * 100) sys.stdout.write("\rTranscoding...(%s%%) [%s%s]" % (per, '#' * per, '-' * (100 - per))) sys.stdout.flush() video = ffmpeg_streaming.input('http://wmccpinetop.axiscam.net/mjpg/video.mjpg') _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls_stream = video.hls(Formats.h264(), hls_list_size = 10, hls_time = 60) hls_stream.representations(_480p) hls_stream.output('/var/media/hls_outputs.m3u8')
def run(request): video = ffmpeg_streaming.input(stream_link) dash = video.dash(Formats.h264()) dash.representations(_480p) dash.output('/app/static/stream/dash.mpd')
def ffmpeg_livestream(url): video = ffmpeg_streaming.input(url) hls = video.hls(Formats.h264()) hls.auto_generate_representations([480]) hls.fragmented_mp4() hls.output("hls.m3u8")
def initial_protocol(self, input_path: str, output_id: str, request_id: str, encode_format: str, video_codec: str = None, audio_codec: str = None, is_hls: bool = None, fragmented: bool = None, quality_names: list[str] = None, custom_qualities: list[dict] = None): """build HLS or MPEG ffmpeg command using ffmpeg_streaming package """ # checking file is exist and not empty try: if os.stat(input_path).st_size == 0: self.save_output_status(self.output_status.OUTPUT_FAILED, output_id, request_id) self.save_job_stop_reason( self.stop_reason.INPUT_VIDEO_SIZE_CAN_NOT_BE_ZERO, request_id) raise self.raise_ignore( message=self.error_messages.INPUT_SIZE_CAN_NOT_BE_ZERO, request_kwargs=self.request.kwargs) except FileNotFoundError: # TODO notify developer self.save_output_status(self.output_status.OUTPUT_FAILED, output_id, request_id) self.save_job_stop_reason(self.stop_reason.INTERNAL_ERROR, request_id) raise self.raise_ignore( message=self.error_messages.INPUT_FILE_IS_NOT_FOUND, request_kwargs=self.request.kwargs) video = ffmpeg_streaming.input(input_path) format_instance = VideoEncodingFormats().get_format_class( encode_format, video=video_codec, audio=audio_codec, ) if is_hls: # HLS Protocol protocol = video.hls(format_instance) if fragmented: protocol.fragmented_mp4() else: # MPEG-Dash Protocol protocol = video.dash(format_instance) """create a list of Representation instances to add to the protocol instance """ # generate default representations if not (custom_qualities or quality_names): try: protocol.auto_generate_representations( ffprobe_bin=settings.FFPROBE_BIN_PATH) return except RuntimeError as e: # TODO capture error and notify developer raise self.retry(exc=e) except Exception as e: # FileNotFoundError: # [Errno 2] No such file or directory: 'ffprobe' # TODO capture error and notify developer raise self.retry(exc=e) reps = [] # quality_names is like ["360p","480p","720p"] if quality_names: reps.extend(Resolutions().get_reps(quality_names)) # custom_qualities is like : # [dict(size=[256, 144], bitrate=[97280, 65536])] for quality in custom_qualities: size = quality.get('size', None) bitrate = quality.get('bitrate', None) # when both of them has not valid value, just continue if not (size or bitrate): continue # when just one of them is exist, # force client to fill both of them if not size or not bitrate: self.save_output_status(self.output_status.OUTPUT_FAILED, output_id, request_id) self.save_job_stop_reason( self.stop_reason. REPRESENTATION_NEEDS_BOTH_SIZE_AND_BITRATE, request_id) raise self.raise_ignore( message=self.error_messages. REPRESENTATION_NEEDS_BOTH_SIZE_AND_BITRATE, request_kwargs=self.request.kwargs) reps.append(Representation(Size(*size), Bitrate(*bitrate))) # generate representations protocol.representations(*reps) return protocol
import ffmpeg_streaming import csv from ffmpeg_streaming import Formats with open('<your list of m3u8s>.csv', newline='') as csvfile: data = list(csv.reader(csvfile)) for x in range(len(data)): filename = data[x][0] streamlink = data[x][1] print("Writing File: " + filename) video = ffmpeg_streaming.input(streamlink) stream = video.stream2file(Formats.h264()) stream.output('<your local directory>' + filename + '.mp4')