Пример #1
0
    def mediaCodec_flv2f4v(self, logname):
        '''mp4 to flv'''
        ret = 0
        for i in range(0,100):
            cmd_str = ""
            in_file_flv = self.param["slice_base"] + str(i) + ".flv"
            out_file_f4v = self.param["slice_base"] + str(i) + ".f4v"
            #if slice exist
            if os.path.exists(in_file_flv):
                cmd_str += mediabase.MEDIA_YAMDI + " -i " + in_file_flv + " -o " + out_file_f4v
                cmd_str += " -c 'mediaCodec tools' 2>>%s 1>&2 " % ( self.param["tmp_log"] )
                ret = mediabase.run_cmd( cmd_str, logname )
                if ret != 0:
                    mediabase.addlog("slice[%d] flv add meta to f4v error!" % i, logname)
                    return ret
                self.param["f4v_num"] = i + 1
                duration = self.mediaCodec_getdur(out_file_f4v, logname)
                if duration != "NULL":
                    index = str(i) + "_dur"
                    self.param[index] = duration
                else:
                    mediabase.addlog("get f4v duration error!", logname)
                    ret = 1
                    return ret
            else:
                #if not exist break
                break

        return ret
Пример #2
0
    def mediaCodec_get_video_param(self, logname):
        '''scan input video'''
        ret = 0
        scan_result = mediaCodec_scan_param.mediaCodec_scan_param( mediabase.MEDIA_FFPROBE,
                      self.param["queuefile"], 0, logname)
        if scan_result['error_code'] != 0:
            mediabase.addlog("scan input video [%s] error" % self.param["queuefile"], logname)
            ret = 1
            return ret
        else:
            video_info = scan_result["data"]

            if video_info.has_key("Video"):
                self.param["input_w"] = video_info["Video"]["0"]["width"]
                self.param["input_h"] = video_info["Video"]["0"]["height"]
            else:
                ret = 1
                return ret
        return ret
Пример #3
0
    def mediaCodec_mp4_movflag(self, logname):
        '''mp4 to flv'''
        ret = 0
        cmd_str = ""
        cmd_str += mediabase.MEDIA_QTFAST + " %s  %s " % ( self.param["basemp4"] , self.param["output_mp4"] )
        cmd_str += " 2>>%s 1>&2" % ( self.param["tmp_log"] )
        ret = mediabase.run_cmd( cmd_str, logname )
        if ret != 0:
            mediabase.addlog("mp4 mov flag error!", logname)
            return ret
        duration = self.mediaCodec_getdur(self.param["output_mp4"], logname)
        if duration != "NULL":
            self.param["mp4_dur"] = duration
        else:
            mediabase.addlog("get mp4 duration error!", logname)
            ret = 1
            return ret

        return ret
Пример #4
0
 def mediaCodec_mp42flv(self, logname):
     '''mp4 to flv'''
     ret = 0
     for i in range(0,100):
         cmd_str = ""
         in_file_mp4 = self.param["slice_base"] + str(i) + ".mp4"
         out_file_flv = self.param["slice_base"] + str(i) + ".flv"
         #if slice exist
         if os.path.exists(in_file_mp4):
             if self.param["aid"] != "":
                 cmd_str += mediabase.MEDIA_FFMPEG + " -i " + in_file_mp4 + " -f flv -vcodec copy -acodec copy -y "
             else:
                 cmd_str += mediabase.MEDIA_FFMPEG + " -i " + in_file_mp4 + " -f flv -vcodec copy -an -y "
             cmd_str += out_file_flv
             cmd_str += " 2>>%s 1>&2" % ( self.param["tmp_log"] )
             ret = mediabase.run_cmd( cmd_str, logname )
             if ret != 0:
                 mediabase.addlog("slice[%d] mp4 to flv error!" % i, logname)
                 return ret
         else:
             #if not exist break
             break
     return ret
Пример #5
0
    def mediaCodec_getdur(self, input_file, logname):
        '''get output dur'''
        scan_result = mediaCodec_scan_param.mediaCodec_scan_param( mediabase.MEDIA_FFPROBE,
                      input_file, 0, logname)
        if scan_result['error_code'] != 0:
            mediabase.addlog("scan input video [%s] error" % input_file, logname)
            out_dur = "NULL"
            return out_dur
        else:
            video_info = scan_result["data"]

            if video_info.has_key("Video"):
                video_dur = video_info["Video"]["0"]["duration"]
            else:
                mediabase.addlog("scan video no duration [%s] error" % input_file, logname)
                out_dur = "NULL"
                return out_dur
            if video_info.has_key("Audio"):
                audio_dur = video_info["Audio"]["0"]["duration"]
            else:
                mediabase.addlog("scan audio no duration [%s] error" % input_file, logname)
                out_dur = "NULL"
                return out_dur

            if abs(int(video_dur) - int(audio_dur))/1000 > int(video_dur)/1000/5: #video and audio len_diff big than 1/5
                mediabase.addlog("scan video and audio diff len [%s] error" % input_file, logname)
                out_dur = "NULL"
                return out_dur

        scan_cmd = mediabase.MEDIA_FFMPEG +  " -i %s 2>&1 | grep Duration" % ( input_file )
        mediabase.addlog("run cmd:%s" % scan_cmd, logname)
        result = commands.getstatusoutput(scan_cmd)
        if result[0] != 0:
            mediabase.addlog( "call function error: %s " % scan_cmd, logname )
            out_dur = "NULL"
            return out_dur

        log_line = result[1].splitlines()
        log_list = log_line[0].split()
        if "Duration" not in log_list[0]:
            out_dur = "NULL"
            return out_dur
        else:
            out_dur = log_list[1].strip(",")
            return out_dur
Пример #6
0
    def mediaCodec_encode_pic(self, logname):
        '''encode pic'''

        result_pic = {}
        result_pic["error_code"] = 0

        #step1.1: get duration
        file_dur = 0
        scan_result = mediaCodec_scan_param.mediaCodec_scan_param( mediabase.MEDIA_FFPROBE,
                      self.param["queuefile"] , 0, logname)
        if scan_result['error_code'] != 0:
            mediabase.addlog("encode pic: scan input video [%s] error" % self.param["queuefile"], logname)
            result_pic["error_code"] = 1
            return result_pic
        else:
            video_info = scan_result["data"]

            if video_info.has_key("duration"):
                file_dur = int(video_info["duration"]) / 1000
            else:
                mediabase.addlog("encode pic:scan video no duration [%s] error" % self.param["queuefile"], logname)
                result_pic["error_code"] = 1
                return result_pic

        #step1: cut time
        if len(self.param["pic_time"]) != 0:
            pic_time_list = self.param["pic_time"].split(";")
        else:
            mediabase.addlog("input pic time error[%s]!" % (self.param["pic_time"]), logname)
            result_pic["error_code"] = 1
            return result_pic

        #step2: format if not valid use default jpg
        if self.param["pic_format"] != "1" and self.param["pic_format"] != "2":
            self.param["pic_format"] = "2"

        #step3: get default dimension
        pic_dimension = "480x320"
        if len(self.param["dimension"]) != 0:
            pic_dimension_list = self.param["dimension"].split("x")
            if len(pic_dimension_list) != 2 or self.param["dimension"].count('.') > 0:
                mediabase.addlog("input dimension error[%s]!" % ( self.param["dimension"] ), logname)
                result_pic["error_code"] = 1
                return result_pic
            else:
                if pic_dimension_list[0].isdigit() and pic_dimension_list[1].isdigit():
                    pic_dimension = self.param["dimension"]
        else:
            mediabase.addlog("input dimension error[%s]!" % ( self.param["dimension"] ), logname)
            result_pic["error_code"] = 1
            return result_pic

        pic_list = []
        idx = -1
        for i in range( 0, len(pic_time_list) ):
            if pic_time_list[i] == "" or pic_time_list[i].count('.') > 0 or not pic_time_list[i].isdigit():
                continue
            if int(pic_time_list[i]) < 0 or int(pic_time_list[i]) > file_dur:
                continue
            idx = idx + 1
            pic_elem = {}
            if self.param["pic_format"] == "1":
                pic_name = self.param["output_pic"] + str(idx) + ".png"
            else:
                pic_name = self.param["output_pic"] + str(idx) + ".jpg"

            cmd_str = ""
            cmd_str += mediabase.MEDIA_FFMPEG + " -ss %s -i %s " % (pic_time_list[i], self.param["queuefile"])
            cmd_str += " -vframes 1 -f image2 -s %s -y %s " % ( pic_dimension, pic_name)
            cmd_str += " 2>>%s 1>&2" % ( self.param["tmp_log"] )

            ret = mediabase.run_cmd( cmd_str, logname )
            if ret != 0:
                mediabase.addlog("get pic error[%s]!" % ( pic_time_list[i] ), logname)
                result_pic["error_code"] = 1
                return result_pic

            pic_elem["time"] = pic_time_list[i]
            pic_elem["pic"] = pic_name
            pic_list.append(pic_elem)

        result_pic["data"] = pic_list
        return result_pic
Пример #7
0
    def mediaCodec_ffmpeg_encode_cmd(self, passtype, logname):
        ''' '''
        cmd_str = ""

        if passtype != 1 and passtype != 2:
            mediabase.addlog( " encode pass not valid! ", logname )
            return cmd_str

        cmd_str += mediabase.MEDIA_FFMPEG + " -i " + self.param["queuefile"]

        #get subtitle and scale param
        if self.param.has_key("input_w") and self.param.has_key("input_h"):
            input_width = int(self.param["input_w"])
            input_height = int(self.param["input_h"])
        else:
            mediabase.addlog( " no source width and height! ", logname )
            cmd_str = ""
            return cmd_str

        crop_cmd = ""
        if self.param.has_key("crop"):
            crop_list = self.param["crop"].split(":")
            if string.atoi(crop_list[0]) > 0 or string.atoi(crop_list[1]) > 0 \
                   or string.atoi(crop_list[2]) > 0 or string.atoi(crop_list[3]) > 0:
                if not (input_width == string.atoi(crop_list[0]) and input_height == string.atoi(crop_list[1])):
                    crop_width = int(crop_list[0])
                    crop_height = int(crop_list[1])
                    crop_cmd = ",crop=" + self.param["crop"]
                else:
                    crop_width = int(input_width)
                    crop_height = int(input_height)
            else:
                crop_width = int(input_width)
                crop_height = int(input_height)
        else:
            crop_width = int(input_width)
            crop_height = int(input_height)

        if self.param.has_key("logofile") and self.param["logofile"] != "":
            logo_percent = int(mediabase.LOGO_SIZEP)
            #get logo cmd_line, just crop,scale,and add sub, logo
            video_filter_cmd = " -vf 'movie=%s,scale=-1:%s[logo];" \
                               % ( self.param["logofile"], str(int(crop_height/logo_percent)) )
            video_filter_cmd += "[in]idet,yadif=0:-1:1" + crop_cmd
            if self.param.has_key("assfile") and self.param["assfile"] != "":
                video_filter_cmd += ",ass=%s" % ( self.param["assfile"] )

            logo_list = self.param["logo_pos"].split(":")
            #width, height, right_side, top_side
            #(1)width+right_side < crop_width
            #(2)height+top_side < crop_height
            if int(logo_list[0]) + int(logo_list[2]) > crop_width or \
               int(logo_list[1]) + int(logo_list[3]) > crop_height:
                mediabase.addlog( " the log position is not right:%s! " % ( self.param["logo_pos"] ), logname )
                cmd_str = ""
                return cmd_str

            #overlay is top_left pos
            video_filter_cmd += "[normal];[normal][logo]overlay=main_w-%d:%d" \
                                % ( int(int(logo_list[0])*crop_height/logo_percent/int(logo_list[1])) \
                                    + int(logo_list[2]), int(logo_list[3]) )

            if int(self.param["height"]) <= crop_height:
                cmd_height = int(self.param["height"])
                cmd_height = cmd_height / 16 * 16
                video_filter_cmd += ",scale=trunc((oh*a*sar+8)/16)*16:" + str(cmd_height)
            else:
                cmd_height = crop_height
                cmd_height = cmd_height / 16 * 16
                video_filter_cmd += ",scale=trunc((oh*a*sar+8)/16)*16:" + str(cmd_height)

            video_filter_cmd += "'"
        else:
            #get no logo cmd_line, just crop, add sub, scale
            video_filter_cmd = " -vf 'idet,yadif=0:-1:1" + crop_cmd

            if self.param.has_key("assfile") and self.param["assfile"] != "":
                video_filter_cmd += ",ass=%s" % ( self.param["assfile"] )

            if int(self.param["height"]) <= crop_height:
                cmd_height = int(self.param["height"])
                cmd_height = cmd_height / 16 * 16
                video_filter_cmd += ",scale=trunc((oh*a*sar+8)/16)*16:" + str(cmd_height)
            else:
                cmd_height = crop_height
                cmd_height = cmd_height / 16 * 16
                video_filter_cmd += ",scale=trunc((oh*a*sar+8)/16)*16:" + str(cmd_height)

            video_filter_cmd += "'"

        cmd_str += video_filter_cmd
        if self.param["aid"] != "":
            cmd_str += " -map 0:v -map 0:a:%s " % self.param["aid"]                        #map
        else:
            cmd_str += " -map 0:v "

        #video encode
        cmd_str += " -vcodec libx264 -r %s -b:v %s -pix_fmt yuv420p " % \
                    ( self.param["vfps"], self.param["vbitrate"] )                     #vcodec param
        cmd_str += " -x264opts %s" % ( self.param["x264opt"] )                         #x264 param
        cmd_str += ":keyint=%d " % ( int(float(self.param["vfps"]))*10 )               #video gop

        if passtype == 2:
            cmd_str += " -pass 2 -passlogfile %s " % self.param["passtmp"]
        else:
            cmd_str += " -pass 1 -passlogfile %s " % self.param["passtmp"]

        #audio encode
        if self.param["aid"] != "":
            #audiogain
            if self.param.has_key("adjust_db") and self.param["adjust_db"] != "0dB":
                cmd_str += " -af volume=%s " % self.param["adjust_db"]

            #audio encode
            cmd_str += " -acodec libfdk_aac -profile:a %s -ar %s -b:a %s -ac %s -strict -2 " % \
                       ( self.param["aaclevel"], self.param["asample"], self.param["abitrate"],
                         self.param["achannel"] )               #video gop
        else:
            cmd_str += " -an "

        #output
        if passtype == 2:
            cmd_str += " -y %s 2>>%s 1>&2 " % ( self.param["basemp4"], self.param["enc_log"] )
        else:
            cmd_str += " -f mp4 -y /dev/null 2>%s 1>&2 " % ( self.param["enc_log"] )

        return cmd_str
Пример #8
0
def srt2ass( input_name, output_name, logname ):
    ''''''
    mediabase.addlog(" python mediaCodec_srt2ass.py -i %s -o %s\n" % (input_name, output_name), logname)
    result_error_code = MEDIACODEC_SRT2ASS_OK

    #step1: check input
    if input_name != None:
        input_file = input_name
    else:
        print " python mediaCodec_srt2ass.py -i input -o output "
        mediabase.addlog("   need input file", logname)
        result_error_code = MEDIACODEC_SRT2ASS_INPUT_ERROR
        return result_error_code

    if output_name != None:
        output_file = output_name
    else:
        print " python mediaCodec_srt2ass.py -i input -o output "
        mediabase.addlog("   need output file", logname)
        result_error_code = MEDIACODEC_SRT2ASS_INPUT_ERROR
        return result_error_code

    if not os.path.isfile (input_name):
        mediabase.addlog("  input file not exist: %s" % input_name, logname )
        result_error_code = MEDIACODEC_SRT2ASS_INPUT_FILE_ERROR
        return result_error_code

    if ".ass" not in input_file and ".ASS" not in input_file and ".srt" not in input_file and ".SRT" not in input_file:
        mediabase.addlog("   input file not support: %s!" % input_file, logname)
        result_error_code = MEDIACODEC_SRT2ASS_INPUT_NOTSUPPORT
        return result_error_code

    mediabase.addlog("   Process start: %s" % input_name, logname )

    #step2: change to utf8
    try:
        fp_input  = open(input_file,"r")
    except:
        mediabase.addlog("open input file error!", logname)
        result_error_code = MEDIACODEC_SRT2ASS_INPUT_FILE_ERROR
        return result_error_code

    orig_content = fp_input.read()

    try:
        fp_input.close()
    except:
        mediabase.addlog("close input file error!", logname)
        result_error_code = MEDIACODEC_SRT2ASS_INPUT_FILE_ERROR
        return result_error_code

    detect_type = chardet.detect(orig_content)['encoding']
    mediabase.addlog( "   input code   : %s " % detect_type, logname )

    encode_type = ['GB2312', 'GBK', 'GB18030']
    if detect_type in encode_type:
        for i in range(0,3):
            tmp_type = encode_type[i]
            try:
                sub_origin = orig_content.decode( tmp_type )
                mediabase.addlog("   detect type  : %s OK!" % tmp_type, logname )
                break
            except:
                mediabase.addlog("   detect type  : %s not right!" % tmp_type, logname )
                if i < 2:
                    continue
                else:
                    mediabase.addlog("   input file not support!", logname)
                    result_error_code = MEDIACODEC_SRT2ASS_INPUT_NOTSUPPORT
                    return result_error_code
    else:
        try:
            sub_origin = orig_content.decode( chardet.detect(orig_content)['encoding'] )
        except:
            mediabase.addlog("   input file not support!", logname)
            result_error_code = MEDIACODEC_SRT2ASS_INPUT_NOTSUPPORT
            return result_error_code

    sub_utf8 = sub_origin.encode('utf8')

    if sub_utf8[:3] == codecs.BOM_UTF8:
        sub_utf8 = sub_utf8[3:]

    mediabase.addlog( "   output code  : %s " % chardet.detect(sub_utf8)['encoding'], logname )

    #step3: srt to ass
    #step3.1: if srt or ass, just copy
    if ".ass" not in input_file and ".ASS" not in input_file and ".srt" not in input_file and ".SRT" not in input_file:
        mediabase.addlog("   input file not support: %s!" % input_file, logname)
        result_error_code = MEDIACODEC_SRT2ASS_INPUT_NOTSUPPORT
        return result_error_code
    else:
        #step3.2: srt or ass
        #step3.2.1: generate header
        final_content = []
        final_content.append( "[Script Info]\n" )
        final_content.append( "ScriptType: v4.00+\n" )
        final_content.append( "Title:\n" )
        final_content.append( "Original Script:\n" )
        final_content.append( "Synch Point:0\n" )
        final_content.append( "Collisions:Normal\n" )
        final_content.append( "PlayResX:1280\n" )
        final_content.append( "PlayResY:720\n" )
        final_content.append( "\n" )
        final_content.append( "[V4+ Styles]\n" )
        final_content.append( "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n" )
        final_content.append( "Style: Default,Microsoft YaHei,50,&H00FFFFFF,&HF0000000,&H00000000,&HF0000000,-1,0,0,0,100,100,0,0.00,1,2,0,2,30,30,10,134\n" )
        final_content.append( "\n" )
        final_content.append( "[Events]\n" )
#        final_content.append( "Format: Layer, Start, End, Style, Actor, MarginL, MarginR, MarginV, Effect, Text\n" )
        final_content.append( "Format: Layer, Start, End, Style, Text\n" )

        sub_list = sub_utf8.splitlines()

        #step3.2.2: ass
        if ".ass" in input_file or ".ASS" in input_file:
            mediabase.addlog( "   input is ass: changed header and copy!", logname )

            #check every line
            ass_list = []
            srt_line_num = 0
            for line in sub_list:
                srt_line_num = srt_line_num + 1
                line = line.strip()

                if re.search(r'Dialogue:', line) and re.search(r'Default', line):
                    ass_list.append( line + '\n' );
                    split_text = re.split( ',', line )
                    time_start = split_text[1]
                    time_stop  = split_text[2]
                    if time_start > time_stop:
                        mediabase.addlog( "  sub_warning timecode line [%d]: %s " %( srt_line_num, line ), logname )

            #sort subtitle
            ass_list.sort()
            final_content = final_content + ass_list

        else:
            mediabase.addlog( "   input is srt: changed to ass!", logname )
            #step3.2.3: srt
            #change every line
            ass_list = []
            line_num = 0
            srt_line_num = 0
            line_content=''
            srt_idx = 0
            for line in sub_list:
                srt_line_num = srt_line_num + 1
                line = line.strip()

                if str(line).isdigit():
                    if srt_idx != 0:
                        ass_list.append( line_content + '\n' )
                        srt_idx = 0
                    line_content='Dialogue: 0,'
                    continue
                elif line.strip() == '':
                    continue
                elif "-->" in line and ":" in line:  #parse time code
                    line_num = line_num + 1
                    time_list = line.split("-->")
                    if "," in time_list[0] and "," in time_list[1]:
                        time_start_list = time_list[0].split(",")
                        time_stop_list = time_list[1].split(",")
                        time_start = time_start_list[0].strip()[1:] + '.' + time_start_list[1].strip()[:2]
                        time_stop  = time_stop_list[0].strip()[1:] + '.' + time_stop_list[1].strip()[:2]
                    else:
                        mediabase.addlog( "   cur line time code invalid: %s" % line, logname )
                        time_start = "0:00:00.00"
                        time_stop  = "0:00:00.00"

                    if time_start > time_stop:
                        mediabase.addlog( "  sub_warning timecode line [%d]: %s " %( line_num, line ), logname )

                    line_content = line_content + time_start + ',' + time_stop + ',Default,'
                else:  #add subtitle
                    if srt_idx > 0:
                        line_content = line_content + ' \N ' + line
                    else:
                        line_content = line_content + line
                    srt_idx = srt_idx + 1

            #add last subtitle
            if srt_idx != 0:
                ass_list.append( line_content + '\n' )

            #sort subtitle
            ass_list.sort()
            final_content = final_content + ass_list

        #step3.4: output
        try:
            fp_output  = open(output_file,"w")
        except:
            mediabase.addlog( "open output file error!", logname )
            result_error_code = MEDIACODEC_SRT2ASS_INPUT_FILE_ERROR
            return result_error_code

        for element in final_content:
            fp_output.write( element )

        try:
            fp_output.close()
        except:
            mediabase.addlog( "close input file error!", logname )
            result_error_code = MEDIACODEC_SRT2ASS_INPUT_FILE_ERROR
            return result_error_code

    mediabase.addlog( "   trans over!", logname )
    return result_error_code
Пример #9
0
def transcode(test_json):
    '''transcode flow'''
    outinfo = {}
    outinfo["error_code"] = mediabase.SUCCESS
    outinfo["error_msg"] = "ok"
    outdata = {}

    param = json.loads(test_json)
    logname = param["flow_log"]

    mediabase.addlog("=================================================================", logname)
    mediabase.addlog("======================= task start ==============================", logname)
    mediabase.addlog("=================================================================", logname)

    #step1: check input file and parse
    mediabase.addlog("step1: check input file and parse", logname)
    #step1.1: check input file
    #input video
    if not os.path.exists(param["queuefile"] ):
        mediabase.addlog("the input file %s is not exist" % param["queuefile"], logname)
        error_code = mediabase.ERROR_INPUT_NOEXIST
        outinfo["error_code"] = error_code
        outinfo["error_msg"] = "the input video file is not exist"
        return json.dumps(outinfo)

    #input srt
    if param["srtfile"] != "":
        if not os.path.exists(param["srtfile"] ):
            mediabase.addlog("the input file %s is not exist" % param["srtfile"], logname)
            error_code = mediabase.ERROR_INPUT_NOEXIST
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "the input srt file is not exist"
            return json.dumps(outinfo)

    #input logo
    if param["logofile"] != "":
        #if exist
        if not os.path.exists(param["logofile"] ):
            mediabase.addlog("the input file %s is not exist" % param["logofile"], logname)
            error_code = mediabase.ERROR_INPUT_NOEXIST
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "the input logo file is not exist"
            return json.dumps(outinfo)

        #check if jpg
        cmd_str = "file %s" % param["logofile"]
        result = commands.getstatusoutput(cmd_str)
        if result[0] != 0:
            error_code = mediabase.ERROR_INPUT_PARAM_VALID
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "the input logo file is error"
            return json.dumps(outinfo)
        else:
            logo_string = result[1]
            if "jpg" not in param["logofile"].lower() and "png" not in param["logofile"].lower():
                mediabase.addlog("the input file %s is not support" % param["logofile"], logname)
                error_code = mediabase.ERROR_INPUT_PARAM_VALID
                outinfo["error_code"] = error_code
                outinfo["error_msg"] = "the input logo file is not support: should 'jpg/png'"
                return json.dumps(outinfo)

        #check pos
        if param.has_key("logo_pos"):
            if param["logo_pos"] == "" or param["logo_pos"] == "0:0:0:0":
                mediabase.addlog("the input logo pos %s is not support" % param["logo_pos"], logname)
                error_code = mediabase.ERROR_INPUT_PARAM_VALID
                outinfo["error_code"] = error_code
                outinfo["error_msg"] = "the input logo pos not valid[width:height:right:top]!"
                return json.dumps(outinfo)
            else:
                logo_pos_list = param["logo_pos"].split(":")
                if int(logo_pos_list[0]) == 0 or int(logo_pos_list[1]) == 0:
                    mediabase.addlog("the input logo pos %s is not support" % param["logo_pos"], logname)
                    error_code = mediabase.ERROR_INPUT_PARAM_VALID
                    outinfo["error_code"] = error_code
                    outinfo["error_msg"] = "the input logo pos not valid[width:height:right:top]!"
                    return json.dumps(outinfo)

    #input crop
    if param.has_key("crop"):
        if param["crop"] == "":
            mediabase.addlog("the input crop %s is not support" % param["crop"], logname)
            error_code = mediabase.ERROR_INPUT_PARAM_VALID
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "the input crop not valid!"
            return json.dumps(outinfo)

    #input fps
    if param.has_key("ifps"):
        tmp_fps = param["ifps"]
        tmp_fps = tmp_fps.replace('.','')
        if tmp_fps.isdigit() and not param["ifps"].count('.') > 1:
            fps_num = string.atof(param["ifps"])
            if fps_num < 5 or fps_num > 30:
                mediabase.addlog("the input ifps %s is not support" % param["ifps"], logname)
                error_code = mediabase.ERROR_INPUT_PARAM_VALID
                outinfo["error_code"] = error_code
                outinfo["error_msg"] = "the input ifps not valid[15-30]!"
                return json.dumps(outinfo)
        else:
            mediabase.addlog("the input ifps %s is not support" % param["ifps"], logname)
            error_code = mediabase.ERROR_INPUT_PARAM_VALID
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "the input ifps not valid!"
            return json.dumps(outinfo)

    #input version_id
    if param["version_id"] != "0" and param["version_id"] != "1" and param["version_id"] != "2" and param["version_id"] != "3":
        error_code = mediabase.ERROR_INPUT_VERSION_ID
        outinfo["error_code"] = error_code
        outinfo["error_msg"] = "the input version id not support,should '0','1','2','3'!"
        return json.dumps(outinfo)

    #get encode_video, encode_pic flag
    encode_pic_flag = 0
    if param["version_id"] == "3":
        encode_pic_flag = 1

    #step1.2: parse
    transcode = mediaCodec_service.Cservice(param)
    transcode.mediaCodec_parse_task_param(mediabase.MEDIA_XMLFILE)
    mediabase.addlog("step1: ok!", logname)

    #step1.3: if encode pic,encode and return
    if encode_pic_flag == 1:
        mediabase.addlog("step1.3: start encode pic", logname)
        result = transcode.mediaCodec_encode_pic(logname)
        if result["error_code"] != 0:
            mediabase.addlog("encode pic error!", logname)
            outinfo["error_code"] = mediabase.ERROR_ENCODE_PIC_ERROR
            outinfo["error_msg"] = "encode pic error"
            return json.dumps(outinfo)

        if result.has_key("data"):
            outdata["pic_out"] = result["data"]
        outinfo["data"] = outdata
        mediabase.addlog("step1.3: ok!", logname)

        mediabase.addlog("=================================================================", logname)
        mediabase.addlog("======================= task over ==============================", logname)
        mediabase.addlog("=================================================================", logname)
        return json.dumps(outinfo)

    #step2: if has subtitle, output ass
    mediabase.addlog("step2: srt to ass", logname)
    if param.has_key("srtfile") and param["srtfile"] != "" and param.has_key("assfile") and param["assfile"] != "":
        sub_info = mediaCodec_srt2ass.srt2ass( param["srtfile"], param["assfile"], logname )
        mediabase.addlog("subtitle info: %s" % sub_info, logname)
        if sub_info['error_code'] != 0:
            mediabase.addlog("the srt file %s is not support" % param["srtfile"], logname)
            outinfo["error_code"] = mediabase.ERROR_SUBTITLE_NOT_SUPPORT
            outinfo["error_msg"] = "the input subtitle not support"
            return json.dumps(outinfo)
        else:
            param["assfile"] = ""
    else:
        param["assfile"] = ""
    mediabase.addlog("step2: ok!", logname)

    #step3: get encode param
    mediabase.addlog("step3: get param", logname)
    ret = transcode.mediaCodec_parse_task_param( mediabase.MEDIA_XMLFILE )
    if ret != 0:
        mediabase.addlog("parse param error!", logname)
        outinfo["error_code"] = mediabase.ERROR_PARSE_PARAM
        outinfo["error_msg"] = "parse param error"
        return json.dumps(outinfo)
    mediabase.addlog("parse param: %s!" % param, logname)
    mediabase.addlog("step3: ok!", logname)

    #step4: get audio volume static
    mediabase.addlog("step4: audiogain", logname)
    if param.has_key("aid") and param["aid"] != "":  #has audio
        volume_info = mediaCodec_audiogain.mediaCodec_scan_volume(mediabase.MEDIA_FFMPEG, param["queuefile"], param, logname)
        mediabase.addlog("audio volume info: %s" % volume_info, logname)
        if volume_info["error_code"]:
            mediabase.addlog("mediaCodec_scan_volume: %s error!" % param["queuefile"], logname)
            error_code = mediabase.ERROR_AUDIO_SCAN_ERROR
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "scan audio volume error!"
            return json.dumps(outinfo)
        else:
            if volume_info.has_key("adjust_db"):
                param["adjust_db"] = volume_info["adjust_db"]
            else:
                param["adjust_db"] = "0dB"
    else:
        param["adjust_db"] = "0dB"
    mediabase.addlog("step4: ok!", logname)

    #step5: start 1 pass
    mediabase.addlog("step5: 1 pass", logname)
    command_pass1 = transcode.mediaCodec_ffmpeg_encode_cmd( 1, logname )
    if command_pass1 == "":
        error_code = mediabase.ERROR_GET_PASS1_CMD
        outinfo["error_code"] = error_code
        outinfo["error_msg"] = "the get pass1 command line error!"
        return json.dumps(outinfo)

    ret = mediabase.run_cmd( command_pass1, logname )
    if ret != 0:
        error_code = mediabase.ERROR_TRANSCODE_PASS1
        outinfo["error_code"] = error_code
        outinfo["error_msg"] = "encode pass1 error"
        return json.dumps(outinfo)
    mediabase.addlog("step5: ok!", logname)

    #step6: start 2 pass
    mediabase.addlog("step6: 2 pass", logname)
    command_pass2 = transcode.mediaCodec_ffmpeg_encode_cmd( 2, logname )
    if command_pass1 == "":
        error_code = mediabase.ERROR_GET_PASS2_CMD
        outinfo["error_code"] = error_code
        outinfo["error_msg"] = "the get pass2 command line error!"
        return json.dumps(outinfo)

    ret = mediabase.run_cmd( command_pass2, logname )
    if ret != 0:
        error_code = mediabase.ERROR_TRANSCODE_PASS2
        outinfo["error_code"] = error_code
        outinfo["error_msg"] = "encode pass2 error"
        return json.dumps(outinfo)
    mediabase.addlog("step6: ok!", logname)

    #step7: get output dur
    mediabase.addlog("step7: get dur", logname)
    ret = transcode.mediaCodec_getdur( param["basemp4"], logname )
    if ret != "NULL":
        param["base_dur"] = ret
    else:
        error_code = mediabase.ERROR_OUTPUT_DURATION
        outinfo["error_code"] = error_code
        outinfo["error_msg"] = "get output duration error"
        return json.dumps(outinfo)
    mediabase.addlog("step7: ok!", logname)

    #step8: mobile, mov fast start mp4
    mobiledata = []
    mediabase.addlog("step8: mov fast start", logname)
    if param["platform"] & mediabase.MOBILE_PLATFORM:
        ret = transcode.mediaCodec_mp4_movflag( logname )
        if ret != 0:
            error_code = mediabase.ERROR_MOV_FAST_START
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "mov fast start error"
            return json.dumps(outinfo)
        else:
            mobile_member = {}
            mobile_member["name"] = param["output_mp4"]
            mobile_member["dur"] = param["mp4_dur"]
            mobiledata.append( mobile_member )
    outdata["mobile_out"] = mobiledata
    mediabase.addlog("step8: ok!", logname)

    #step9: hls, get m3u8
    hlsdata = {}
    mediabase.addlog("step9: get m3u8", logname)
    if param["platform"] & mediabase.HLS_PLATFORM:
        ret = transcode.mediaCodec_mp42hls( logname )
        if ret != 0:
            error_code = mediabase.ERROR_MP4_TO_M3U8
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "mp4 to m3u8 error"
            return json.dumps(outinfo)
        else:
            hlsdata["hls_m3u8"] = param["output_m3u8"]
            hlsdata["hls_dur"] = param["hls_dur"]
            ts_num = transcode.mediaCodec_hls_num( logname )
            if ts_num == 0:
                error_code = mediabase.ERROR_M3U8_IS_NULL
                outinfo["error_code"] = error_code
                outinfo["error_msg"] = "m3u8 has no ts error"
                return json.dumps(outinfo)
            hlsdata["ts_num"] = str(ts_num)
    outdata["hls_out"] = hlsdata
    mediabase.addlog("step9: ok!", logname)

    #step10: web, cut mp4 and meta f4v
    #step10.1: cut mp4
    f4vdata = []
    mediabase.addlog("step10: cut flow", logname)
    if param["platform"] & mediabase.WEB_PLATFORM:
        #step10.1: cut mp4
        mediabase.addlog("step10.1: cut mp4", logname)
        ret = transcode.mediaCodec_cut( logname )
        if ret != 0:
            error_code = mediabase.ERROR_MP4_MEDIA_CUT
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "mp4 cut to slice error"
            return json.dumps(outinfo)

        #step10.2: flv and f4v
        mediabase.addlog("step10.2: mp4 to flv", logname)
        ret = transcode.mediaCodec_mp42flv( logname )
        if ret != 0:
            error_code = mediabase.ERROR_MP4_TO_FLV
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "slice mp4 to flv error"
            return json.dumps(outinfo)

        mediabase.addlog("step10.3: flv to f4v", logname)
        ret = transcode.mediaCodec_flv2f4v( logname )
        if ret != 0:
            error_code = mediabase.ERROR_MP4_TO_FLV
            outinfo["error_code"] = error_code
            outinfo["error_msg"] = "slice flv to f4v error"
            return json.dumps(outinfo)

        mediabase.addlog("step10.4: dur and output", logname)
        mediabase.addlog("video has %d slice" % param["f4v_num"] , logname)
        for i in range (0, param["f4v_num"] ):
            f4v_member = {}
            index_dur = str(i) + "_dur"
            f4v_member["name"] = param["slice_base"] + str(i) + ".f4v"
            if os.path.exists(f4v_member["name"]):
                mediabase.addlog("get slice f4v dur: %d" % i, logname)
                if param.has_key(index_dur):
                    f4v_member["dur"] = param[index_dur]
                    mediabase.addlog("dur: %s" % param[index_dur], logname)
                else:
                    error_code = mediabase.ERROR_OUTPUT_DURATION
                    outinfo["error_code"] = error_code
                    outinfo["error_msg"] = "get slice f4v dur error!"
                    return json.dumps(outinfo)
            else:
                error_code = mediabase.ERROR_FLV_TO_F4V
                outinfo["error_code"] = error_code
                outinfo["error_msg"] = "flv to f4v error!"
                return json.dumps(outinfo)
            f4vdata.append(f4v_member)
    outdata["f4v_out"] = f4vdata
    mediabase.addlog("step10: ok!", logname)

    outinfo["data"] = outdata

    mediabase.addlog("=================================================================", logname)
    mediabase.addlog("======================= task over ==============================", logname)
    mediabase.addlog("=================================================================", logname)

    return json.dumps(outinfo)
Пример #10
0
def mediaCodec_scan_volume( ffmpeg_input, input_name, param, logname ):
    '''scan volume'''
    mediabase.addlog("python mediaCodec_audiogain.py -i %s" % input_name, logname)

    result_error_code = MEDIACODEC_SCAN_VOLUME_OK

    #step1: check input
    if input_name != None:
        input_file = input_name
    else:
        mediabase.addlog("need input file!\n", logname)
        result_error_code = MEDIACODEC_SCAN_VOLUME_INPUT_ERROR
        return result_error_code

    if not os.path.exists(ffmpeg_input):
        mediabase.addlog("  encoder does not exist", logname)
        result_error_code = MEDIACODEC_SCAN_VOLUME_INPUT_ERROR
        return result_error_code
    elif not os.path.exists(input_file):
        mediabase.addlog("  input file not exist:%s\n" % input_file, logname)
        result_error_code = MEDIACODEC_SCAN_VOLUME_INPUT_FILE_ERROR
        return result_error_code
    else:
        if param.has_key("aid") and param["aid"] != "":  #has audio map
            audio_map = str(param["aid"]).strip()
            scan_cmd = ffmpeg_input +  " -i %s -map 0:a:%s -af volumedetect -f null - " % ( input_file, audio_map )
            mediabase.addlog( "get audio volume info cmd:\n%s " % scan_cmd, logname )
            result = commands.getstatusoutput(scan_cmd)
            if result[0] != 0:
                mediabase.addlog( "call function error: %s\n " % scan_cmd, logname )
                result_error_code = MEDIACODEC_SCAN_VOLUME_INPUT_FILE_ERROR
                return result_error_code

            mean_volume_line = []
            max_volume_line = []
            log_line = result[1].splitlines()

            for line in log_line:
                if "volumedetect" in line and "mean_volume" in line:
                    mean_volume_line = line
                if "volumedetect" in line and "max_volume" in line:
                    max_volume_line = line

            if len(mean_volume_line) == 0:
                mediabase.addlog( "get audio volume error:mean!", logname )
                result_error_code = MEDIACODEC_SCAN_VOLUME_INPUT_FILE_ERROR
                mediabase.addlog( "get audio volume info:\n%s " % result_error_code, logname )
                return result_error_code
            if len(max_volume_line) == 0:
                mediabase.addlog( "get audio volume error:max! " )
                result_error_code = MEDIACODEC_SCAN_VOLUME_INPUT_FILE_ERROR
                mediabase.addlog( "get audio volume info:\n%s " % result_error_code, logname )
                return result_error_code

            if DEBUG:
                print mean_volume_line
                print max_volume_line
                print ""

            mean_list = mean_volume_line.split()
            max_list  = max_volume_line.split()

            if "mean_volume:" in mean_list:
                temp_db = mean_list[mean_list.index("mean_volume:") + 1].strip()
                if "-" in temp_db:
                    result_error_code["mean_db"] = -string.atof(temp_db.strip("-"))
                else:
                    result_error_code["mean_db"] = string.atof(temp_db.strip())

                if result_error_code.has_key("mean_db"):
                    result_error_code["adjust_db"] = str(MEDIACODEC_AUDIO_VOLUME_TH - result_error_code["mean_db"]) + "dB"
            if "max_volume:" in max_list:
                temp_db = max_list[max_list.index("max_volume:") + 1].strip()
                if "-" in temp_db:
                    result_error_code["max_db"] = -string.atof(temp_db.strip("-"))
                else:
                    result_error_code["max_db"] = string.atof(temp_db.strip())

    mediabase.addlog( "get audio volume info:\n%s " % result_error_code, logname )

    return result_error_code