/usr/share/transmageddon/transmageddon.py is in transmageddon 0.25-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 | #! /usr/bin/env python3
# -.- coding: utf-8 -.-
# Transmageddon
# Copyright (C) 2009,2010,2011,2012 Christian Schaller <uraeus@gnome.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
import sys
import os
os.environ["GST_DEBUG_DUMP_DOT_DIR"] = "/tmp"
import which
import time
from gi.repository import Notify
from gi.repository import GdkX11, Gio, Gtk, GLib, Gst, GstPbutils
Gst.init(None)
from gi.repository import GObject
GObject.threads_init()
import transcoder_engine
from urllib.parse import urlparse
import codecfinder
import about
import presets
import utils
import datetime
#major, minor, patch = Gst.pygst_version
#if (major == 0) and (patch < 22):
# print("You need version 0.10.22 or higher of Gstreamer-python for Transmageddon")
# sys.exit(1)
major, minor, patch = GObject.pygobject_version
if (major == 2) and (minor < 18):
print("You need version 2.18.0 or higher of pygobject for Transmageddon")
sys.exit(1)
TARGET_TYPE_URI_LIST = 80
dnd_list = [ ( 'text/uri-list', 0, TARGET_TYPE_URI_LIST ) ]
supported_containers = [
"Ogg", #0
"Matroska", #1
"AVI", #2
"MPEG PS", #3
"MPEG TS", #4
"AVCHD/BD", #5
"FLV", #6
"Quicktime", #7
"MPEG4", #8
"3GPP", #9
"MXF", #10
"ASF", #11
"I can not get this item to show for some reason",
"WebM" #12
]
supported_audio_codecs = [
"vorbis",
"flac",
"mp3",
"aac",
"ac3",
"speex",
"celt",
"amrnb",
"wma2"
]
supported_video_codecs = [
"theora",
"dirac",
"h264",
"mpeg2",
"mpeg4",
"h263p",
"wmv2",
"vp8"
]
# Maps containers to the codecs they support. The first two elements are
# "special" in that they are the default audio/video selections for that
# container.
supported_video_container_map = {
'Ogg': [ 'Theora', 'Dirac', 'On2 vp8' ],
'MXF': [ 'H264', 'MPEG2', 'MPEG4' ],
'Matroska': [ 'Dirac', 'Theora', 'H264', 'On2 vp8',
'MPEG4', 'MPEG2', 'H263+' ],
'AVI': [ 'H264', 'Dirac', 'MPEG2', 'MPEG4',
'Windows Media Video 2', 'On2 vp8' ],
'Quicktime': [ 'H264', 'Dirac', 'MPEG2', 'MPEG4', 'On2 vp8' ],
'MPEG4': [ 'H264', 'MPEG2', 'MPEG4' ],
'FLV': [ 'H264'],
'3GPP': [ 'H264', 'MPEG2', 'MPEG4', 'H263+' ],
'MPEG PS': [ 'MPEG2', 'MPEG1', 'H264', 'MPEG4' ],
'MPEG TS': [ 'MPEG2', 'MPEG1', 'H264', 'MPEG4', 'Dirac' ],
'AVCHD/BD': [ 'H264' ],
'ASF': [ 'Windows Media Video 2' ],
'WebM': [ 'On2 vp8']
}
supported_audio_container_map = {
'Ogg': [ 'Vorbis', 'FLAC', 'Speex', 'Celt Ultra' ],
'MXF': [ 'mp3', 'AAC', 'AC3' ],
'Matroska': [ 'FLAC', 'AAC', 'AC3', 'Vorbis' ],
'AVI': [ 'mp3', 'AC3', 'Windows Media Audio 2' ],
'Quicktime': [ 'AAC', 'AC3', 'mp3' ],
'MPEG4': [ 'AAC', 'mp3' ],
'3GPP': [ 'AAC', 'mp3', 'AMR-NB' ],
'MPEG PS': [ 'mp3', 'AC3', 'AAC', 'mp2' ],
'MPEG TS': [ 'mp3', 'AC3', 'AAC', 'mp2' ],
'AVCHD/BD': [ 'AC3' ],
'FLV': [ 'mp3' ],
'ASF': [ 'Windows Media Audio 2', 'mp3'],
'WebM': [ 'Vorbis']
# "No container" is 13th option here (0-12)
# if adding more containers make sure to update code for 'No container as it is placement tied'
}
class Transmageddon(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
self.win = TransmageddonUI(self)
self.win.show_all()
def do_startup (self):
# start the application
Gtk.Application.do_startup(self)
# create a menu
menu = Gio.Menu()
# append to the menu the options
menu.append(_("About"), "app.about")
menu.append(_("Quit"), "app.quit")
menu.append(_("Debug"), "app.debug")
# set the menu as menu of the application
self.set_app_menu(menu)
# create an action for the option "new" of the menu
debug_action = Gio.SimpleAction.new("debug", None)
debug_action.connect("activate", self.debug_cb)
self.add_action(debug_action)
# option "about"
about_action = Gio.SimpleAction.new("about", None)
about_action.connect("activate", self.about_cb)
self.add_action(about_action)
# option "quit"
quit_action = Gio.SimpleAction.new("quit", None)
quit_action.connect("activate", self.quit_cb)
self.add_action(quit_action)
# callback function for "new"
def debug_cb(self, action, parameter):
dotfile = "/tmp/transmageddon-debug-graph.dot"
pngfile = "/tmp/transmageddon-pipeline.png"
if os.access(dotfile, os.F_OK):
os.remove(dotfile)
if os.access(pngfile, os.F_OK):
os.remove(pngfile)
Gst.debug_bin_to_dot_file (self.win._transcoder.pipeline, \
Gst.DebugGraphDetails.ALL, 'transmageddon-debug-graph')
# check if graphviz is installed with a simple test
try:
dot = which.which("dot")
os.system(dot + " -Tpng -o " + pngfile + " " + dotfile)
Gtk.show_uri(self.win.get_screen(), "file://"+pngfile, 0)
except which.WhichError:
print("The debug feature requires graphviz (dot) to be installed.")
print("Transmageddon can not find the (dot) binary.")
# callback function for "about"
def about_cb(self, action, parameter):
"""
Show the about dialog.
"""
about.AboutDialog()
# callback function for "quit"
def quit_cb(self, action, parameter):
print("You have quit.")
self.quit()
class TransmageddonUI(Gtk.ApplicationWindow):
def on_window_destroy(self, widget, data=None):
Gtk.main_quit()
def __init__(self, app):
Gtk.Window.__init__(self, title="Transmageddon", application=app)
"""This class loads the GtkBuilder file of the UI"""
# create discoverer object
self.discovered = GstPbutils.Discoverer.new(50000000000)
self.discovered.connect('discovered', self.succeed)
self.discovered.start()
self.audiorows=[] # set up the lists for holding the codec combobuttons
self.videorows=[]
self.audiocodecs=[] # create lists to store the ordered lists of codecs
self.videocodecs=[]
# set flag so we remove bogus value from menu only once
self.bogus=0
# init the notification area
Notify.init('Transmageddon')
# These dynamic comboboxes allow us to support files with
# multiple streams eventually
def dynamic_comboboxes_audio(streams,extra = []):
streams=1 # this will become a variable once we support multiple streams
vbox = Gtk.VBox()
x=-1
while x < (streams-1):
x=x+1
combo = Gtk.ComboBoxText.new()
self.audiorows.append(combo)
vbox.add(self.audiorows[x])
return vbox
def dynamic_comboboxes_video(streams,extra = []):
streams=1
vbox = Gtk.VBox()
x=-1
while x < (streams-1):
x=x+1
combo = Gtk.ComboBoxText.new()
self.videorows.append(combo)
vbox.add(self.videorows[x])
return vbox
self.builder = Gtk.Builder()
self.builder.set_translation_domain("transmageddon")
uifile = "transmageddon.ui"
self.builder.add_from_file(uifile)
#Define functionality of our button and main window
self.box = self.builder.get_object("window")
self.FileChooser = self.builder.get_object("FileChooser")
self.videoinformation = self.builder.get_object("videoinformation")
self.audioinformation = self.builder.get_object("audioinformation")
self.videocodec = self.builder.get_object("videocodec")
self.audiocodec = self.builder.get_object("audiocodec")
self.audiobox = dynamic_comboboxes_audio([GObject.TYPE_PYOBJECT])
self.videobox = dynamic_comboboxes_video([GObject.TYPE_PYOBJECT])
self.CodecBox = self.builder.get_object("CodecBox")
self.presetchoice = self.builder.get_object("presetchoice")
self.containerchoice = self.builder.get_object("containerchoice")
self.rotationchoice = self.builder.get_object("rotationchoice")
self.transcodebutton = self.builder.get_object("transcodebutton")
self.ProgressBar = self.builder.get_object("ProgressBar")
self.cancelbutton = self.builder.get_object("cancelbutton")
self.StatusBar = self.builder.get_object("StatusBar")
self.CodecBox.attach(self.audiobox, 0, 1, 1, 2, yoptions = Gtk.AttachOptions.FILL)
self.CodecBox.attach(self.videobox, 2, 3, 1, 2, yoptions = Gtk.AttachOptions.FILL)
self.CodecBox.show_all()
self.containerchoice.connect("changed", self.on_containerchoice_changed)
self.presetchoice.connect("changed", self.on_presetchoice_changed)
self.audiorows[0].connect("changed", self.on_audiocodec_changed)
self.videorows[0].connect("changed", self.on_videocodec_changed)
self.rotationchoice.connect("changed", self.on_rotationchoice_changed)
self.window=self.builder.get_object("window")
self.builder.connect_signals(self) # Initialize User Interface
self.add(self.box)
def get_file_path_from_dnd_dropped_uri(self, uri):
# get the path to file
path = ""
if uri.startswith('file:\\\\\\'): # windows
path = uri[8:] # 8 is len('file:///')
elif uri.startswith('file://'): # nautilus, rox
path = uri[7:] # 7 is len('file://')
elif uri.startswith('file:'): # xffm
path = uri[5:] # 5 is len('file:')
return path
# This could should be fixed and re-enabled to allow drag and drop
def on_drag_data_received(widget, context, x, y, selection, target_type, \
timestamp):
if target_type == TARGET_TYPE_URI_LIST:
uri = selection.data.strip('\r\n\x00')
self.builder.get_object ("FileChooser").set_uri(uri)
# self.connect('drag_data_received', on_drag_data_received)
#Gtk.drag_dest_set(self, Gtk.DEST_DEFAULT_MOTION |
# Gtk.DEST_DEFAULT_HIGHLIGHT | Gtk.DEST_DEFAULT_DROP, dnd_list, \
# Gdk.DragAction.COPY)
self.start_time = False
self.multipass = 0
self.passcounter = 0
# Set the Videos XDG UserDir as the default directory for the filechooser
# also make sure directory exists
#if 'get_user_special_dir' in GLib.__dict__:
self.videodirectory = \
GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_VIDEOS)
self.audiodirectory = \
GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_MUSIC)
#else:
# print("XDG video or audio directory not available")
# self.videodirectory = os.getenv('HOME')
# self.audiodirectory = os.getenv('HOME')
if self.videodirectory is None:
self.videodirectory = os.getenv('HOME')
self.audiodirectory = os.getenv('HOME')
CheckDir = os.path.isdir(self.videodirectory)
if CheckDir == (False):
os.mkdir(self.videodirectory)
CheckDir = os.path.isdir(self.audiodirectory)
if CheckDir == (False):
os.mkdir(self.audiodirectory)
self.FileChooser.set_current_folder(self.videodirectory)
# Setting AppIcon
FileExist = os.path.isfile("../../share/pixmaps/transmageddon.svg")
if FileExist:
self.set_icon_from_file( \
"../../share/pixmaps/transmageddon.svg")
else:
try:
self.set_icon_from_file("transmageddon.svg")
except:
print("failed to find appicon")
# default all but top box to insensitive by default
# self.containerchoice.set_sensitive(False)
self.CodecBox.set_sensitive(False)
self.transcodebutton.set_sensitive(False)
self.cancelbutton.set_sensitive(False)
self.presetchoice.set_sensitive(False)
self.containerchoice.set_sensitive(False)
self.rotationchoice.set_sensitive(False)
# set default values for various variables
self.AudioCodec = Gst.caps_from_string("audio/x-vorbis")
self.VideoCodec = Gst.caps_from_string("video/x-theora")
self.ProgressBar.set_text(_("Transcoding Progress"))
self.codeccontainer = False
self.vsourcecaps = False
self.asourcecaps = False
self.videopasstoggle=False # toggle for passthrough mode chosen
self.audiopasstoggle=False
self.videopass=False # toggle for enabling adding of video passthrough on menu
self.audiopass=False
self.containertoggle=False # used to not check for encoders with pbutils
self.discover_done=False # lets us know that discover is finished
self.missingtoggle=False
self.interlaced=False
self.havevideo=False # tracks if input file got video
self.haveaudio=False
self.devicename = "nopreset"
self.nocontaineroptiontoggle=False
self.outputdirectory=False # directory for holding output directory value
# create variables to store passthrough options slot in the menu
self.audiopassmenuno=1
self.videopassmenuno=1
self.videonovideomenuno=-2
# create toggle so I can split codepath depending on if I using a preset
# or not
self.usingpreset=False
self.presetaudiocodec=Gst.Caps.new_empty()
self.presetvideocodec=Gst.Caps.new_empty()
self.inputvideocaps=None # using this value to store videocodec name to feed uridecodebin to avoid decoding video when not keeping video
self.nocontainernumber = int(13) # this needs to be set to the number of the no container option in the menu (from 0)
self.p_duration = Gst.CLOCK_TIME_NONE
self.p_time = Gst.Format.TIME
# Populate the Container format combobox
# print("do we try to populate container choice")
for i in supported_containers:
self.containerchoice.append_text(i)
# add i18n "No container"option
self.containerchoice.append_text(_("No container (Audio-only)"))
# Populate the rotatation box
# print("populating rotationbox")
self.rotationlist = [_("No rotation (default)"),\
_("Clockwise 90 degrees"), \
_("Rotate 180 degrees"),
_("Counterclockwise 90 degrees"), \
_("Horizontal flip"),
_("Vertical flip"), \
_("Upper left diagonal flip"),
_("Upper right diagnonal flip") ]
for y in self.rotationlist:
self.rotationchoice.append_text(y)
self.rotationchoice.set_active(0)
self.rotationvalue = int(0)
# Populate Device Presets combobox
# print("starting preset population")
devicelist = []
shortname = []
preset_list = sorted(list(presets.get().items()),
key = (lambda x: x[1].make + x[1].model))
for x, (name, device) in enumerate(preset_list):
self.presetchoice.append_text(str(device))
devicelist.append(str(device))
shortname.append(str(name))
for (name, device) in (list(presets.get().items())):
shortname.append(str(name))
# self.presetchoices = dict(zip(devicelist, shortname))
self.presetchoices = shortname
self.presetchoice.prepend_text(_("No Presets"))
self.waiting_for_signal="False"
# Get all preset values
def reverse_lookup(self,v):
for k in codecfinder.codecmap:
if codecfinder.codecmap[k] == v:
return k
def provide_presets(self,devicename):
devices = presets.get()
device = devices[devicename]
preset = device.presets["Normal"]
self.usingpreset=True
self.containerchoice.set_active(-1) # resetting to -1 to ensure population of menu triggers
self.presetaudiocodec=Gst.caps_from_string(preset.acodec.name)
self.AudioCodec=Gst.caps_from_string(preset.acodec.name)
self.presetvideocodec=Gst.caps_from_string(preset.vcodec.name)
self.VideoCodec=Gst.caps_from_string(preset.vcodec.name)
if preset.container == "application/ogg":
self.containerchoice.set_active(0)
elif preset.container == "video/x-matroska":
self.containerchoice.set_active(1)
elif preset.container == "video/x-msvideo":
self.containerchoice.set_active(2)
elif preset.container == "video/mpeg,mpegversion=2,systemstream=true":
self.containerchoice.set_active(3)
elif preset.container == "video/mpegts,systemstream=true,packetsize=188":
self.containerchoice.set_active(4)
elif preset.container == "video/mpegts,systemstream=true,packetsize=192":
self.containerchoice.set_active(5)
elif preset.container == "video/x-flv":
self.containerchoice.set_active(6)
elif preset.container == "video/quicktime,variant=apple":
self.containerchoice.set_active(7)
elif preset.container == "video/quicktime,variant=iso":
self.containerchoice.set_active(8)
elif preset.container == "video/quicktime,variant=3gpp":
self.containerchoice.set_active(9)
elif preset.container == "application/mxf":
self.containerchoice.set_active(10)
elif preset.container == "video/x-ms-asf":
self.containerchoice.set_active(11)
elif preset.container == "video/webm":
self.containerchoice.set_active(12)
else:
print("failed to set container format from preset data")
# Check for number of passes
passes = preset.vcodec.passes
if passes == "0":
self.multipass = 0
else:
self.multipass = int(passes)
self.passcounter = int(0)
# Create query on uridecoder to get values to populate progressbar
# Notes:
# Query interface only available on uridecoder, not decodebin2)
# FORMAT_TIME only value implemented by all plugins used
# a lot of original code from Gst-python synchronizer.py example
def Increment_Progressbar(self):
# print("incrementing progressbar")
if self.start_time == False:
self.start_time = time.time()
try:
success, position = \
self._transcoder.uridecoder.query_position(Gst.Format.TIME)
except:
position = Gst.CLOCK_TIME_NONE
try:
success, duration = \
self._transcoder.uridecoder.query_duration(Gst.Format.TIME)
except:
duration = Gst.CLOCK_TIME_NONE
if position != Gst.CLOCK_TIME_NONE:
if duration != 0:
value = float(position) / duration
if float(value) < (1.0) and float(value) >= 0:
self.ProgressBar.set_fraction(value)
percent = (value*100)
timespent = time.time() - self.start_time
percent_remain = (100-percent)
if percent != 0:
rem = (timespent / percent) * percent_remain
else:
rem = 0.1
min = rem / 60
sec = rem % 60
time_rem = _("%(min)d:%(sec)02d") % {
"min": min,
"sec": sec,
}
if percent_remain > 0.5:
if self.passcounter == int(0):
txt = "Estimated time remaining: %(time)s"
self.ProgressBar.set_text(_(txt) % \
{'time': str(time_rem)})
else:
txt = "Pass %(count)d time remaining: %(time)s"
self.ProgressBar.set_text(_(txt) % { \
'count': self.passcounter, \
'time': str(time_rem), })
return True
else:
self.ProgressBar.set_fraction(0.0)
return False
else:
return False
# Call GObject.timeout_add with a value of 500millisecond to regularly poll
# for position so we can
# use it for the progressbar
def ProgressBarUpdate(self, source):
GObject.timeout_add(500, self.Increment_Progressbar)
def _on_eos(self, source):
context_id = self.StatusBar.get_context_id("EOS")
if self.passcounter == int(0):
self.StatusBar.push(context_id, (_("File saved to %(dir)s") % \
{'dir': self.outputdirectory}))
uri = "file://" + os.path.abspath(os.path.curdir) + "/transmageddon.svg"
notification = Notify.Notification.new("Transmageddon", (_("%(file)s saved to %(dir)s") % {'dir': self.outputdirectory, 'file': self.outputfilename}), uri)
notification.show()
self.FileChooser.set_sensitive(True)
self.containerchoice.set_sensitive(True)
self.CodecBox.set_sensitive(True)
self.presetchoice.set_sensitive(True)
self.cancelbutton.set_sensitive(False)
self.transcodebutton.set_sensitive(True)
self.rotationchoice.set_sensitive(True)
self.start_time = False
self.ProgressBar.set_text(_("Done Transcoding"))
self.ProgressBar.set_fraction(1.0)
self.start_time = False
self.multipass = 0
self.passcounter = 0
self.audiopasstoggle=False
self.videopasstoggle=False
self.houseclean=False # due to not knowing which APIs to use I need
# this toggle to avoid errors when cleaning
# the codec comboboxes
else:
self.start_time = False
if self.passcounter == (self.multipass-1):
self.StatusBar.push(context_id, (_("Writing %(filename)s") % {'filename': self.outputfilename}))
self.passcounter = int(0)
self._start_transcoding()
else:
self.StatusBar.push(context_id, (_("Pass %(count)d Complete. ") % \
{'count': self.passcounter}))
self.passcounter = self.passcounter+1
self._start_transcoding()
def succeed(self, discoverer, info, error):
result=GstPbutils.DiscovererInfo.get_result(info)
if result != GstPbutils.DiscovererResult.ERROR:
streaminfo=info.get_stream_info()
if streaminfo != None:
container = streaminfo.get_caps()
else:
self.check_for_elements()
seekbool = info.get_seekable()
clipduration=info.get_duration()
audiostreamcounter=-1
audiostreams=[]
audiotags=[]
audiochannels=[]
samplerate=[]
inputaudiocaps=[]
markupaudioinfo=[]
videowidth = None
videoheight = None
for i in info.get_stream_list():
if isinstance(i, GstPbutils.DiscovererAudioInfo):
audiostreamcounter=audiostreamcounter+1
inputaudiocaps.append(i.get_caps())
audiostreams.append( \
GstPbutils.pb_utils_get_codec_description(inputaudiocaps[audiostreamcounter]))
audiotags.append(i.get_tags())
test=i.get_channels()
audiochannels.append(i.get_channels())
samplerate.append(i.get_sample_rate())
self.haveaudio=True
self.audiodata = { 'audiochannels' : audiochannels[audiostreamcounter], \
'samplerate' : samplerate[audiostreamcounter], 'audiotype' : inputaudiocaps[audiostreamcounter], \
'clipduration' : clipduration }
markupaudioinfo.append((''.join(('<small>', \
'Audio channels: ', str(audiochannels[audiostreamcounter]) ,'</small>'))))
self.containerchoice.set_active(-1) # set this here to ensure it happens even with quick audio-only
self.containerchoice.set_active(0)
if self.haveaudio==False:
self.audioinformation.set_markup(''.join(('<small>', _("No Audio"), '</small>')))
self.audiocodec.set_markup(''.join(('<small>', "",'</small>')))
if isinstance(i, GstPbutils.DiscovererVideoInfo):
self.inputvideocaps=i.get_caps()
videotags=i.get_tags()
interlacedbool = i.is_interlaced()
if interlacedbool is True:
self.interlaced=True
self.havevideo=True
self.populate_menu_choices() # run this to ensure video menu gets filled
videoheight=i.get_height()
videowidth=i.get_width()
videodenom=i.get_framerate_denom()
videonum=i.get_framerate_num()
self.videodata = { 'videowidth' : videowidth, 'videoheight' : videoheight, 'videotype' : self.inputvideocaps,
'fratenum' : videonum, 'frateden' : videodenom }
self.presetchoice.set_sensitive(True)
self.videorows[0].set_sensitive(True)
self.rotationchoice.set_sensitive(True)
if self.havevideo==False:
self.videoinformation.set_markup(''.join(('<small>', _("No Video"), '</small>')))
self.videocodec.set_markup(''.join(('<small>', "",
'</small>')))
self.presetchoice.set_sensitive(False)
self.videorows[0].set_sensitive(False)
self.rotationchoice.set_sensitive(False)
self.discover_done=True
if self.waiting_for_signal == True:
if self.containertoggle == True:
if self.codeccontainer != False:
self.check_for_passthrough(self.codeccontainer)
else:
# self.check_for_elements()
if self.missingtoggle==False:
self._start_transcoding()
if self.codeccontainer != False:
self.check_for_passthrough(self.codeccontainer)
# set markup
if audiostreamcounter >= 0:
self.audioinformation.set_markup(''.join(('<small>', \
'Audio channels: ', str(audiochannels[0]), '</small>')))
self.audiocodec.set_markup(''.join(('<small>','Audio codec: ', \
str(GstPbutils.pb_utils_get_codec_description(inputaudiocaps[audiostreamcounter])), \
'</small>')))
if videowidth and videoheight:
self.videoinformation.set_markup(''.join(('<small>', 'Video width/height: ', str(videowidth),
"x", str(videoheight), '</small>')))
self.videocodec.set_markup(''.join(('<small>', 'Video codec: ',
str(GstPbutils.pb_utils_get_codec_description (self.inputvideocaps)),
'</small>')))
else:
print("hoped for a great discovery; got an error")
print(result)
print(error)
def discover(self, path):
self.discovered.discover_uri_async("file://"+path)
def mediacheck(self, FileChosen):
uri = urlparse (FileChosen)
path = uri.path
self.discover(path)
def check_for_passthrough(self, containerchoice):
videointersect = Gst.Caps.new_empty()
audiointersect = Gst.Caps.new_empty()
if containerchoice != False: # or self.usingpreset==False): <- Need to figure out what this was about
container = codecfinder.containermap[containerchoice]
containerelement = codecfinder.get_muxer_element(container)
if containerelement == False:
self.containertoggle = True
else:
factory = Gst.Registry.get().lookup_feature(containerelement)
for x in factory.get_static_pad_templates():
if (x.direction == Gst.PadDirection.SINK):
sourcecaps = x.get_caps()
if self.havevideo == True:
if videointersect.is_empty():
videointersect = sourcecaps.intersect(self.videodata['videotype'])
self.vsourcecaps = videointersect
if self.haveaudio == True:
if audiointersect.is_empty():
audiointersect = sourcecaps.intersect(self.audiodata['audiotype'])
#else:
self.asourcecaps = audiointersect
if videointersect.is_empty():
self.videopass=False
else:
self.videopass=True
if audiointersect.is_empty():
self.audiopass=False
else:
self.audiopass=True
# define the behaviour of the other buttons
def on_FileChooser_file_set(self, widget):
self.filename = self.builder.get_object ("FileChooser").get_filename()
self.audiodata = {}
if self.filename is not None:
self.haveaudio=False #make sure to reset these for each file
self.havevideo=False #
self.mediacheck(self.filename)
self.ProgressBar.set_fraction(0.0)
self.ProgressBar.set_text(_("Transcoding Progress"))
if (self.havevideo==False and self.nocontaineroptiontoggle==False):
self.nocontaineroptiontoggle=True
else:
self.presetchoice.set_sensitive(True)
self.presetchoice.set_active(0)
# removing bogus text from supported_containers
if self.bogus==0:
self.containerchoice.remove(12)
self.bogus=1
self.nocontaineroptiontoggle=False
self.containerchoice.set_sensitive(True)
def _start_transcoding(self):
filechoice = self.builder.get_object ("FileChooser").get_uri()
self.filename = self.builder.get_object ("FileChooser").get_filename()
if (self.havevideo and (self.VideoCodec != "novid")):
vheight = self.videodata['videoheight']
vwidth = self.videodata['videowidth']
ratenum = self.videodata['fratenum']
ratednom = self.videodata['frateden']
if self.videopasstoggle == False:
videocodec = self.VideoCodec
else:
videocodec = self.vsourcecaps
self.outputdirectory=self.videodirectory
else:
self.outputdirectory=self.audiodirectory
videocodec=False
vheight=False
vwidth=False
ratenum=False
ratednom=False
if self.haveaudio:
achannels = self.audiodata['audiochannels']
if self.audiopasstoggle == False:
audiocodec = self.AudioCodec
else:
audiocodec = self.asourcecaps
else:
audiocodec=False
achannels=False
self._transcoder = transcoder_engine.Transcoder(filechoice, self.filename,
self.outputdirectory, self.codeccontainer, audiocodec,
videocodec, self.devicename,
vheight, vwidth, ratenum, ratednom, achannels,
self.multipass, self.passcounter, self.outputfilename,
self.timestamp, self.rotationvalue, self.audiopasstoggle,
self.videopasstoggle, self.interlaced, self.inputvideocaps)
self._transcoder.connect("ready-for-querying", self.ProgressBarUpdate)
self._transcoder.connect("got-eos", self._on_eos)
self._transcoder.connect("missing-plugin", self.install_plugin)
return True
def install_plugin(self, signal):
# print("install plugin called")
plugin=GstPbutils.missing_plugin_message_get_installer_detail(self._transcoder.missingplugin)
missing = []
missing.append(plugin)
self.context = GstPbutils.InstallPluginsContext ()
self.context.set_xid(self.get_window().get_xid())
GstPbutils.install_plugins_async (missing, self.context, \
self.donemessage, "NULL")
self.on_cancelbutton_clicked("click")
def donemessage(self, donemessage, null):
# print("donemessage is called")
if donemessage == GstPbutils.InstallPluginsReturn.SUCCESS:
if Gst.update_registry():
print("Plugin registry updated, trying again")
else:
print("Gstreamer registry update failed")
if self.containertoggle == False:
# FIXME - might want some test here to check plugins needed are
# actually installed
# but it is a rather narrow corner case when it fails
self._start_transcoding()
elif donemessage == GstPbutils.InstallPluginsReturn.PARTIAL_SUCCESS:
print("Plugin install not fully succesfull")
elif donemessage == GstPbutils.InstallPluginsReturn.INVALID:
context_id = self.StatusBar.get_context_id("EOS")
self.StatusBar.push(context_id, \
_("Got an invalid response from codec installer, can not install missing codec."))
elif donemessage == GstPbutils.InstallPluginsReturn.HELPER_MISSING:
context_id = self.StatusBar.get_context_id("EOS")
self.StatusBar.push(context_id, \
_("No Codec installer helper application available."))
elif donemessage == GstPbutils.InstallPluginsReturn.NOT_FOUND:
context_id = self.StatusBar.get_context_id("EOS")
self.StatusBar.push(context_id, \
_("Plugins not found, choose different codecs."))
self.FileChooser.set_sensitive(True)
self.containerchoice.set_sensitive(True)
self.CodecBox.set_sensitive(True)
self.cancelbutton.set_sensitive(False)
self.transcodebutton.set_sensitive(True)
elif donemessage == GstPbutils.InstallPluginsReturn.USER_ABORT:
self._cancel_encoding = \
transcoder_engine.Transcoder.Pipeline(self._transcoder,"null")
context_id = self.StatusBar.get_context_id("EOS")
self.StatusBar.push(context_id, _("Codec installation aborted."))
self.FileChooser.set_sensitive(True)
self.containerchoice.set_sensitive(True)
self.CodecBox.set_sensitive(True)
self.cancelbutton.set_sensitive(False)
self.transcodebutton.set_sensitive(True)
else:
context_id = self.StatusBar.get_context_id("EOS")
self.StatusBar.push(context_id, _("Missing plugin installation failed."))
def check_for_elements(self):
# print("checking for elements")
# this function checks for missing plugins using pbutils
if self.codeccontainer==False:
containerstatus=True
videostatus=True
else:
containerchoice = self.builder.get_object ("containerchoice").get_active_text ()
if containerchoice != None:
containerstatus = codecfinder.get_muxer_element(codecfinder.containermap[containerchoice])
if self.havevideo:
if self.videopasstoggle != True:
if self.VideoCodec == "novid":
videostatus=True
else:
videostatus = codecfinder.get_video_encoder_element(self.VideoCodec)
else:
videostatus=True
if self.haveaudio:
if self.audiopasstoggle != True:
audiostatus = codecfinder.get_audio_encoder_element(self.AudioCodec)
else:
audiostatus=True
else:
audiostatus=True
if self.havevideo == False: # this flags help check if input is audio-only file
videostatus=True
if not containerstatus or not videostatus or not audiostatus:
self.missingtoggle=True
fail_info = []
if self.containertoggle==True:
audiostatus=True
videostatus=True
if containerstatus == False:
fail_info.append(Gst.caps_from_string(codecfinder.containermap[containerchoice]))
if audiostatus == False:
fail_info.append(self.AudioCodec)
if videostatus == False:
fail_info.append(self.VideoCodec)
missing = []
for x in fail_info:
missing.append(GstPbutils.missing_encoder_installer_detail_new(x))
context = GstPbutils.InstallPluginsContext ()
context.set_xid(self.get_window().get_xid())
GstPbutils.install_plugins_async (missing, context, \
self.donemessage, "NULL")
# The transcodebutton is the one that calls the Transcoder class and thus
# starts the transcoding
def on_transcodebutton_clicked(self, widget):
self.containertoggle = False
self.FileChooser.set_sensitive(False)
self.containerchoice.set_sensitive(False)
self.presetchoice.set_sensitive(False)
self.CodecBox.set_sensitive(False)
self.transcodebutton.set_sensitive(False)
self.rotationchoice.set_sensitive(False)
self.cancelbutton.set_sensitive(True)
self.ProgressBar.set_fraction(0.0)
# create a variable with a timestamp code
timeget = datetime.datetime.now()
self.timestamp = str(timeget.strftime("-%H%M%S-%d%m%Y"))
# Remove suffix from inbound filename so we can reuse it together with suffix to create outbound filename
self.nosuffix = os.path.splitext(os.path.basename(self.filename))[0]
# pick output suffix
container = self.builder.get_object("containerchoice").get_active_text()
if self.codeccontainer==False: # deal with container less formats
self.ContainerFormatSuffix = codecfinder.nocontainersuffixmap[Gst.Caps.to_string(self.AudioCodec)]
else:
if self.havevideo == False:
self.ContainerFormatSuffix = codecfinder.audiosuffixmap[container]
else:
self.ContainerFormatSuffix = codecfinder.csuffixmap[container]
self.outputfilename = str(self.nosuffix+self.timestamp+self.ContainerFormatSuffix)
context_id = self.StatusBar.get_context_id("EOS")
self.StatusBar.push(context_id, (_("Writing %(filename)s") % {'filename': self.outputfilename}))
if self.multipass != 0:
self.passcounter=int(1)
self.StatusBar.push(context_id, (_("Pass %(count)d Progress") % {'count': self.passcounter}))
if self.haveaudio:
if "samplerate" in self.audiodata:
# self.check_for_elements()
if self.missingtoggle==False:
self._start_transcoding()
else:
self.waiting_for_signal="True"
elif self.havevideo:
if "videoheight" in self.videodata:
# self.check_for_elements()
if self.missingtoggle==False:
self._start_transcoding()
else:
self.waiting_for_signal="True"
def on_cancelbutton_clicked(self, widget):
self.FileChooser.set_sensitive(True)
self.containerchoice.set_sensitive(True)
self.CodecBox.set_sensitive(True)
self.presetchoice.set_sensitive(True)
self.rotationchoice.set_sensitive(True)
self.presetchoice.set_active(0)
self.cancelbutton.set_sensitive(False)
self.transcodebutton.set_sensitive(True)
self._cancel_encoding = \
transcoder_engine.Transcoder.Pipeline(self._transcoder,"null")
self.ProgressBar.set_fraction(0.0)
self.ProgressBar.set_text(_("Transcoding Progress"))
context_id = self.StatusBar.get_context_id("EOS")
self.StatusBar.pop(context_id)
def populate_menu_choices(self):
# self.audiocodecs - contains list of whats in self.audiorows
# self.videocodecs - contains listof whats in self.videorows
# audio_codecs, video_codecs - temporary lists
# clean up stuff from previous run
self.houseclean=True # set this to avoid triggering events when cleaning out menus
for c in self.audiocodecs: #
self.audiorows[0].remove(0)
self.audiocodecs =[]
if self.havevideo==True:
if self.codeccontainer != False:
for c in self.videocodecs:
self.videorows[0].remove(0)
self.videocodecs=[]
self.houseclean=False
# end of housecleaning
# start filling audio
if self.haveaudio==True:
if self.usingpreset==True: # First fill menu based on presetvalue
testforempty = self.presetaudiocodec.to_string()
if testforempty != "EMPTY":
self.audiorows[0].append_text(str(GstPbutils.pb_utils_get_codec_description(self.presetaudiocodec)))
self.audiorows[0].set_active(0)
self.audiocodecs.append(self.presetaudiocodec)
elif self.codeccontainer==False: # special setup for container less case, looks ugly, but good enough for now
self.audiorows[0].append_text(str(GstPbutils.pb_utils_get_codec_description(Gst.caps_from_string("audio/mpeg, mpegversion=(int)1, layer=(int)3"))))
self.audiorows[0].append_text(str(GstPbutils.pb_utils_get_codec_description(Gst.caps_from_string("audio/mpeg, mpegversion=4, stream-format=adts"))))
self.audiorows[0].append_text(str(GstPbutils.pb_utils_get_codec_description(Gst.caps_from_string("audio/x-flac"))))
self.audiocodecs.append(Gst.caps_from_string("audio/mpeg, mpegversion=(int)1, layer=(int)3"))
self.audiocodecs.append(Gst.caps_from_string("audio/mpeg, mpegversion=4, stream-format=adts"))
self.audiocodecs.append(Gst.caps_from_string("audio/x-flac"))
self.audiorows[0].set_active(0)
self.audiorows[0].set_sensitive(True)
else:
audio_codecs = []
audio_codecs = supported_audio_container_map[self.codeccontainer]
for c in audio_codecs:
self.audiocodecs.append(Gst.caps_from_string(codecfinder.codecmap[c]))
for c in self.audiocodecs: # Use codec descriptions from GStreamer
self.audiorows[0].append_text(GstPbutils.pb_utils_get_codec_description(c))
self.audiorows[0].set_sensitive(True)
self.audiorows[0].set_active(0)
else:
self.audiorows[0].set_sensitive(False)
# fill in with video
if self.havevideo==True:
if self.codeccontainer != False:
if self.usingpreset==True:
testforempty = self.presetvideocodec.to_string()
if testforempty != "EMPTY":
self.videorows[0].append_text(str(GstPbutils.pb_utils_get_codec_description(self.presetvideocodec)))
self.videorows[0].set_active(0)
self.videocodecs.append(self.presetvideocodec)
else:
video_codecs=[]
video_codecs = supported_video_container_map[self.codeccontainer]
self.rotationchoice.set_sensitive(True)
for c in video_codecs:
self.videocodecs.append(Gst.caps_from_string(codecfinder.codecmap[c]))
for c in self.videocodecs: # Use descriptions from GStreamer
self.videorows[0].append_text(GstPbutils.pb_utils_get_codec_description(c))
self.videorows[0].set_sensitive(True)
self.videorows[0].set_active(0)
#add a 'No Video option'
self.videorows[0].append_text(_("No Video"))
self.videocodecs.append("novid")
self.videonovideomenuno=(len(self.videocodecs))-1
# add the Passthrough option
if self.videopass==True:
self.videorows[0].append_text(_("Video passthrough"))
self.videocodecs.append("pass")
self.videopassmenuno=(len(self.videocodecs))-1
if self.audiopass==True:
self.audiorows[0].append_text(_("Audio passthrough"))
self.audiocodecs.append("pass")
self.audiopassmenuno=(len(self.audiocodecs))-1
def on_containerchoice_changed(self, widget):
self.CodecBox.set_sensitive(True)
self.ProgressBar.set_fraction(0.0)
self.ProgressBar.set_text(_("Transcoding Progress"))
if self.builder.get_object("containerchoice").get_active() == self.nocontainernumber:
self.codeccontainer = False
self.videorows[0].set_active(self.videonovideomenuno)
self.videorows[0].set_sensitive(False)
else:
if self.builder.get_object("containerchoice").get_active()!= -1:
self.codeccontainer = self.builder.get_object ("containerchoice").get_active_text()
self.check_for_elements()
if self.discover_done == True:
self.check_for_passthrough(self.codeccontainer)
self.populate_menu_choices()
self.transcodebutton.set_sensitive(True)
def on_presetchoice_changed(self, widget):
presetchoice = self.builder.get_object ("presetchoice").get_active()
self.ProgressBar.set_fraction(0.0)
if presetchoice == 0:
self.usingpreset=False
self.devicename = "nopreset"
self.containerchoice.set_sensitive(True)
self.containerchoice.set_active(0)
self.start_time = False
self.multipass = 0
self.passcounter = 0
self.rotationchoice.set_sensitive(True)
if self.builder.get_object("containerchoice").get_active():
self.populate_menu_choices()
self.CodecBox.set_sensitive(True)
self.transcodebutton.set_sensitive(True)
else:
self.usingpreset=True
self.ProgressBar.set_fraction(0.0)
if presetchoice != None:
self.devicename= self.presetchoices[presetchoice-1]
self.provide_presets(self.devicename)
self.containerchoice.set_sensitive(False)
self.CodecBox.set_sensitive(False)
self.rotationchoice.set_sensitive(False)
else:
if self.builder.get_object("containerchoice").get_active_text():
self.transcodebutton.set_sensitive(True)
def on_rotationchoice_changed(self, widget):
self.rotationvalue = self.rotationchoice.get_active()
def on_audiocodec_changed(self, widget):
self.audiopasstoggle=False
if (self.houseclean == False and self.usingpreset==False):
self.AudioCodec = self.audiocodecs[self.audiorows[0].get_active()]
if self.codeccontainer != False:
if self.audiorows[0].get_active() == self.audiopassmenuno:
self.audiopasstoggle=True
elif self.usingpreset==True:
self.AudioCodec = self.presetaudiocodec
def on_videocodec_changed(self, widget):
self.videopasstoggle=False
if (self.houseclean == False and self.usingpreset==False):
if self.codeccontainer != False:
self.VideoCodec = self.videocodecs[self.videorows[0].get_active()]
else:
self.VideoCodec = "novid"
self.rotationchoice.set_sensitive(False)
if self.videorows[0].get_active() == self.videopassmenuno:
self.videopasstoggle=True
elif self.usingpreset==True:
self.VideoCodec = self.presetvideocodec
# Setup i18n support
import locale
from gettext import gettext as _
import gettext
import signal
#Set up i18n
gettext.bindtextdomain("transmageddon","../../share/locale")
gettext.textdomain("transmageddon")
if __name__ == "__main__":
app = Transmageddon()
# FIXME: Get rid of the following line which has the only purpose of
# working around Ctrl+C not exiting Gtk applications from bug 622084.
# https://bugzilla.gnome.org/show_bug.cgi?id=622084
signal.signal(signal.SIGINT, signal.SIG_DFL)
exit_status = app.run(sys.argv)
sys.exit(exit_status)
|