def reset(self): """ desc: Initialize/ reset the plug-in. """ # Experimental variables self.var.resizeVideo = u"yes" self.var.duration = u"keypress" self.var.event_handler = u"" self.var.event_handler_trigger = u"on keypress" self.var.video_src = u"" self.var.playaudio = u"yes" # Internal variables self.file_loaded = False self.vlc_event_handler = None self.media = None self.hasMediaInfo = False self.process_feedback = True # See if MediaInfo functions are available try: MediaInfo.parse(u"") self.hasMediaInfo = True except: debug.msg(u"MediaInfo CLI not found. Frame info might be unavailable.", reason=u"warning") self.hasMediaInfo = False
def reset(self): """ desc: Initialize/ reset the plug-in. """ self.file_loaded = False self.resizeVideo = u"yes" self.duration = u"keypress" self.playaudio = u"yes" self.sendInfoToEyelink = u"no" self.event_handler = u"" self.event_handler_trigger = u"on keypress" self.vlc_event_handler = None self.media = None self.framerate = 0 self.frame_duration = 0 self.startPlaybackTime = 0 self.playbackStarted = False self.hasMediaInfo = False #See if MediaInfo functions are available try: MediaInfo.parse(u"") self.hasMediaInfo = True except: debug.msg( \ u"MediaInfo CLI not found. Frame info might be unavailable.", reason=u"warning") self.hasMediaInfo = False
def __init__(self, name, experiment, string=None): """ Constructor. Link to the video can already be specified but this is optional Arguments: name -- the name of the item experiment -- the opensesame experiment Keyword arguments: string -- a definition string for the item (Default=None) """ # The version of the plug-in self.version = 0.10 self.file_loaded = False self.paused = False self.item_type = "media_player_vlc" self.description = "Plays a video from file" self.duration = "keypress" self.playaudio = "yes" self.sendInfoToEyelink = "no" self.event_handler = "" self.event_handler_trigger = "on keypress" self.vlc_event_handler = None self.vlcInstance = vlc.Instance() self.player = self.vlcInstance.media_player_new() self.media = None self.framerate = 0 self.frame_duration = 0 self.startPlaybackTime = 0 self.playbackStarted = False self.hasMediaInfo = False #See if MediaInfo functions are available try: MediaInfo.parse("") self.hasMediaInfo = True except: debug.msg( \ "MediaInfo CLI not found. Frame info might be unavailable.", reason="warning") self.hasMediaInfo = False # The parent handles the rest of the construction item.item.__init__(self, name, experiment, string)
def run(self): uri = urlparse(self.subject[dc.identifier]) # Resolve absolute paths for command-line system calls if uri.scheme == "" or uri.scheme == "file": # Remove leading / from /C:\folder\ URIs # Don't use platform.system() here, because we don't want to include Cygwin if os.name == "nt" and len(uri.path) >= 3 and uri.path[0] == "/" and uri.path[2] == ":": filename = os.path.abspath(uri.path[1:]) else: filename = os.path.abspath(uri.path) else: filename = self.subject[dc.identifier] try: media_info = MediaInfo.parse(filename) tracks = media_info.tracks except: tracks = [] video_streams = list() audio_streams = list() for track in tracks: if track.track_type == 'General' and track.duration: self.subject.emit("duration", track.duration / 1000.0) elif track.track_type == 'Video': v = dict() if track.frame_rate: v["framerate"] = float(track.frame_rate) if track.codec: v["codec"] = track.codec if track.height: v["height"] = int(track.height) if track.width: v["width"] = int(track.width) video_streams.append(v) elif track.track_type == "Audio": a = dict() if track.sampling_rate: a["samplerate"] = int(track.sampling_rate) if track.codec: a["codec"] = track.codec if track.channel_s: a["channels"] = int(track.channel_s) audio_streams.append(a) for v in video_streams: self.subject.emit("video_stream", v) for a in audio_streams: self.subject.emit("audio_stream", a) if len(video_streams) > 0: self.subject.extendClass("item.video") elif len(audio_streams) > 0: self.subject.extendClass("item.audio")
def handle_media(content): with tempfile.NamedTemporaryFile() as f: f.write(content) media = MediaInfo.parse(f.name) duration = timedelta(seconds=media.tracks[0].duration // 1000) num_tracks = len(media.tracks) - 1 first_video_track = next((track for track in media.tracks if track.track_type == 'Video'), None) first_audio_track = next((track for track in media.tracks if track.track_type == 'Audio'), None) info = "\x02Media Info:\x02 {n} track{s}, {duration}, {size}".format( size=humanize.naturalsize(media.tracks[0].file_size), n=num_tracks, s='s' if num_tracks != 1 else '', duration=duration ) if first_video_track: info += "; {w} x {h} {codec}, {bitrate}bps, {framerate}fps".format( codec=first_video_track.format, bitrate=humanize.naturalsize(first_video_track.bit_rate, gnu=True).lower(), framerate=first_video_track.frame_rate, w=first_video_track.width, h=first_video_track.height ) if first_audio_track: info += "; {ch}ch {codec}, {sr}kHz".format( codec=first_audio_track.format, ch=first_audio_track.channel_s, sr=first_audio_track.sampling_rate // 100 / 10 ) return info
def parse_metadata(self, path, id_): """ Parse the MP4 header metadata for bitrate information. Specifically, retrieve the maximum encoded bitrate for each quality level. """ self.player.event('start', 'parsing metadata ' + str(path)) found = False try: media_info = MediaInfo.parse(path) except OSError: self._set_maximum_encoded_bitrate(0, id_) self.player.event('error', 'MediaInfo not installed') return for track in media_info.tracks: if track.track_type == 'Video': maximum_bitrate = track.maximum_bit_rate if maximum_bitrate: self._set_maximum_encoded_bitrate(maximum_bitrate, id_) found = True else: self.player.event( 'error', 'maximum bitrate not found in metadata') self._set_maximum_encoded_bitrate(0, id_) return if not found: self.player.event('error', 'no video track in metadata') self._set_maximum_encoded_bitrate(0, id_) self.player.event('stop', 'parsing metadata ' + str(path))
def analysis(video): mediainfoobject = MediaInfo.parse(str(settings.BASE_DIR) + str(os.path.normpath(video.videofile.url))) try: for track in mediainfoobject.tracks: if track.track_type == 'General': video.format = track.format video.filesize = track.file_size video.duration = track.duration if track.track_type == 'Video': video.width = track.width video.height = track.height video.resolution = str(video.width) + 'x' + str(video.height) video.vcodec = track.codec video.aspect = track.display_aspect_ratio video.framerate = track.frame_rate video.colorspace = track.color_space video.bitdepth = track.bit_depth video.vbitrate = track.bit_rate if track.track_type == 'Audio': video.acodec = track.format video.abitrate = track.bit_rate video.asamplingrate = track.asampling_rate video.abitdepth = track.bit_depth video.channels = track.channel_s except: return video
def get_video_size(input_file): media_info = MediaInfo.parse(input_file) for track in media_info.tracks: if track.track_type == 'Video': #print(str(track.width)+"x"+str(track.height)) return str(track.width)+":"+str(track.height) raise AssertionError("failed to read video info from " + input_file)
def get_duration(self): if MediaInfo is not None: for track in MediaInfo.parse(self.path).tracks: if track.track_type == 'Video': log.debug("Found video track with duration %d" % track.duration) self.duration = track.duration return self.duration
def set_techmd_values(self): techmd = MediaInfo.parse(self.filepath) md_track = None for track in techmd.tracks: if track.track_type == "General": md_track = track if not md_track: self.raise_AMIFileError('Could not find General track') self.base_filename = md_track.file_name self.extension = md_track.file_extension self.format = md_track.format self.size = md_track.file_size if md_track.encoded_date: self.date_created = parse_date(md_track.encoded_date) elif md_track.recorded_date: self.date_created = parse_date(md_track.recorded_date) elif md_track.file_last_modification_date: self.date_created = parse_date(md_track.file_last_modification_date) self.duration_milli = md_track.duration self.duration_human = parse_duration(self.duration_milli) self.audio_codec = md_track.audio_codecs if md_track.codecs_video: self.video_codec = md_track.codecs_video
def get_video_info(file_list, output_filename="output.csv"): """Get video info for a file(s)""" total_duration = timedelta() items = [] for filename in file_list: media_info = MediaInfo.parse(filename) media_dict = OrderedDict() src_dir, src_file = os.path.split(filename) media_dict['filename'] = src_file for t in media_info.tracks: if t.track_type == 'General': media_dict['format'] = t.format elif t.track_type == 'Video': media_dict['duration'] = timedelta(milliseconds=t.duration) media_dict['dimensions'] = "%sx%s" % (t.width, t.height) media_dict['video_bitrate'] = t.other_bit_rate[0] media_dict['video_framerate'] = t.frame_rate total_duration += timedelta(milliseconds=t.duration) items.append(media_dict) csv_list = [] if len(items) > 0: csv_list.append([key for key, _ in items[0].items()]) for item in items: csv_list.append([v for k, v in item.items()]) totals = ['TOTALS:', len(items), total_duration] csv_list.append(totals) with open(os.path.join(src_dir, output_filename), 'w', newline='') as f: writer = csv.writer(f) writer.writerows(csv_list)
def parse_media(self): self.mtime_end = os.path.getmtime(self.file_path) if myutil.match_type(self.file_path, ["jpg"]): self.media_type = "Image" elif myutil.match_type(self.file_path, ["mp4", "mts", "lrv"]): self.media_type = "Video" elif myutil.match_type(self.file_path, ["wav"]): self.media_type = "Audio" media_info = MediaInfo.parse(self.file_path) for track in media_info.tracks: if StreamFile.Debug: pprint(track.to_data()) if track.track_type == "Video": # some jpg has a video track self.video_width = track.width self.video_height = track.height if track.duration is None: self.duration = -1 else: self.duration = track.duration break elif track.track_type == "Audio": self.duration = track.duration break elif track.track_type == "Image": self.video_width = track.width self.video_height = track.height self.duration = -1 break self.calc_mtime_begin()
def __init__(self, fpath): try: self.added = now() self.finished = 0 self.fullpath = fpath self.fileid = getNewFileID() tempMediainfo = MediaInfo.parse(self.fullpath) self.mediainfo = {} for track in tempMediainfo.tracks: if track.track_type not in self.mediainfo: self.mediainfo[track.track_type] = track.to_data() else: if track.track_type in ['Audio', 'Subtitle']: if not isinstance(self.mediainfo[track.track_type], list): tempTrack = self.mediainfo[track.track_type] self.mediainfo[track.track_type] = [] self.mediainfo[track.track_type].append(tempTrack) self.mediainfo[track.track_type].append(track.to_data()) self.outputfilename = pacvert.CONFIG.OUTPUT_DIRECTORY+'/'+generateOutputFilename(self.fullpath) self.createThumbs() self.crop = self.analyzeThumbs() self.deleteThumbs() self.updateStatus(2) except Exception as e: logger.error(e)
def find_file_extension(root, file_name): ext = "" codec = "" container = "" abs_file_path = os.path.join(root, file_name) print "Analysing file ...", abs_file_path media_info = MediaInfo.parse(abs_file_path) for track in media_info.tracks: if track.track_type == 'General': container = track.codec_id if track.track_type == 'Audio': codec = track.codec if container is not None: container = container.strip() if codec is not None: codec = codec.strip() if container is None: if codec in ["MPA2L3", "MPA1L3"]: ext = ".mp3" elif container == 'M4A': ext = ".m4a" print "container: {}, codec: {}, ext: {}".format(container, codec, ext) return ext
async def streaming(_response): debug.info("streaming " + str(_response)) total_size = 0 temporary_file = os.path.join(_app.config['REST_TMP_DATA'], str(tmp_value) + ".tmp") if not os.path.exists(_app.config['REST_TMP_DATA']): os.makedirs(_app.config['REST_TMP_DATA']) if not os.path.exists(_app.config['REST_MEDIA_DATA']): os.makedirs(_app.config['REST_MEDIA_DATA']) file_stream = open(temporary_file, "wb") sha1 = hashlib.sha512() while True: body = await _request.stream.read() if body is None: debug.warning("empty body") break total_size += len(body) debug.verbose("body " + str(len(body)) + "/" + str(total_size)) file_stream.write(body) sha1.update(body) file_stream.close() print("SHA512: " + str(sha1.hexdigest())) destination_filename = os.path.join(_app.config['REST_MEDIA_DATA'], str(sha1.hexdigest())) if os.path.isfile(destination_filename) == True: answer_data = { "size": total_size, "sha512": str(sha1.hexdigest()), 'filename': _request.headers["filename"], 'mime-type': _request.headers["mime-type"], "already_exist": True, } await _response.write( json.dumps(answer_data, sort_keys=True, indent=4)) return # move the file shutil.move(temporary_file, destination_filename) # collect media info ... media_info = MediaInfo.parse(destination_filename) data_metafile = { "sha512": str(sha1.hexdigest()), "size": total_size, 'filename': _request.headers["filename"], 'mime-type': _request.headers["mime-type"], 'media-info': json.loads(media_info.to_json()) } tools.file_write_data( destination_filename + ".meta", json.dumps(data_metafile, sort_keys=True, indent=4)) answer_data = { "size": total_size, "sha512": str(sha1.hexdigest()), 'filename': _request.headers["filename"], 'mime-type': _request.headers["mime-type"], "already_exist": True, } await _response.write( json.dumps(answer_data, sort_keys=True, indent=4))
def un(pathname): # files from the UN. # date is in the file name # time is in other: time_code_of_first_frame # 1672828_DMOICT Open Camps CR7 8AM-12PM 16 JULY 16.mov year = "2016" month = 'JULY' day = pathname.split(month)[0].split()[-1] media_info = MediaInfo.parse(pathname) t3=media_info.tracks[3] time = t3.time_code_of_first_frame dt = "{year}-{month}-{day} {time}".format( year=year, month=month, day=day, time=time) # start = datetime.datetime.strptime("16 JULY 2016 07:50:00;00", "%d %B %Y %H:%M:%S;00") start = datetime.datetime.strptime(dt, "%Y-%B-%d %H:%M:%S;00") print( start ) return start # d+_DMOICT...move stuff so it errors if it finds something else start_date_re = r".*/" + date_re + ".*/\d+_DMOICT.*\.mov" start_date_o = re.match(start_date_re, pathname) dt_parts = start_date_o.groupdict() print("date_parts:", dt_parts) cmd = ['mediainfo', '--Inform=Video;%TimeCode_FirstFrame%', pathname ] p = subprocess.Popen( cmd, stdout = subprocess.PIPE ) stdout = p.stdout.read() # '07:50:00:00\n' # time_code = stdout.strip().split(':') start_time_re = time_re + rb":\d\d\n" start_time_o = re.match(start_time_re, stdout) start_time_d = start_time_o.groupdict() print("start_time_d:",start_time_d) dt_parts.update(start_time_d) pprint.pprint(dt_parts) dt_parts = {k:int(v) for k,v in list(dt_parts.items())} print(dt_parts) start=datetime.datetime( **dt_parts ) print(start) return start
def __get_size(self): _all = [] for video in self.video_streams: v = MediaInfo.parse(os.path.join(self.path, video[0][1:] + '.flv')) size = v.video_tracks[0] _all.append([size.width, size.height]) return self.__max_count_items(_all)
def video_info_getter(): global filesize, chunk_sum, duration filesize = os.stat(file_path).st_size chunk_sum = filesize // chunk_size if chunk_sum * chunk_size != filesize: chunk_sum += 1 mi = MediaInfo.parse(file_path).tracks[0] duration = mi.duration // 1000
def check_video_pymediainfo(path): fileinfo = MediaInfo.parse(path) for track in fileinfo.tracks: if track.track_type == "Video": return True return False
def is_video(fn): if Path(fn).suffix in video_fexts: return True fn_info = MediaInfo.parse(fn) for track in fn_info.tracks: if track.track_type == 'Video': return True return False
def get_duration(path: str) -> float: ''' Get the duration of a single video file ''' media_info = MediaInfo.parse(path) #duration in milliseconds duration_in_ms = media_info.tracks[0].duration # print(duration_in_ms) return duration_in_ms
def is_video_has_sound(src): media_info = MediaInfo.parse(src) hasSound = False for track in media_info.tracks: if 'Audio' == track.track_type : hasSound = True return hasSound
def create_mediainfo(entry=None, entry_id=None): if entry is None: entry = get_entry(entry_id) filename = entry["filename"] info = MediaInfo.parse(filename) mediainfo_file = f"{filename}.mediainfo.json" with open(mediainfo_file, "w") as fp: fp.write(info.to_json())
def file_info(file_path, log): media_info = MediaInfo.parse(file_path).to_data() local_file_info = [ get_media_info(*keys, media_info, log) for keys in media_keys ] return [i[0] if type(i) == list else i for i in local_file_info]
def processDir(s3client, directory, files, unittest=False, metadataCache=None): if metadataCache: metadata = metadataCache else: metadata = getMetadataFile(s3client, directory) metadataChange = False filesystem = {} for filename in files: s3fileinfo = files[filename] fullpath = "{}/{}".format(directory, filename) if not filename.endswith('metadata.json'): path = fullpath.split('/') dirEl = filesystem leaf = {} for pathElement in path: if pathElement != '': if pathElement not in dirEl: dirEl[pathElement] = {} leaf = dirEl[pathElement] dirEl = dirEl[pathElement] try: if fullpath in metadata and 'metadata' in metadata[fullpath]: leaf['metadata'] = {} for key in metadata[fullpath]['metadata']: leaf['metadata'][key] = metadata[fullpath]['metadata'][ key] if (directory.startswith('video/') or directory.startswith('audio/')) and ( 'metadata' not in leaf or 'mediainfo' not in leaf['metadata']): print('Media info not found so adding') fileJson = json.loads( MediaInfo.parse('{}/{}'.format(hostName, fullpath)).to_json()) leaf['metadata'] = {'mediainfo': fileJson} if fullpath not in metadata: metadata[fullpath] = {} if 'metadata' not in metadata[fullpath]: metadata[fullpath]['metadata'] = {} metadata[fullpath]['metadata']['mediainfo'] = fileJson metadataChange = True except OSError as configError: print( 'Failed to analysis file due to a problem with the setup of mediainfo:' ) print(configError) if not unittest and metadataChange: # save metadata to s3 saveMetadata(directory, metadata) if unittest: return (metadataChange, metadata) else: return filesystem
async def get_dvdinfo(self, discs): for each in discs: path = each.get('path') os.chdir(path) files = glob(f"VTS_*.VOB") files.sort() filesdict = [[]] main_set = [] for i in range(len(files)): trimmed = files[i][4:] set = int(trimmed[:2]) - 1 try: filesdict[set].append(trimmed) except: filesdict.append([]) filesdict[set].append(trimmed) for vob_set in filesdict: if len(vob_set) > len(main_set): main_set = vob_set elif len(vob_set) == len(main_set): vob_set_mi = MediaInfo.parse(f"VTS_{vob_set[0][:2]}_0.IFO", output='JSON') vob_set_mi = json.loads(vob_set_mi) vob_set_duration = vob_set_mi['media']['track'][1]['Duration'] main_set_mi = MediaInfo.parse(f"VTS_{main_set[0][:2]}_0.IFO", output='JSON') main_set_mi = json.loads(main_set_mi) main_set_duration = main_set_mi['media']['track'][1]['Duration'] if vob_set_duration > main_set_duration: main_set = vob_set each['main_set'] = main_set set = main_set[0][:2] # print(main_set[1:len(main_set)-1]) #For Screens #if len > 3 # print(main_set[0][:2]) each['vob'] = vob = f"{path}/VTS_{set}_1.VOB" each['ifo'] = ifo = f"{path}/VTS_{set}_0.IFO" each['vob_mi'] = MediaInfo.parse(os.path.basename(vob), output='STRING', full=False, mediainfo_options={'inform_version' : '1'}) each['ifo_mi'] = MediaInfo.parse(os.path.basename(ifo), output='STRING', full=False, mediainfo_options={'inform_version' : '1'}) size = sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))/float(1<<30) if size <= 7.95: dvd_size = "DVD9" if size <= 4.37: dvd_size = "DVD5" each['size'] = dvd_size return discs
def video_duration(list): duration = 0 for video in list: media_info = MediaInfo.parse(video) for track in media_info.tracks: if track.track_type == 'Video': duration += track.duration / 1000 return duration
def get_cbr(video_file, t_type): media_info = MediaInfo.parse(video_file) cbr = 0 for track in media_info.tracks: if track.track_type == t_type: cbr = track.bit_rate return str(cbr)
def plugin_main(self, new_file): inode, file_path = new_file ext = path.splitext(file_path)[1][1:].lower() thumb_dir = settings.get('thumbnail', 'path') thumb_file = path.join(thumb_dir, inode + '.jpg') # Extract base image if ext in self.EXT_VIDEO: fnull = open(devnull, 'w') command = [ 'ffmpeg', '-i', file_path, '-y', '-vframes', '1', '-ss', '00:00:01', '-an', thumb_file ] call(command, shell=False, stdout=fnull, stderr=fnull) fnull.close() elif ext in self.EXT_AUDIO: media_info = MediaInfo.parse(file_path) if media_info.tracks[0].cover == 'Yes': cover_data = media_info.tracks[0].cover_data open(thumb_file, 'wb').write(a2b_base64(cover_data)) else: audio_dir = path.dirname(file_path) for folder_cover in [ 'Folder.jpg', 'folder.jpg', 'Cover.jpg', 'cover.jpg' ]: audio_cover = path.join(audio_dir, folder_cover) if path.exists(audio_cover): command = ['convert', audio_cover, thumb_file] call(command) else: if not ext in self.EXT_EPEG_SUPPORT: if ext == 'gif': command = ['convert', file_path + "[0]", thumb_file] else: command = ['convert', file_path, thumb_file] call(command) else: thumb_file = file_path # Generate thumbnail for size in settings.get('thumbnail', 'size').split(','): WxH = settings.get('thumbnail', size) filename = [inode, size, 'jpg'] command = [ 'epeg', '-m', WxH, thumb_file, path.join(thumb_dir, '.'.join(filename)) ] call(command) self.push_back({ 'uid': inode, 'module': self.name, 'has_thumbnail': 'true' }) log.debug("{} module finished: {}".format(self.name, new_file[1]))
def get_tracks(file, sub_language='en'): to_mux = [] info = MediaInfo.parse(file) for track in info.tracks: if (track.track_type == 'Audio') and (track.language == 'ja'): to_mux.append('a:' + str(track.stream_identifier)) if (track.track_type == 'Text') and (track.language == sub_language): to_mux.append('s:' + str(track.stream_identifier)) return to_mux
def test_mediainfo_options(self): self.assertNotEqual( self.mi_detail0, self.mi_detail1, ) self.assertEqual( self.mi_detail0, MediaInfo.parse(os.path.join(data_dir, "aac_he_v2.aac"), text=True))
def get_mediainfo(path, mdpath): print("Getting Mediainfo") media_info = MediaInfo.parse(path, output="STRING", full=False) media_info = media_info.encode(encoding='utf8') media_info = media_info.decode('utf8', 'strict') bhdlogger.debug(media_info) t = open(mdpath, "w") t.write(media_info)
def hello(event, context): event_obj = json.loads(event["body"]) url = event_obj['url'] print url os.system("ls layer/") media_info = MediaInfo.parse( url, library_file='layer/libmediainfo.so.0').to_data() print media_info return {"statusCode": 200, "body": json.dumps(media_info, indent=2)}
def printMediaInfo(filepath): media_info = MediaInfo.parse(filepath) for track in media_info.tracks: print(track.track_type) if (track.track_type == 'General' or track.track_type == 'Video' or track.track_type == 'Audio'): print("type: {0}: ".format(track.track_type)) print_dict(track.__dict__) print()
def test_json_output(self): lib_version_str, lib_version = _get_library_version() if lib_version < (18, 3): pytest.skip("This version of the library does not support JSON output " "(v{} detected, v18.03 required)".format(lib_version_str) ) mi = MediaInfo.parse(os.path.join(data_dir, "sample.mp4"), output="JSON") parsed = json.loads(mi) self.assertEqual(parsed["media"]["track"][0]["FileSize"], "404567")
def process(fname): media_info = MediaInfo.parse(fname) for track in media_info.tracks: print_frame(track.track_type) pprint(track.to_data()) print() for track in media_info.tracks: if track.track_type == 'General' and track.duration: print("Duration: {} sec.".format(track.duration / 1000.0))
def get_video_info(self): media_info = MediaInfo.parse(self.abs_file_path) data = media_info.to_json() data = json.loads(data)['tracks'] for key in data: if key['track_type'] == 'Video': self.video_duration = int(key['frame_count']) / (int( key['frame_rate'].split('.')[0])) return self.video_duration
def get_cbr(video_file, t_type): media_info = MediaInfo.parse(video_file) cbr = 0 for track in media_info.tracks: if track.track_type == t_type: cbr=track.bit_rate return str(cbr)
def Transcode(self, path, codec, crf, speed, options=None): if not os.path.isfile(path): logging.error('Path does not point to a file: {}'.format(path)) logging.info('Transcode processing starting for %s' % path) # Get the media info object for this file mediainfo = MediaInfo.parse(path) # Handle auto-selecting parameters if codec == 'auto': params = self.AutoSelectEncParameters(mediainfo, options=options) codec = params['codec'] speed = params['speed'] crf = params['crf'] try: # Full hardware transcode try: cmds = self.BuildFFMPEGCommands(path, mediainfo, codec, crf, speed, options=options) logging.info( 'Transcoder command builder returned {} commands to run'. format(len(cmds))) for cmd in cmds: self.Call(cmd) except Exception, e: logging.info( 'Full hardware transcoding failed, trying software decode, hardware encode: %s' % e) # Software decode, hardware transcode hw_dec_disabled = {'disable_hw_decode': True} if options: hw_dec_disabled.update(options) cmds = self.BuildFFMPEGCommands(path, mediainfo, codec, crf, speed, options=hw_dec_disabled) logging.info( 'Transcoder command builder returned {} commands to run'. format(len(cmds))) for cmd in cmds: self.Call(cmd) # Return the transcoded file temp_path = cmds[-1][-1] logging.info('Finished processing: {}, transcoded file: {}'.format( path, temp_path)) return temp_path
def get_mediainfo(source_path, gprkey): ''' Use pymediainfo lib to extract the MP4 file info. Pass these values back to the concat and downcovert. ''' media_dict = {} gprkey_path = source_path + str(gprkey) media_info = MediaInfo.parse(gprkey_path) for track in media_info.tracks: if track.track_type == 'Video': media_dict.update(v_format=track.format) media_dict.update(v_info=track.format_info) media_dict.update(v_profile=track.format_profile) media_dict.update(v_settings=track.format_settings) media_dict.update(v_settings_cabac=track.format_settings_cabac) media_dict.update( v_settings_reframes=track.format_settings_reframes) media_dict.update(v_format_settings_gop=track.format_settings_gop) media_dict.update(v_codec_id=track.codec_id) media_dict.update(v_codec_id_info=track.codec_id_info) media_dict.update(v_duration=track.duration) media_dict.update(v_bit_rate_mode=track.bit_rate_mode) media_dict.update(v_bit_rate=track.bit_rate) media_dict.update(v_max_bit_rate=track.maximum_bit_rate) media_dict.update(v_frame_rate=track.frame_rate) media_dict.update(v_frame_rate_mode=track.frame_rate_mode) media_dict.update(v_width=track.width) media_dict.update(v_height=track.height) media_dict.update( v_display_aspect_ratio=track.display_aspect_ratio) media_dict.update(v_standard=track.standard) media_dict.update(v_color_space=track.color_space) media_dict.update(v_chroma_sub=track.chroma_subsampling) media_dict.update(v_bit_depth=track.bit_depth) media_dict.update(v_scan_type=track.scan_type) media_dict.update(v_encoded_date=track.encoded_date) if track.track_type == 'Audio': media_dict.update(a_format=track.format) media_dict.update(a_format_info=track.format_info) media_dict.update(a_format_profile=track.format_profile) media_dict.update(a_codec_id=track.codec_id) media_dict.update(a_duration=track.duration) media_dict.update(a_bit_rate_mode=track.bit_rate_mode) media_dict.update(a_bit_rate=track.bit_rate) media_dict.update(a_max_bit_rate=track.maximum_bit_rate) media_dict.update(a_channel_positions=track.channel_positions) media_dict.update(a_sampling_rate=track.sampling_rate) media_dict.update(a_compression_mode=track.compression_mode) # print(media_dict) return media_dict
def get_media_path(extensions, dir=None): config = read_yaml() extensions = extensions.split(' ') playout_extensions = config['storage']['extensions'] gui_extensions = [x for x in extensions if x not in playout_extensions] media_path = config['storage']['path'].replace('\\', '/').rstrip('/') media_dir = media_path.split('/')[-1] media_root = os.path.dirname(media_path) if not dir: dir = media_path else: if '/..' in dir: # remove last folder to navigate in upper directory dir = '/'.join(dir.split('/')[:-2]) dir = dir.lstrip('/') if dir.startswith(media_dir): dir = dir[len(media_dir):] dir = os.path.join(media_root, media_dir, os.path.abspath('/' + dir).strip('/')) for root, dirs, files in os.walk(dir, topdown=True): root = root.rstrip('/') media_files = [] for file in files: ext = os.path.splitext(file)[1] if ext in playout_extensions: media_info = MediaInfo.parse(os.path.join(root, file)) duration = 0 for track in media_info.tracks: if track.track_type == 'General': try: duration = float( track.to_data()["duration"]) / 1000 break except KeyError: pass media_files.append({'file': file, 'duration': duration}) elif ext in gui_extensions: media_files.append({'file': file, 'duration': ''}) dirs = natsorted(dirs) if root != media_path: dirs.insert(0, '..') if not dirs: dirs = ['..'] if root.startswith(media_root): root = root[len(media_root):] return [root, dirs, natsorted(media_files, key=lambda x: x['file'])]
def _get_rotation(self, input_file): video_track_infos = [t for t in MediaInfo.parse(input_file).tracks if t.track_type == 'Video'] if not video_track_infos: return 0 rotation = video_track_infos[0].rotation if not rotation: return 0 return int(float(rotation))
def is_4k(movie): file_info = MediaInfo.parse(movie) for track in file_info.tracks: if track.track_type == 'Video': if track.width == 3840: print(str(movie) + "Movie is 4k") return True else: print(str(movie) + "Movie is not 4k") return False
def get_duration(self): #video = cv2.VideoCapture(self.name) #duration = video.get(cv2.CAP_PROP_POS_MSEC) #frame_count = video.get(cv2.CAP_PROP_FRAME_COUNT) #fps = video.get(cv2.CAP_PROP_FPS) #return frame_count/fps #return duration, frame_count media_info = MediaInfo.parse(self.name) return float(media_info.tracks[0].duration)
def meta_tags(my_file): """ Not ready for prime time :param my_file: :return: """ media_info = MediaInfo.parse(my_file) foo = media_info.to_json() parsed = json.loads(foo) print(json.dumps(parsed, indent=4))
def scan_file(full_file_path): media_info = MediaInfo.parse(full_file_path) with open('data.json', 'a') as fp: fp.write("{\n\t\"file\": \"" + full_file_path + "\",\n") fp.write("\t\"tracks\": \n") for track in media_info.tracks: fp.write("{\n\t\"" + (track.track_type) + "\":\n") json.dump(track.to_data(), fp, indent=4) fp.write("\n},") fp.write("},")
def process(fname): media_info = MediaInfo.parse(fname) for track in media_info.tracks: print_frame(track.track_type) pprint(track.to_data()) # print() for track in media_info.tracks: if track.track_type == 'General': print("Duration: {} sec.".format(track.duration / 1000.0))
def __init__(self, slide_input, template): if 'video' not in slide_input and 'file' not in slide_input: raise ValueError('No video was specified in either video or file slide input type') self.content = {'background-1': slide_input} if 'background-1' not in Templates[template]: raise KeyError('The template %s has no background to put the video' % template) video_path = slide_input['video'] if 'video' in slide_input else Asset.get(slide_input['file']).path video_info = MediaInfo.parse(video_path) self.duration = video_info.tracks[0].duration + 1000 self.template = template
def _get_metadata(self): source = Metadata_Source(self.config) metadata = source.get_metadata(self.tvdb_id, self.filename) print ' - Setting options' tags = dict() # Metadata that's always present tags['TVSeasonNum'] = metadata['seasonnumber'] tags['TVEpisodeNum'] = metadata['episodenumber'] tags['TVShowName'] = tags['artist'] = metadata['seriesname'] tags['title'] = metadata['episodename'] tags['album'] = metadata['seriesname'] + ', Season ' + metadata['seasonnumber'] tags['disk'] = '1/1' tags['stik'] = 'TV Show' # Metadata that may not be present if 'poster' in metadata: tags['artwork'] = self._get_artwork(metadata['poster']) else: tags['artwork'] = self._get_artwork(None) if 'network' in metadata: tags['TVNetwork'] = metadata['network'] if 'airdate' in metadata: tags['year'] = metadata['airdate'] self.airdate = metadata['airdate'] if 'certificate' in metadata: tags['contentRating'] = metadata['certificate'] if 'genre' in metadata: tags['genre'] = metadata['genre'] if 'episodecount' in metadata: tags['tracknum'] = metadata['episodenumber'] + '/' + metadata['episodecount'] if 'id' in metadata: tags['cnID'] = metadata['id'] if 'description' in metadata: tags['description'] = metadata['description'] if 'description' in metadata: tags['longdesc'] = metadata['description'] # Check file for HDness print ' - Scanning video to check HDness' mi = MediaInfo.parse(self.filename) video_hd = False for track in mi.tracks: if track.track_type == 'Video': video_hd = True if (track.height >= 700 or track.width >= 1260) else False tags['hdvideo'] = '1' if video_hd else '0' xml = None if self.config.get('tagMP4', 'add_people') == 'True' and 'actors' in metadata: xml = self._gen_XML(metadata['actors']) return tags, xml
def set_from_media_info(self, directory_path): """ Set attributes by extracting them from media info input: directory_path <str> parent directory of the file """ file_path = os.path.join(directory_path, self.file_name) media = MediaInfo.parse(file_path) media_general_track = media.tracks[0] duration = getattr(media_general_track, "duration", 0) or 0 self.song.duration = timedelta(milliseconds=int(duration))
def open( self, fd ): self.__test_music() if self.file : a = Media.parse( fd ) for track in a.tracks: if track.track_type == 'General' and self.__audio == True and self.music: #print track.bit_rate, track.bit_rate_mode, track.codec, track.format #print track.complete_name, print str(track.performer) + ' ' + str(track.album) + ' ' + str(track.recorded_date) if track.track_type == 'Audio' and self.__audio == True: print track.format , ' ' , track.bit_rate, ' ' , track.sampling_rate , ' ', track.channel_s
def parse(self): self.tracklist = [] mediainfo = MediaInfo.parse(self.path) # UID if self.ext == '.mkv' and mediainfo.tracks[0].other_unique_id: uid = mediainfo.tracks[0].other_unique_id[0] uid = re.findall('0x[^)]*', uid)[0].replace('0x', '') # Mediainfo strips leading zeroes self.uid = uid.rjust(32, '0') # Track: [track_id, track_type] for t in mediainfo.tracks: if t.track_type == 'Video': tr = VideoTrack() self.dimensions[0] = t.width self.dimensions[2] = t.width self.dimensions[1] = t.height self.dimensions[3] = t.height if t.frame_rate_mode == 'CFR': if t.frame_rate == '23.976': self.fps[0] = 24000 self.fps[2] = 24000 self.fps[1] = 1001 self.fps[3] = 1001 elif t.frame_rate == '29.970': self.fps[0] = 30000 self.fps[2] = 30000 self.fps[1] = 1001 self.fps[3] = 1001 elif t.track_type == 'Audio': tr = AudioTrack() tr.channel = t.channel_s tr.rate = t.sampling_rate tr.depth = t.bit_depth elif t.track_type == 'Text': tr = TextTrack() elif t.track_type == 'Menu': # tr = MenuTrack() pass if t.track_type not in ['General', 'Menu']: tr.file = self tr.id = t.track_id - 1 tr.default = True if t.default == 'Yes' else False tr.type = t.track_type tr.format = t.format tr.title = t.title if t.title else '' # We want the 3 letter code tr.lang = t.other_language[3] if t.other_language else '' self.tracklist.append(tr)
def get_movie_date(path): dt = None media_info = MediaInfo.parse(path) for track in media_info.tracks: dt = track.encoded_date if dt: return parse_movie_date(dt) # created_time = datetime.fromtimestamp(os.path.getctime(path)) # dt = arrow.get(created_time, 'Asia/Jakarta') return dt
def get_episode_number(file): """Return the episode number from the SYNOPSIS field in the file metadata""" media_info = MediaInfo.parse(file) for track in media_info.tracks: if track.track_type == 'General': synopsis = track.synopsis """We assume that there won't be more than 99 episodes in a season here, so just trim the last two characters and what remains must be our season number. There has to be a smarter way.""" episode_num = synopsis[-2:] return int(episode_num)
def main(): parser = argparse.ArgumentParser() parser.add_argument("infile", help="Original input video file.") parser.add_argument("edlfile", help="EDL file with edit definitions.") parser.add_argument("outfile", help="Edited video file path/name.") parser.add_argument("-t", "--threads", type=int, help="Number of CPU threads to use.") parser.add_argument("-p", "--preset", choices=["ultrafast", "superfast", "fast", "medium", "slow", "superslow"], help="FFMPEG preset to use for optimizing the compression. Defaults to 'medium'.") parser.add_argument("-vb", "--videobitrate", help="Video bitrate setting. Auto-detected from original video unless specified.") parser.add_argument("-ab", "--audiobitrate", help="Audio bitrate setting. Auto-detected from original video unless specified.") parser.add_argument("-vc", "--vcodec", help="Video codec to use.") parser.add_argument("-ac", "--acodec", help="Audio codec to use.") parser.add_argument("-fp", "--ffmpegparams", help="Additional FFMpeg parameters to use. Example: '-crf=24 -s=640x480'.") args = parser.parse_args() estruct = edl.EDL(args.edlfile) videoBitrate = "" audioBitrate = "" if args.threads == None: threadNum = 2 else: threadNum = args.threads if args.preset == None: ffmpegPreset = "medium" else: ffmpegPreset = args.preset mi = MediaInfo.parse(args.infile) if args.videobitrate == None: videoBitrate = str(int(mi.tracks[1].bit_rate / 1000)) + "k" print("Using original video bitrate: "+videoBitrate) else: videoBitrate = args.videobitrate if videoBitrate[-1] != 'k': videoBitrate = videoBitrate+'k' if args.audiobitrate == None: try: audioBitrate = str(int(mi.tracks[2].bit_rate / 1000)) + "k" except TypeError: audioBitrate = str(int(int(mi.tracks[2].bit_rate.split(' / ')[1]) / 1000)) + "k" print("Using original audio bitrate: "+audioBitrate) else: audioBitrate = args.audiobitrate if audioBitrate[-1] != 'k': audioBitrate = audioBitrate+'k' render(args.infile, estruct, args.outfile, videoBitrate, audioBitrate, threadNum=threadNum, vcodec=args.vcodec, acodec=args.acodec, ffmpeg_params=args.ffmpegparams, ffmpegPreset=ffmpegPreset)
def get_video_size(*args, **kwargs): ''' use mediainfo to compute the video size ''' print args, kwargs context = args[0] media_info = MediaInfo.parse(context["original_file"]) for track in media_info.tracks: if track.track_type == 'Video': print "video is %d, %d" % (track.height, track.width) context["track_width"] = track.width context["track_height"] = track.height return context raise AssertionError("failed to read video info from " + context["original_file"])
def get_duration(f): mc = memcache.Client(['127.0.0.1:11211'], debug=0) key = escape_generic(f) d = mc.get(key) if d is not None: return d else: d = 0 info = MediaInfo.parse(f) for track in info.tracks: if getattr(track, 'duration') is not None: d = track.duration break mc.set(key, d) return d
def getMediaInfoForFile(file): media_info = MediaInfo.parse(file) vc = '' ac = '' for track in media_info.tracks: if track.track_type == 'Video': vc = track.codec if track.track_type == 'Audio': ac = track.codec c = {} c['audio'] = ac; c['video'] = vc; return c
def discover_forcedsubs(self, dbvideo): """ Attempts to find foreign subtitle track Input: dbvideo (Obj): Video database object Output: If successful, track number of forced subtitle Else, None """ MEDIADIR = os.path.join(dbvideo.path, dbvideo.filename) # wrapper class for mediainfo tool media_info = MediaInfo.parse(MEDIADIR.encode('unicode-escape')) subs = [] # Iterates though tracks and finds subtitles in preferred language, creates # list of dictionaries for track in media_info.tracks: data = track.to_data() if data['track_type'] == 'Text' and data['language']==self.lang: subs.append(data) if len(subs) is 0: self.log.info("No subtitle found, cannot determine foreign language track.") return None if len(subs) is 1: self.log.info("Only one {} subtitle found, cannot determine foreign language track." .format(self.lang)) return None # Sort list by size of track file subs.sort(key=lambda sub: sub['stream_size'], reverse = True) # Main language subtitle assumed to be largest main_sub = subs[0] main_subsize = main_sub['stream_size'] main_sublen = float(main_sub['duration']) # Checks other subs for size, duration, and if forced flag is set for sub in subs[1:]: if ( sub['stream_size'] <= main_subsize*self.secsub_ratio and main_sublen*.9 <= float(sub['duration']) <= main_sublen*1.1 and sub['forced']=='No' ): secondary_sub = sub else: self.log.info("No foreign language subtitle found, try adjusting ratio.") return None return secondary_sub['track_id']
def run(self): uri = urlparse(self.subject[dc.identifier]).path mime_type = self.subject[dc.format] if uri: media_info = MediaInfo.parse(uri) video_streams = list() audio_streams = list() for track in media_info.tracks: if track.track_type == 'General' and track.duration: self.subject.emit("duration", track.duration / 1000.0) elif track.track_type == 'Video': v = dict() if track.frame_rate: v["framerate"] = float(track.frame_rate) if track.codec: v["codec"] = track.codec if track.height: v["height"] = int(track.height) if track.width: v["width"] = int(track.width) video_streams.append(v) elif track.track_type == "Audio": a = dict() if track.sampling_rate: a["samplerate"] = int(track.sampling_rate) if track.codec: a["codec"] = track.codec if track.channel_s: a["channels"] = int(track.channel_s) audio_streams.append(a) for v in video_streams: self.subject.emit("video_stream", v) for a in audio_streams: self.subject.emit("audio_stream", a) if len(video_streams) > 0: self.subject.extendClass("item.video") elif len(audio_streams) > 0: self.subject.extendClass("item.audio")