예제 #1
0
def get_thumb(filepath=None,
              output_file="/users/bern/Desktop/output_file.jpg"):
    duration = probe(filepath)["streams"][0]["duration"]
    time = (float(duration) / 2)
    # should make this global
    ffmpeg_path = path.get_ffmpeg_bin() + '\\'

    if sys.platform == 'win32':
        ffmpeg_path = path.make_windows_style(ffmpeg_path)
        filepath = path.make_windows_style(filepath)
        ffmpeg_executable = 'ffmpeg.exe'
    else:
        ffmpeg_path = path.sanitize(ffmpeg_path)
        filepath = path.sanitize(filepath)
        ffmpeg_executable = 'ffmpeg'

    ffmpeg_command = '"{}{}" '.format(ffmpeg_path, ffmpeg_executable)
    ffmpeg_command += '-i "{}" '.format(filepath)
    # ffmpeg_command += '-filter:v select="eq(n\,0)" -vframes 1'
    ffmpeg_command += '-y '
    ffmpeg_command += '"{}"'.format(output_file)
    subprocess.call(ffmpeg_command, shell=True)
    output_file = path.sanitize(output_file)

    # print "Creating Thumb for %s >> %s"%(filepath,output_file)
    if not os.path.isfile(output_file):
        return
    else:
        return output_file
    '''
예제 #2
0
def get_thumb(filepath = None, output_file = ""):
    if not output_file:
        output_file = "{0}/Desktop/output_file.jpg".format(expanduser("~"))
   
    # should make this global
    ffmpeg_path = path.get_ffmpeg_bin() + '\\'

    if sys.platform == 'win32':
        ffmpeg_path = path.make_windows_style(ffmpeg_path)
        filepath = path.make_windows_style(filepath)
        ffmpeg_executable = 'ffmpeg.exe'
    else:
        ffmpeg_path = path.sanitize(ffmpeg_path)
        filepath = path.sanitize(filepath)
        ffmpeg_executable = 'ffmpeg'

    ffmpeg_command = '"{}{}" '.format(ffmpeg_path, ffmpeg_executable)
    ffmpeg_command += '-i "{}" '.format(filepath)
    # ffmpeg_command += '-filter:v select="eq(n\,0)" -vframes 1'
    ffmpeg_command += '-y '
    ffmpeg_command += '"{}"'.format(output_file)
    subprocess.call(ffmpeg_command, shell = True)
    output_file = path.sanitize(output_file)

    # print "Creating Thumb for %s >> %s"%(filepath,output_file)
    if not os.path.isfile(output_file):
        return
    else:
        return output_file
    '''
예제 #3
0
def probe(filename):
    if not filename:
        return
    
    ffmpeg_path = path.get_ffmpeg_bin() + '/'
    ffmpeg_path = path.sanitize(ffmpeg_path)
    filename = path.sanitize(filename)

    if sys.platform == 'win32':
        ffprobe_executable = 'ffprobe.exe'
    else:
        ffprobe_executable = 'ffprobe'

    ffprobe_command = '"{}{}" '.format(ffmpeg_path,ffprobe_executable)
    ffprobe_command += '-v error  '
    ffprobe_command += '-loglevel quiet  '
    ffprobe_command += '-select_streams v:0 '
    ffprobe_command += '-show_entries stream=width,height,avg_frame_rate,codec_name,duration '
    ffprobe_command += '-show_entries format=duration '
    ffprobe_command += '-of default=noprint_wrappers=1 '
    ffprobe_command += '-print_format json '
    ffprobe_command += ' "{}"'.format(filename)

    try:
        ffprobe_output = subprocess.check_output(ffprobe_command, shell = True).decode('utf-8')
        ffprobe_output = json.loads(ffprobe_output)
        return ffprobe_output
    
    except Exception as err:
        print (u'%s' %(err))
        return
예제 #4
0
def encodeToH264Mov(filepath=None, output_file=""):
    print("ahey")
    ffmpeg_path = path.get_ffmpeg_bin() + '\\'

    if sys.platform == 'win32':
        ffmpeg_path = path.make_windows_style(ffmpeg_path)
        filepath = path.make_windows_style(filepath)
        ffmpeg_executable = 'ffmpeg.exe'
    else:
        ffmpeg_path = path.sanitize(ffmpeg_path)
        filepath = path.sanitize(filepath)
        ffmpeg_executable = 'ffmpeg'

    ffmpeg_command = '"{}{}" '.format(ffmpeg_path, ffmpeg_executable)
    ffmpeg_command += '-i "{}" '.format(filepath)
    # ffmpeg_command += '-filter:v select="eq(n\,0)" -vframes 1'
    ffmpeg_command += '-c:v libx264 -preset fast -tune animation '
    ffmpeg_command += '-y '
    ffmpeg_command += '"{}"'.format(output_file)
    subprocess.call(ffmpeg_command, shell=True)
    output_file = path.sanitize(output_file)
    logger.info('ffmpeg command: {}'.format(ffmpeg_command))

    # print "Creating Thumb for %s >> %s"%(filepath,output_file)
    if not os.path.isfile(output_file):
        return
    else:
        return output_file
예제 #5
0
def encodeToH264Mov(filepath = None, output_file = ""):
    ffmpeg_path = path.get_ffmpeg_bin() + '\\'

    if sys.platform == 'win32':
        filepath = path.make_windows_style(filepath)
        ffmpeg_executable = 'ffmpeg.exe'
        ffmpeg_path = os.path.join(ffmpeg_path, ffmpeg_executable)
        ffmpeg_path = path.make_windows_style(ffmpeg_path)
        output_file = path.make_windows_style(output_file)
    else:
        filepath = path.sanitize(filepath)
        ffmpeg_executable = 'ffmpeg'
        ffmpeg_path = os.path.join(ffmpeg_path, ffmpeg_executable)
        ffmpeg_path = path.sanitize(ffmpeg_path)
        output_file = path.sanitize(output_file)
    
    if not os.path.isfile(ffmpeg_path):
        logger.error("FFMPEG executable missing. No File at: {}".format(ffmpeg_path))
        raise RuntimeError("FFMPEG executable missing")

    filepath = filepath.replace("####", r"%04d")

    ffmpeg_command = [ffmpeg_path]
    ffmpeg_command.extend(['-i', filepath])
    # ffmpeg_command += '-filter:v select="eq(n\,0)" -vframes 1'
    ffmpeg_command.extend(['-c:v', 'libx264', '-preset', 'fast', '-tune', 'animation'])
    ffmpeg_command.extend(['-y'])
    ffmpeg_command.extend([output_file])
    logger.info('ffmpeg command: {}'.format(' '.join(ffmpeg_command)))
    try:
        subprocess.check_output(ffmpeg_command, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as err:
        logger.error("FFMPEG conversion non zero exit: {}".format(err.output))
        raise err    


    # print "Creating Thumb for %s >> %s"%(filepath,output_file)
    if not os.path.isfile(output_file):
        logger.error("FFMPEG conversion from {} to {} not successful. Converted File missing. \n Command used: {}".format(filepath, output_file, ffmpeg_command))
        return
    else:
        return path.sanitize(output_file)
def play_in_default_player(filename):
    filename = path.sanitize(filename)
    filename = path.make_safe(filename)

    get_thumb(filename)
    if sys.platform == 'win32':
        os.system('start {}'.format(filename))
    elif sys.platform == 'darwin':
        os.system('open {}'.format(filename))
    else:
        os.system('open {}'.format(filename))
예제 #7
0
def playblast_with_settings(viewport_preset=None,
                            viewport_preset_yaml=None,
                            **recArgs):
    '''
    Playblast with the user-defined settings
    recArgs are the arguments needed for the capture command
    '''

    # get default viewport preset config
    if viewport_preset and viewport_preset_yaml:
        cache_file = path.get_config_yaml(viewport_preset_yaml)
        viewportArgs = database.read_cache(viewport_preset, cache_file)
    else:
        viewportArgs = {}

    # process filenames
    filepath = recArgs["filename"]
    if not filepath:
        filepath = path.get_default_playblast_folder()

    filepath = path.sanitize(filepath)
    filepath_with_ext = add_extension(filepath, recArgs)
    if is_file_on_disk(
            filepath_with_ext) and not recArgs.get("force_overwrite"):
        filename = os.path.split(filepath_with_ext)[-1]
        message = '[{}] already exists.\nDo you want to replace it?'.format(
            filename)
        if not confirm_overwrite_dialogue(message) == 'yes':
            return

    recArgs["show_ornaments"] = False
    recArgs["viewer"] = False

    # merge with viewport args
    viewport_options = viewportArgs.copy()
    viewport_options.update(recArgs)

    logger.info("viewport_options: {}".format(viewport_options))

    playblast_file = capture.capture(**viewport_options)

    if playblast_file:
        playblast_file = add_extension(playblast_file, recArgs)
        recArgs["filename"] = playblast_file
        database.save_last_recorded(recArgs)
        database.dump_cache({"last_recorded_selection": playblast_file})
        logger.info('Find your recorded file here: {}'.format(playblast_file))
        return playblast_file
    else:
        logger.info("playblast_with_settings failed")
예제 #8
0
def get_current_file():
    # validate file name
    filename = database.read_cache('last_recorded_selection')

    if not filename:
        raise RuntimeError('There is no previously recorded video file.')

    filename = path.sanitize(filename)

    if not os.path.isfile(filename):
        raise RuntimeError('Please provide a valid file.')
        return
    else:
        return filename
예제 #9
0
def modifyGreasePencil(zipname, offset=0):
    if not offset:
        return zipname
    xmlfileName = 'greasePencil.xml'
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        for f in zf.namelist():
            print f
        zipFileXML = zf.open(xmlfileName)
        # Generate temp file name for modified zml file
        tmpname = tempfile.TemporaryFile()
        # modify existing xml file and write to temp file
        modifyXMLData(zipFileXML, tmpname, offset)
        tmpname.seek(0)
        updateZip(zipname, xmlfileName, tmpname.read())
        tmpname.close()
    return path.sanitize(zipname)
예제 #10
0
def get_current_file():
    # validate file name
    filename = database.read_cache('last_recorded_selection')

    if not filename:
        title = 'No File for Upload'
        message = 'There is no previously recorded video file, please record one first through The Widget'
        qt_widgets.WarningDialog(None, title, message)
        return

    filename = path.sanitize(filename)

    if not os.path.isfile(filename):
        title = 'Not a valid file'
        message = 'Please provide a valid file'
        logger.debug("{} is not a valid file".format(filename))
        qt_widgets.WarningDialog(None, title, message)
        return
    else:
        return filename
예제 #11
0
def apply_greasepencil(filename, clear_existing_frames=False):
    import pymel.core as pm
    ctxName = 'syncSketchGreasePencil'

    # file path must be unix style otherwise IO Error by Maya Python zip.py
    filename = path.sanitize(filename)

    # create grease pencil if it doesn't exist
    if not pm.greasePencilCtx(ctxName, exists=True):
        ctx = pm.greasePencilCtx(ctxName)
        pm.setToolTo(ctx)
    else:
        nodeNames = pm.greasePencilCtx(ctxName,sequenceNodeName=True, query=True)
        if nodeNames and clear_existing_frames:
            pm.delete(nodeNames)
            logger.info('Deleted Existing Greasepencil frames ...')
    active_panel = get_active_editor()
    cmds.modelEditor(active_panel, edit=True, greasePencils=True)

    pm.greasePencilCtx(ctxName, edit = True, importArchive =  filename )
예제 #12
0
def add_extension(file):
    # Find out the file extension manually because maya wouldn't
    # return the extension if the the viewer is turned off
    extension = None

    if '.' in file:
        extension = file.rsplit('.', 1)[-1]

    if not extension:
        if sys.platform == 'darwin':
            extension = 'mov'
        elif sys.platform == 'linux2':
            extension = 'mov'
        elif sys.platform == 'win32':
            extension = 'avi'
        else:
            extension = 'mov'

    file = '{}.{}'.format(file.rsplit('.', 1)[0], extension)
    return path.sanitize(file)
예제 #13
0
def add_extension(file):
    '''
    Find out the file extension manually because maya wouldn't
    return the extension if the the viewer is turned off
    '''
    extension = None
    #Assumptions that might not hold up, we should maybe consider setting
    #mov as a default for all
    if '.' in file:
        extension = file.rsplit('.', 1)[-1]

    if not extension:
        if sys.platform == 'darwin':
            extension = 'mov'
        elif sys.platform == 'linux2':
            extension = 'mov'
        elif sys.platform == 'win32':
            extension = 'mov'
        else:
            extension = 'mov'

    file = '{}.{}'.format(file.rsplit('.', 1)[0], extension)
    return path.sanitize(file)
예제 #14
0
def _record():
    # filename & path
    filepath = database.read_cache('ps_directory_lineEdit')
    filename = database.read_cache('us_filename_lineEdit')
    clipname = database.read_cache('ps_clipname_lineEdit')

    if not filepath or not filename:
        title = 'Playblast Location'
        message = 'Please specify playblast file name and location.'
        return
        qt_widgets.WarningDialog(None, title, message)
        filepath = os.path.expanduser('~/Desktop/playblasts/')
        filename = 'playblast'
    if clipname:
        filename = filename + clipname
    filepath = path.sanitize(os.path.join(filepath, filename))

    # preset
    preset_file = path.get_config_yaml(PRESET_YAML)
    preset_data = database._parse_yaml(preset_file)
    preset_name = database.read_cache('current_preset')
    preset = preset_data.get(preset_name)

    start_frame, end_frame = maya_scene.get_InOutFrames(
        database.read_cache('current_range_type'))
    start_frame = database.read_cache('frame_start')
    end_frame = database.read_cache('frame_end')

    #setting up args for recording
    recArgs = {
        "show_ornaments":
        False,
        "start_frame":
        start_frame,
        "end_frame":
        end_frame,
        "camera":
        database.read_cache('selected_camera'),
        "format":
        preset.get('format'),
        "viewer":
        True if database.read_cache('ps_play_after_creation_checkBox')
        == 'true' else False,
        "filename":
        filepath,
        "width":
        preset.get('width'),
        "height":
        preset.get('height'),
        "overwrite":
        True if database.read_cache('ps_force_overwrite_checkBox') == 'true'
        else False,
        "compression":
        preset.get('encoding'),
        "off_screen":
        True
    }
    logger.info("recArgs: {}".format(recArgs))

    # read from database Settings
    playblast_file = maya_scene.playblast_with_settings(
        viewport_preset=database.read_cache('current_viewport_preset'),
        viewport_preset_yaml=VIEWPORT_PRESET_YAML,
        **recArgs)

    return playblast_file
예제 #15
0
def playblast(filepath = None, width = 1280, height = 720, start_frame = 0, end_frame = 0, view_afterward = False, force_overwrite=False):
    '''
    Playblast with the pre-defined settings based on the user's OS
    '''
    logger.info("Playblast this:")
    if not filepath:
        filepath = path.get_default_playblast_folder()


    if filepath:
        filepath = path.sanitize(filepath)
        if os.path.isfile(filepath) and not force_overwrite:
            filename = os.path.split(filepath)[-1]
            message = '[{}] already exists.\nDo you want to replace it?'.format(filename)

            if not confirm_overwrite_dialogue(message) == 'yes':
                return


    recArgs = {
        "width": width,
        "height": height,
        "start_frame": start_frame,
        "end_frame": end_frame
    }
    logger.info("recargsplayblast (): {}".format(recArgs))
    # record with OS specific Fallback Settings
    os_settings = {
        "darwin": [
            {
                "format": 'qt',
                "compression": 'H.264',
            },
            {
                "format": 'avfoundation',
                "compression": 'H.264',
            }
        ],
        "linux2": [
            {
                "format": 'movie',
                "compression": 'H.264',
            },
            {
                "format": 'movie',
                "compression": '',
            }
        ],
        "linux2": [
            {
                "win32": 'qt',
                "compression": 'H.264',
            },
            {
                "format": 'movie',
                "compression": '',
            }
        ]
    }

    for platform, settingsList in os_settings.iteritems():
        if sys.platform == platform:
            for setting in settingsList:
                recArgs["compression"]  = setting["compression"]
                try:
                    logger.info("recArgs playblast(): {}".format(**recArgs))
                    playblast_file = _playblast_with_settings(**recArgs)
                    return playblast_file

                except Exception as err:
                    logger.info(u'%s' %(err))
예제 #16
0
def add_extension(file, rec_args):
    """
    Use the recording arguments provided to playblast to add appropriate extension to file path.
    In case the file already ends with the computed extension, the provided file path will not be changed.

    Args:
        file (string): file path without extension
        rec_args (dict): recording arguments used to playblast

    Returns:
        string: file path with extension
    """

    file_format = rec_args["format"]
    compression = rec_args["compression"]

    # Extension outputed by maya when following keys are used as expressions
    # Tested with Maya2020 on Win10
    image_extensions = {
        "gif": "gif",
        "si": "pic",
        "rla": "rla",
        "tif": "tif",
        "tifu": "tif",
        "sgi": "sgi",
        "als": "als",
        "maya": "iff",
        "jpg": "jpg",
        "eps": "eps",
        "cin": "cin",
        "yuv": "yuv",
        "tga": "tga",
        "bmp": "bmp",
        "png": "png",
        "psd": "psd",
        "dds": "dds",
        "psdLayered": "psd",
    }

    if file_format == "avi":
        extension = "avi"
    elif file_format == "qt":
        extension = "mov"
    elif file_format == "image":
        try:
            image_extension = image_extensions[compression]
        except KeyError as e:
            logger.error(
                "No extension known for image sequence with compression {}".
                format(compression))
            raise e
        extension = "####.{}".format(
            image_extension)  #TODO: assumption frame padding 4 might fail

    else:
        logger.error("No extension known for format {}".format(file_format))
        raise KeyError

    if file.endswith(extension):
        logger.info(
            "File {} already ends with {}. No Extension added. ".format(
                file, extension))
        return file

    file_with_ext = '{}.{}'.format(file, extension)
    logger.info("Added extension {} to file {} -> {} ".format(
        extension, file, file_with_ext))
    return path.sanitize(file_with_ext)