diff --git a/danmaku2ass.py b/danmaku2ass.py index 7a14a9b..67e7348 100755 --- a/danmaku2ass.py +++ b/danmaku2ass.py @@ -137,12 +137,12 @@ def ReadCommentsNiconico(f, fontsize): elif mailstyle == 'shita': pos = 2 elif mailstyle == 'big': - size = fontsize*1.44 + size = fontsize * 1.44 elif mailstyle == 'small': - size = fontsize*0.64 + size = fontsize * 0.64 elif mailstyle in NiconicoColorMap: color = NiconicoColorMap[mailstyle] - yield (max(int(comment.getAttribute('vpos')), 0)*0.01, int(comment.getAttribute('date')), int(comment.getAttribute('no')), c, pos, color, size, (c.count('\n')+1)*size, CalculateLength(c)*size) + yield (max(int(comment.getAttribute('vpos')), 0) * 0.01, int(comment.getAttribute('date')), int(comment.getAttribute('no')), c, pos, color, size, (c.count('\n') + 1) * size, CalculateLength(c) * size) except (AssertionError, AttributeError, IndexError, TypeError, ValueError): logging.warning(_('Invalid comment: %s') % comment.toxml()) continue @@ -159,10 +159,10 @@ def ReadCommentsAcfun(f, fontsize): p = str(comment['c']).split(',') assert len(p) >= 6 assert p[2] in ('1', '2', '4', '5', '7') - size = int(p[3])*fontsize/25.0 + size = int(p[3]) * fontsize / 25.0 if p[2] != '7': c = str(comment['m']).replace('\\r', '\n').replace('\r', '\n') - yield (float(p[0]), int(p[5]), i, c, {'1': 0, '2': 0, '4': 2, '5': 1}[p[2]], int(p[1]), size, (c.count('\n')+1)*size, CalculateLength(c)*size) + yield (float(p[0]), int(p[5]), i, c, {'1': 0, '2': 0, '4': 2, '5': 1}[p[2]], int(p[1]), size, (c.count('\n') + 1) * size, CalculateLength(c) * size) else: c = dict(json.loads(comment['m'])) yield (float(p[0]), int(p[5]), i, c, 'acfunpos', int(p[1]), size, 0, 0) @@ -182,8 +182,8 @@ def ReadCommentsBilibili(f, fontsize): if comment.childNodes.length > 0: if p[1] in ('1', '4', '5', '6'): c = str(comment.childNodes[0].wholeText).replace('/n', '\n') - size = int(p[2])*fontsize/25.0 - yield (float(p[0]), int(p[4]), i, c, {'1': 0, '4': 2, '5': 1, '6': 3}[p[1]], int(p[3]), size, (c.count('\n')+1)*size, CalculateLength(c)*size) + size = int(p[2]) * fontsize / 25.0 + yield (float(p[0]), int(p[4]), i, c, {'1': 0, '4': 2, '5': 1, '6': 3}[p[1]], int(p[3]), size, (c.count('\n') + 1) * size, CalculateLength(c) * size) elif p[1] == '7': # positioned comment c = str(comment.childNodes[0].wholeText) yield (float(p[0]), int(p[4]), i, c, 'bilipos', int(p[3]), int(p[2]), 0, 0) @@ -201,8 +201,8 @@ def ReadCommentsTudou(f, fontsize): assert comment['pos'] in (3, 4, 6) c = str(comment['data']) assert comment['size'] in (0, 1, 2) - size = {0: 0.64, 1: 1, 2: 1.44}[comment['size']]*fontsize - yield (int(comment['replay_time']*0.001), int(comment['commit_time']), i, c, {3: 0, 4: 2, 6: 1}[comment['pos']], int(comment['color']), size, (c.count('\n')+1)*size, CalculateLength(c)*size) + size = {0: 0.64, 1: 1, 2: 1.44}[comment['size']] * fontsize + yield (int(comment['replay_time'] * 0.001), int(comment['commit_time']), i, c, {3: 0, 4: 2, 6: 1}[comment['pos']], int(comment['color']), size, (c.count('\n') + 1) * size, CalculateLength(c) * size) except (AssertionError, AttributeError, IndexError, TypeError, ValueError): logging.warning(_('Invalid comment: %r') % comment) continue @@ -237,8 +237,8 @@ def ReadCommentsMioMio(f, fontsize): message = comment.getElementsByTagName('message')[0] c = str(message.childNodes[0].wholeText) pos = 0 - size = int(message.getAttribute('fontsize'))*fontsize/25.0 - yield (float(comment.getElementsByTagName('playTime')[0].childNodes[0].wholeText), int(calendar.timegm(time.strptime(comment.getElementsByTagName('times')[0].childNodes[0].wholeText, '%Y-%m-%d %H:%M:%S')))-28800, i, c, {'1': 0, '4': 2, '5': 1}[message.getAttribute('mode')], int(message.getAttribute('color')), size, (c.count('\n')+1)*size, CalculateLength(c)*size) + size = int(message.getAttribute('fontsize')) * fontsize / 25.0 + yield (float(comment.getElementsByTagName('playTime')[0].childNodes[0].wholeText), int(calendar.timegm(time.strptime(comment.getElementsByTagName('times')[0].childNodes[0].wholeText, '%Y-%m-%d %H:%M:%S'))) - 28800, i, c, {'1': 0, '4': 2, '5': 1}[message.getAttribute('mode')], int(message.getAttribute('color')), size, (c.count('\n') + 1) * size, CalculateLength(c) * size) except (AssertionError, AttributeError, IndexError, TypeError, ValueError): logging.warning(_('Invalid comment: %s') % comment.toxml()) continue @@ -248,20 +248,20 @@ CommentFormatMap = {'Niconico': ReadCommentsNiconico, 'Acfun': ReadCommentsAcfun def WriteCommentBilibiliPositioned(f, c, width, height, styleid): - #BiliPlayerSize = (512, 384) # Bilibili player version 2010 - #BiliPlayerSize = (540, 384) # Bilibili player version 2012 + # BiliPlayerSize = (512, 384) # Bilibili player version 2010 + # BiliPlayerSize = (540, 384) # Bilibili player version 2012 BiliPlayerSize = (672, 438) # Bilibili player version 2014 ZoomFactor = GetZoomFactor(BiliPlayerSize, (width, height)) def GetPosition(InputPos, isHeight): isHeight = int(isHeight) # True -> 1 if isinstance(InputPos, int): - return ZoomFactor[0]*InputPos+ZoomFactor[isHeight+1] + return ZoomFactor[0] * InputPos + ZoomFactor[isHeight + 1] elif isinstance(InputPos, float): if InputPos > 1: - return ZoomFactor[0]*InputPos+ZoomFactor[isHeight+1] + return ZoomFactor[0] * InputPos + ZoomFactor[isHeight + 1] else: - return BiliPlayerSize[isHeight]*ZoomFactor[0]*InputPos+ZoomFactor[isHeight+1] + return BiliPlayerSize[isHeight] * ZoomFactor[0] * InputPos + ZoomFactor[isHeight + 1] else: try: InputPos = int(InputPos) @@ -283,30 +283,30 @@ def WriteCommentBilibiliPositioned(f, c, width, height, styleid): alpha = safe_list(str(comment_args.get(2, '1')).split('-')) from_alpha = float(alpha.get(0, 1)) to_alpha = float(alpha.get(1, from_alpha)) - from_alpha = 255-round(from_alpha*255) - to_alpha = 255-round(to_alpha*255) + from_alpha = 255 - round(from_alpha * 255) + to_alpha = 255 - round(to_alpha * 255) rotate_z = int(comment_args.get(5, 0)) rotate_y = int(comment_args.get(6, 0)) lifetime = float(comment_args.get(3, 4500)) - duration = int(comment_args.get(9, lifetime*1000)) + duration = int(comment_args.get(9, lifetime * 1000)) delay = int(comment_args.get(10, 0)) fontface = comment_args.get(12) isborder = comment_args.get(11, 'true') from_rotarg = ConvertFlashRotation(rotate_y, rotate_z, from_x, from_y, width, height) to_rotarg = ConvertFlashRotation(rotate_y, rotate_z, to_x, to_y, width, height) - styles = ['\\org(%d, %d)' % (width/2, height/2)] + styles = ['\\org(%d, %d)' % (width / 2, height / 2)] if from_rotarg[0:2] == to_rotarg[0:2]: styles.append('\\pos(%.0f, %.0f)' % (from_rotarg[0:2])) else: - styles.append('\\move(%.0f, %.0f, %.0f, %.0f, %.0f, %.0f)' % (from_rotarg[0:2]+to_rotarg[0:2]+(delay, delay+duration))) + styles.append('\\move(%.0f, %.0f, %.0f, %.0f, %.0f, %.0f)' % (from_rotarg[0:2] + to_rotarg[0:2] + (delay, delay + duration))) styles.append('\\frx%.0f\\fry%.0f\\frz%.0f\\fscx%.0f\\fscy%.0f' % (from_rotarg[2:7])) if (from_x, from_y) != (to_x, to_y): - styles.append('\\t(%d, %d, ' % (delay, delay+duration)) + styles.append('\\t(%d, %d, ' % (delay, delay + duration)) styles.append('\\frx%.0f\\fry%.0f\\frz%.0f\\fscx%.0f\\fscy%.0f' % (to_rotarg[2:7])) styles.append(')') if fontface: styles.append('\\fn%s' % ASSEscape(fontface)) - styles.append('\\fs%.0f' % (c[6]*ZoomFactor[0])) + styles.append('\\fs%.0f' % (c[6] * ZoomFactor[0])) if c[5] != 0xffffff: styles.append('\\c&H%s&' % ConvertColor(c[5])) if c[5] == 0x000000: @@ -314,14 +314,14 @@ def WriteCommentBilibiliPositioned(f, c, width, height, styleid): if from_alpha == to_alpha: styles.append('\\alpha&H%02X' % from_alpha) elif (from_alpha, to_alpha) == (255, 0): - styles.append('\\fad(%.0f,0)' % (lifetime*1000)) + styles.append('\\fad(%.0f,0)' % (lifetime * 1000)) elif (from_alpha, to_alpha) == (0, 255): - styles.append('\\fad(0, %.0f)' % (lifetime*1000)) + styles.append('\\fad(0, %.0f)' % (lifetime * 1000)) else: - styles.append('\\fade(%(from_alpha)d, %(to_alpha)d, %(to_alpha)d, 0, %(end_time).0f, %(end_time).0f, %(end_time).0f)' % {'from_alpha': from_alpha, 'to_alpha': to_alpha, 'end_time': lifetime*1000}) + styles.append('\\fade(%(from_alpha)d, %(to_alpha)d, %(to_alpha)d, 0, %(end_time).0f, %(end_time).0f, %(end_time).0f)' % {'from_alpha': from_alpha, 'to_alpha': to_alpha, 'end_time': lifetime * 1000}) if isborder == 'false': styles.append('\\bord0') - f.write('Dialogue: -1,%(start)s,%(end)s,%(styleid)s,,0,0,0,,{%(styles)s}%(text)s\n' % {'start': ConvertTimestamp(c[0]), 'end': ConvertTimestamp(c[0]+lifetime), 'styles': ''.join(styles), 'text': text, 'styleid': styleid}) + f.write('Dialogue: -1,%(start)s,%(end)s,%(styleid)s,,0,0,0,,{%(styles)s}%(text)s\n' % {'start': ConvertTimestamp(c[0]), 'end': ConvertTimestamp(c[0] + lifetime), 'styles': ''.join(styles), 'text': text, 'styleid': styleid}) except (IndexError, ValueError) as e: try: logging.warning(_('Invalid comment: %r') % c[3]) @@ -335,7 +335,7 @@ def WriteCommentAcfunPositioned(f, c, width, height, styleid): def GetPosition(InputPos, isHeight): isHeight = int(isHeight) # True -> 1 - return AcfunPlayerSize[isHeight]*ZoomFactor[0]*InputPos*0.001+ZoomFactor[isHeight+1] + return AcfunPlayerSize[isHeight] * ZoomFactor[0] * InputPos * 0.001 + ZoomFactor[isHeight + 1] def GetTransformStyles(x=None, y=None, scale_x=None, scale_y=None, rotate_z=None, rotate_y=None, color=None, alpha=None): styles = [] @@ -349,18 +349,18 @@ def WriteCommentAcfunPositioned(f, c, width, height, styleid): scale_x = 1 if scale_y is None: scale_y = 1 - styles.append('\\frx%.0f\\fry%.0f\\frz%.0f\\fscx%.0f\\fscy%.0f' % (rotarg[2:5]+(rotarg[5]*scale_x, rotarg[6]*scale_y))) + styles.append('\\frx%.0f\\fry%.0f\\frz%.0f\\fscx%.0f\\fscy%.0f' % (rotarg[2:5] + (rotarg[5] * scale_x, rotarg[6] * scale_y))) else: if scale_x is not None: - styles.append('\\fscx%.0f' % (scale_x*100)) + styles.append('\\fscx%.0f' % (scale_x * 100)) if scale_y is not None: - styles.append('\\fscy%.0f' % (scale_y*100)) + styles.append('\\fscy%.0f' % (scale_y * 100)) if color is not None: styles.append('\\c&H%s&' % ConvertColor(color)) if color == 0x000000: styles.append('\\3c&HFFFFFF&') if alpha is not None: - alpha = 255-round(alpha*255) + alpha = 255 - round(alpha * 255) styles.append('\\alpha&H%02X' % alpha) return out_x, out_y, styles @@ -371,7 +371,7 @@ def WriteCommentAcfunPositioned(f, c, width, height, styleid): try: comment_args = c[3] text = ASSEscape(str(comment_args['n']).replace('\r', '\n')) - common_styles = ['\org(%d, %d)' % (width/2, height/2)] + common_styles = ['\org(%d, %d)' % (width / 2, height / 2)] anchor = {0: 7, 1: 8, 2: 9, 3: 4, 4: 5, 5: 6, 6: 1, 7: 2, 8: 3}.get(comment_args.get('c', 0), 7) if anchor != 7: common_styles.append('\\an%s' % anchor) @@ -384,7 +384,7 @@ def WriteCommentAcfunPositioned(f, c, width, height, styleid): fontbold = bool(font.get('b')) if fontbold: common_styles.append('\\b1') - common_styles.append('\\fs%.0f' % (c[6]*ZoomFactor[0])) + common_styles.append('\\fs%.0f' % (c[6] * ZoomFactor[0])) isborder = bool(comment_args.get('b', True)) if not isborder: common_styles.append('\\bord0') @@ -401,7 +401,7 @@ def WriteCommentAcfunPositioned(f, c, width, height, styleid): action_time = float(comment_args.get('l', 3.0)) actions = list(comment_args.get('z', [])) to_out_x, to_out_y, transform_styles = GetTransformStyles(to_x, to_y, to_scale_x, to_scale_y, to_rotate_z, to_rotate_y, to_color, to_alpha) - FlushCommentLine(f, text, common_styles+['\\pos(%.0f, %.0f)' % (to_out_x, to_out_y)]+transform_styles, c[0]+from_time, c[0]+from_time+action_time, styleid) + FlushCommentLine(f, text, common_styles + ['\\pos(%.0f, %.0f)' % (to_out_x, to_out_y)] + transform_styles, c[0] + from_time, c[0] + from_time + action_time, styleid) action_styles = transform_styles for action in actions: action = dict(action) @@ -434,11 +434,11 @@ def WriteCommentAcfunPositioned(f, c, width, height, styleid): pos_style = '\\pos(%.0f, %.0f)' % (to_out_x, to_out_y) else: pos_style = '\\move(%.0f, %.0f, %.0f, %.0f)' % (from_out_x, from_out_y, to_out_x, to_out_y) - styles = common_styles+transform_styles + styles = common_styles + transform_styles styles.append(pos_style) if action_styles: styles.append('\\t(%s)' % (''.join(action_styles))) - FlushCommentLine(f, text, styles, c[0]+from_time, c[0]+from_time+action_time, styleid) + FlushCommentLine(f, text, styles, c[0] + from_time, c[0] + from_time + action_time, styleid) except (IndexError, ValueError) as e: logging.warning(_('Invalid comment: %r') % c[3]) @@ -453,16 +453,16 @@ def GetZoomFactor(SourceSize, TargetSize): pass GetZoomFactor.Cached_Size = (SourceSize, TargetSize) try: - SourceAspect = SourceSize[0]/SourceSize[1] - TargetAspect = TargetSize[0]/TargetSize[1] + SourceAspect = SourceSize[0] / SourceSize[1] + TargetAspect = TargetSize[0] / TargetSize[1] if TargetAspect < SourceAspect: # narrower - ScaleFactor = TargetSize[0]/SourceSize[0] - GetZoomFactor.Cached_Result = (ScaleFactor, 0, (TargetSize[1]-TargetSize[0]/SourceAspect)/2) + ScaleFactor = TargetSize[0] / SourceSize[0] + GetZoomFactor.Cached_Result = (ScaleFactor, 0, (TargetSize[1] - TargetSize[0] / SourceAspect) / 2) elif TargetAspect > SourceAspect: # wider - ScaleFactor = TargetSize[1]/SourceSize[1] - GetZoomFactor.Cached_Result = (ScaleFactor, (TargetSize[0]-TargetSize[1]*SourceAspect)/2, 0) + ScaleFactor = TargetSize[1] / SourceSize[1] + GetZoomFactor.Cached_Result = (ScaleFactor, (TargetSize[0] - TargetSize[1] * SourceAspect) / 2, 0) else: - GetZoomFactor.Cached_Result = (TargetSize[0]/SourceSize[0], 0, 0) + GetZoomFactor.Cached_Result = (TargetSize[0] / SourceSize[0], 0, 0) return GetZoomFactor.Cached_Result except ZeroDivisionError: GetZoomFactor.Cached_Result = (1, 0, 0) @@ -476,7 +476,7 @@ def GetZoomFactor(SourceSize, TargetSize): # Result: (transX, transY, rotX, rotY, rotZ, scaleX, scaleY) def ConvertFlashRotation(rotY, rotZ, X, Y, width, height): def WrapAngle(deg): - return 180-((180-deg) % 360) + return 180 - ((180 - deg) % 360) rotY = WrapAngle(rotY) rotZ = WrapAngle(rotZ) if rotY in (90, -90): @@ -485,37 +485,37 @@ def ConvertFlashRotation(rotY, rotZ, X, Y, width, height): outX = 0 outY = -rotY # Positive value means clockwise in Flash outZ = -rotZ - rotY *= math.pi/180.0 - rotZ *= math.pi/180.0 + rotY *= math.pi / 180.0 + rotZ *= math.pi / 180.0 else: - rotY *= math.pi/180.0 - rotZ *= math.pi/180.0 - outY = math.atan2(-math.sin(rotY)*math.cos(rotZ), math.cos(rotY))*180/math.pi - outZ = math.atan2(-math.cos(rotY)*math.sin(rotZ), math.cos(rotZ))*180/math.pi - outX = math.asin(math.sin(rotY)*math.sin(rotZ))*180/math.pi - trX = (X*math.cos(rotZ)+Y*math.sin(rotZ))/math.cos(rotY)+(1-math.cos(rotZ)/math.cos(rotY))*width/2-math.sin(rotZ)/math.cos(rotY)*height/2 - trY = Y*math.cos(rotZ)-X*math.sin(rotZ)+math.sin(rotZ)*width/2+(1-math.cos(rotZ))*height/2 - trZ = (trX-width/2)*math.sin(rotY) - FOV = width*math.tan(2*math.pi/9.0)/2 + rotY *= math.pi / 180.0 + rotZ *= math.pi / 180.0 + outY = math.atan2(-math.sin(rotY) * math.cos(rotZ), math.cos(rotY)) * 180 / math.pi + outZ = math.atan2(-math.cos(rotY) * math.sin(rotZ), math.cos(rotZ)) * 180 / math.pi + outX = math.asin(math.sin(rotY) * math.sin(rotZ)) * 180 / math.pi + trX = (X * math.cos(rotZ) + Y * math.sin(rotZ)) / math.cos(rotY) + (1 - math.cos(rotZ) / math.cos(rotY)) * width / 2 - math.sin(rotZ) / math.cos(rotY) * height / 2 + trY = Y * math.cos(rotZ) - X * math.sin(rotZ) + math.sin(rotZ) * width / 2 + (1 - math.cos(rotZ)) * height / 2 + trZ = (trX - width / 2) * math.sin(rotY) + FOV = width * math.tan(2 * math.pi / 9.0) / 2 try: - scaleXY = FOV/(FOV+trZ) + scaleXY = FOV / (FOV + trZ) except ZeroDivisionError: logging.error('Rotation makes object behind the camera: trZ == %.0f' % trZ) scaleXY = 1 - trX = (trX-width/2)*scaleXY+width/2 - trY = (trY-height/2)*scaleXY+height/2 + trX = (trX - width / 2) * scaleXY + width / 2 + trY = (trY - height / 2) * scaleXY + height / 2 if scaleXY < 0: scaleXY = -scaleXY outX += 180 outY += 180 logging.error('Rotation makes object behind the camera: trZ == %.0f < %.0f' % (trZ, FOV)) - return (trX, trY, WrapAngle(outX), WrapAngle(outY), WrapAngle(outZ), scaleXY*100, scaleXY*100) + return (trX, trY, WrapAngle(outX), WrapAngle(outY), WrapAngle(outZ), scaleXY * 100, scaleXY * 100) def ProcessComments(comments, f, width, height, bottomReserved, fontface, fontsize, alpha, duration_marquee, duration_still, filter_regex, reduced, progress_callback): styleid = 'Danmaku2ASS_%04x' % random.randint(0, 0xffff) WriteASSHead(f, width, height, fontface, fontsize, alpha, styleid) - rows = [[None]*(height-bottomReserved+1) for i in range(4)] + rows = [[None] * (height - bottomReserved + 1) for i in range(4)] for idx, i in enumerate(comments): if progress_callback and idx % 1000 == 0: progress_callback(idx, len(comments)) @@ -523,7 +523,7 @@ def ProcessComments(comments, f, width, height, bottomReserved, fontface, fontsi if filter_regex and filter_regex.search(i[3]): continue row = 0 - rowmax = height-bottomReserved-i[7] + rowmax = height - bottomReserved - i[7] while row <= rowmax: freerows = TestFreeRows(rows, i, row, width, height, bottomReserved, duration_marquee, duration_still) if freerows >= i[7]: @@ -549,26 +549,26 @@ def ProcessComments(comments, f, width, height, bottomReserved, fontface, fontsi def TestFreeRows(rows, c, row, width, height, bottomReserved, duration_marquee, duration_still): res = 0 - rowmax = height-bottomReserved + rowmax = height - bottomReserved targetRow = None if c[4] in (1, 2): while row < rowmax and res < c[7]: if targetRow != rows[c[4]][row]: targetRow = rows[c[4]][row] - if targetRow and targetRow[0]+duration_still > c[0]: + if targetRow and targetRow[0] + duration_still > c[0]: break row += 1 res += 1 else: try: - thresholdTime = c[0]-duration_marquee*(1-width/(c[8]+width)) + thresholdTime = c[0] - duration_marquee * (1 - width / (c[8] + width)) except ZeroDivisionError: - thresholdTime = c[0]-duration_marquee + thresholdTime = c[0] - duration_marquee while row < rowmax and res < c[7]: if targetRow != rows[c[4]][row]: targetRow = rows[c[4]][row] try: - if targetRow and (targetRow[0] > thresholdTime or targetRow[0]+targetRow[8]*duration_marquee/(targetRow[8]+width) > c[0]): + if targetRow and (targetRow[0] > thresholdTime or targetRow[0] + targetRow[8] * duration_marquee / (targetRow[8] + width) > c[0]): break except ZeroDivisionError: pass @@ -579,7 +579,7 @@ def TestFreeRows(rows, c, row, width, height, bottomReserved, duration_marquee, def FindAlternativeRow(rows, c, height, bottomReserved): res = 0 - for row in range(height-bottomReserved-math.ceil(c[7])): + for row in range(height - bottomReserved - math.ceil(c[7])): if not rows[c[4]][row]: return row elif rows[c[4]][row][0] < rows[c[4]][res][0]: @@ -589,7 +589,7 @@ def FindAlternativeRow(rows, c, height, bottomReserved): def MarkCommentRow(rows, c, row): try: - for i in range(row, row+math.ceil(c[7])): + for i in range(row, row + math.ceil(c[7])): rows[c[4]][i] = c except IndexError: pass @@ -597,7 +597,7 @@ def MarkCommentRow(rows, c, row): def WriteASSHead(f, width, height, fontface, fontsize, alpha, styleid): f.write( -'''[Script Info] + '''[Script Info] ; Script generated by Danmaku2ASS ; https://github.com/m13253/danmaku2ass Script Updated By: Danmaku2ASS (https://github.com/m13253/danmaku2ass) @@ -616,7 +616,7 @@ Style: %(styleid)s, %(fontface)s, %(fontsize).0f, &H%(alpha)02XFFFFFF, &H%(alpha [Events] Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text -''' % {'width': width, 'height': height, 'fontface': fontface, 'fontsize': fontsize, 'alpha': 255-round(alpha*255), 'outline': max(fontsize/25.0, 1), 'styleid': styleid} +''' % {'width': width, 'height': height, 'fontface': fontface, 'fontsize': fontsize, 'alpha': 255 - round(alpha * 255), 'outline': max(fontsize / 25.0, 1), 'styleid': styleid} ) @@ -624,10 +624,10 @@ def WriteComment(f, c, row, width, height, bottomReserved, fontsize, duration_ma text = ASSEscape(c[3]) styles = [] if c[4] == 1: - styles.append('\\an8\\pos(%(halfwidth)d, %(row)d)' % {'halfwidth': width/2, 'row': row}) + styles.append('\\an8\\pos(%(halfwidth)d, %(row)d)' % {'halfwidth': width / 2, 'row': row}) duration = duration_still elif c[4] == 2: - styles.append('\\an2\\pos(%(halfwidth)d, %(row)d)' % {'halfwidth': width/2, 'row': ConvertType2(row, height, bottomReserved)}) + styles.append('\\an2\\pos(%(halfwidth)d, %(row)d)' % {'halfwidth': width / 2, 'row': ConvertType2(row, height, bottomReserved)}) duration = duration_still elif c[4] == 3: styles.append('\\move(%(neglen)d, %(row)d, %(width)d, %(row)d)' % {'width': width, 'row': row, 'neglen': -math.ceil(c[8])}) @@ -635,13 +635,13 @@ def WriteComment(f, c, row, width, height, bottomReserved, fontsize, duration_ma else: styles.append('\\move(%(width)d, %(row)d, %(neglen)d, %(row)d)' % {'width': width, 'row': row, 'neglen': -math.ceil(c[8])}) duration = duration_marquee - if not (-1 < c[6]-fontsize < 1): + if not (-1 < c[6] - fontsize < 1): styles.append('\\fs%.0f' % c[6]) if c[5] != 0xffffff: styles.append('\\c&H%s&' % ConvertColor(c[5])) if c[5] == 0x000000: styles.append('\\3c&HFFFFFF&') - f.write('Dialogue: 2,%(start)s,%(end)s,%(styleid)s,,0000,0000,0000,,{%(styles)s}%(text)s\n' % {'start': ConvertTimestamp(c[0]), 'end': ConvertTimestamp(c[0]+duration), 'styles': ''.join(styles), 'text': text, 'styleid': styleid}) + f.write('Dialogue: 2,%(start)s,%(end)s,%(styleid)s,,0000,0000,0000,,{%(styles)s}%(text)s\n' % {'start': ConvertTimestamp(c[0]), 'end': ConvertTimestamp(c[0] + duration), 'styles': ''.join(styles), 'text': text, 'styleid': styleid}) def ASSEscape(s): @@ -651,9 +651,9 @@ def ASSEscape(s): if slen == len(sstrip): return s else: - llen = slen-len(s.lstrip(' ')) - rlen = slen-len(s.rstrip(' ')) - return ''.join(('\u2007'*llen, sstrip, '\u2007'*rlen)) + llen = slen - len(s.lstrip(' ')) + rlen = slen - len(s.rstrip(' ')) + return ''.join(('\u2007' * llen, sstrip, '\u2007' * rlen)) return '\\N'.join((ReplaceLeadingSpace(i) or ' ' for i in str(s).replace('\\', '\\\\').replace('{', '\\{').replace('}', '\\}').split('\n'))) @@ -662,7 +662,7 @@ def CalculateLength(s): def ConvertTimestamp(timestamp): - timestamp = round(timestamp*100.0) + timestamp = round(timestamp * 100.0) hour, minute = divmod(timestamp, 360000) minute, second = divmod(minute, 6000) second, centsecond = divmod(second, 100) @@ -682,14 +682,14 @@ def ConvertColor(RGB, width=1280, height=576): else: # VobSub always uses BT.601 colorspace, convert to BT.709 ClipByte = lambda x: 255 if x > 255 else 0 if x < 0 else round(x) return '%02X%02X%02X' % ( - ClipByte(R*0.00956384088080656+G*0.03217254540203729+B*0.95826361371715607), - ClipByte(R*-0.10493933142075390+G*1.17231478191855154+B*-0.06737545049779757), - ClipByte(R*0.91348912373987645+G*0.07858536372532510+B*0.00792551253479842) + ClipByte(R * 0.00956384088080656 + G * 0.03217254540203729 + B * 0.95826361371715607), + ClipByte(R * -0.10493933142075390 + G * 1.17231478191855154 + B * -0.06737545049779757), + ClipByte(R * 0.91348912373987645 + G * 0.07858536372532510 + B * 0.00792551253479842) ) def ConvertType2(row, height, bottomReserved): - return height-bottomReserved-row + return height - bottomReserved - row def ConvertToFile(filename_or_file, *args, **kwargs): @@ -708,6 +708,7 @@ def FilterBadChars(f): class safe_list(list): + def get(self, index, default=None): try: return self[index] diff --git a/test/test-3drot.py b/test/test-3drot.py index 544defe..cda1e7c 100755 --- a/test/test-3drot.py +++ b/test/test-3drot.py @@ -13,6 +13,7 @@ except (AttributeError, ImportError): extcode = 0 + def main(): logging.basicConfig(level=logging.INFO) for Y in (120, 360): @@ -23,50 +24,54 @@ def main(): logging.info('(%3d, %3d), %4d, %4d => %4d, %4d, %4d, %4d%%' % (X, Y, rotY, rotZ, outX, outY, outZ, scaleX)) CompareMatrix(rotY, rotZ, outX, outY, outZ) + def CompareMatrix(rotY, rotZ, outX, outY, outZ): def ApproxEqual(a, b, e=0.015): assert e >= 0 - a_b = a-b + a_b = a - b if -e < a_b < e: return 0 else: return a_b + def FormatError(i, j, l, r): global extcode if ApproxEqual(l, r) != 0: extcode = 1 logging.error('l[%s][%s]=%9.6f r[%s][%s]=%9.6f' % (i, j, l, i, j, r)) - def sind(x): - return math.sin(x*math.pi/180.0) - def cosd(x): - return math.cos(x*math.pi/180.0) - l = cosd(rotY)*cosd(rotZ) - r = -sind(outX)*sind(outY)*sind(outZ)+cosd(outY)*cosd(outZ) + def sind(x): + return math.sin(x * math.pi / 180.0) + + def cosd(x): + return math.cos(x * math.pi / 180.0) + + l = cosd(rotY) * cosd(rotZ) + r = -sind(outX) * sind(outY) * sind(outZ) + cosd(outY) * cosd(outZ) FormatError(0, 0, l, r) - l = cosd(rotY)*sind(rotZ) - r = -cosd(outX)*sind(outZ) + l = cosd(rotY) * sind(rotZ) + r = -cosd(outX) * sind(outZ) FormatError(0, 1, l, r) l = sind(rotY) - r = -sind(outX)*cosd(outY)*sind(outZ)-sind(outY)*cosd(outZ) + r = -sind(outX) * cosd(outY) * sind(outZ) - sind(outY) * cosd(outZ) FormatError(0, 2, l, r) l = -sind(rotZ) - r = sind(outX)*sind(outY)*cosd(outZ)+cosd(outY)*sind(outZ) + r = sind(outX) * sind(outY) * cosd(outZ) + cosd(outY) * sind(outZ) FormatError(1, 0, l, r) l = cosd(rotZ) - r = cosd(outX)*cosd(outZ) + r = cosd(outX) * cosd(outZ) FormatError(1, 1, l, r) l = 0 - r = sind(outX)*cosd(outY)*cosd(outZ)-sind(outY)*sind(outZ) + r = sind(outX) * cosd(outY) * cosd(outZ) - sind(outY) * sind(outZ) FormatError(1, 2, l, r) - l = -sind(rotY)*cosd(rotZ) - r = cosd(outX)*sind(outY) + l = -sind(rotY) * cosd(rotZ) + r = cosd(outX) * sind(outY) FormatError(2, 0, l, r) - l = -sind(rotY)*sind(rotZ) + l = -sind(rotY) * sind(rotZ) r = -sind(outX) FormatError(2, 1, l, r) l = cosd(rotY) - r = cosd(outX)*cosd(outY) + r = cosd(outX) * cosd(outY) FormatError(2, 2, l, r) if __name__ == '__main__':