Example #1
0
    def run(self):

        self.queue_complete = False
        while 1:
            # Blocca finché c'è qualcosa da processare nella coda
            request = self.request_queue.get()
            # Se l'elemento della coda è None esce
            if request is None:
                break
            # Estrae dall'elemento della coda da processare
            n, sel = request

            # Avanza la progressbar
            self.work_complete = False
            self.amount_completed = 0
            self.idevent = gobject.timeout_add(200,
                                               self.mainapp.on_ProgressBar)

            # Seleziona il file da processare
            af = sel[0]
            it = sel[1]
            try:
                self.mainapp.FileTable.tvSelection.select_iter(it)
            except:
                pass

            # Prepara il messaggio per la status bar
            self.n = n
            if af.get_tag("title") != "Unknown title" and af.get_tag(
                    "artist") != "Unknown artist":
                self.msg = af.get_tag("artist") + " - " + af.get_tag("title")
            else:
                self.msg = af.get_filename()

            # Percorso di ingresso
            if af.get_uri()[:7] == "file://":
                input_path = af.get_uri()[7:]
            elif af.get_uri()[:7] == "cdda://":
                input_path = af.get_uri()[7:]
            else:
                input_path = af.get_uri()

            # Se usa gstreamer per la conversione
            if not bool(int(self.prefs.get_option("use-external-encoder"))):
                # Estrae le opzioni per la conversione
                print self.Options(af, self.prefs)
                format, mode, qual, bitrate, save_path, output_file_name, tagsv1, tagsv2 = self.Options(
                    af, self.prefs)
                # Pipeline
                converter_pipe = Pipeline(input_path, format, mode, qual,
                                          bitrate,
                                          save_path + "/" + output_file_name)

                # Rimane nel ciclo finché la pipeline non è finita
                while 1:
                    state, pending, timeout = converter_pipe.pipe.get_state()
                    if pending == gst.STATE_NULL:
                        print "Finito:", input_path
                        self.work_complete = True
                        gobject.source_remove(self.idevent)
                        break
                    else:
                        position = converter_pipe.pipe.query_position(
                            gst.FORMAT_TIME, None)[0]
                        perc = float(position) / converter_pipe.duration
                        if perc > 1:
                            perc = 0
                        time.sleep(0.1)
                        self.amount_completed = perc

                # Scrive i tags
                af_output = AudioFile("file://" + save_path + "/" +
                                      output_file_name + "." + format)
                if tagsv1:
                    af_output.set_tags_as_dict(af.get_tags_as_dict())
                    af_output.set_tag("comment", "X Audio Copy")
                    af_output.write_metadata()
                else:
                    af_output.remove_metadata()
                if tagsv2:
                    af_output.write_ID3v2()

                if bool(int(self.prefs.get_option("playlist"))):
                    if "/CD" in save_path:
                        self.savepath = save_path[:save_path.index("/CD")]
                    else:
                        self.savepath = save_path
                    self.playlistname = af_output.get_tag(
                        "artist") + " - " + af_output.get_tag("album")
                    self.listsongs.append("#EXTINF:" +
                                          str(int(af_output.get_duration())) +
                                          "," + af_output.get_tag("artist") +
                                          " - " + af_output.get_tag("title") +
                                          "\n")
                    self.listsongs.append(save_path[save_path.index("/CD") +
                                                    1:] + "/" +
                                          af_output.get_filename() + "\n")
                self.work_complete = True

            # Se usa un encoder esterno. Prima decodifica il file.
            elif bool(int(self.prefs.get_option(
                    "use-external-encoder"))) and self.Options(af, self.prefs):

                # Estrae le opzioni per la conversione
                opt_string, input_path, output_path, tagsv1, tagsv2 = self.Options(
                    af, self.prefs)

                if af.get_type() == "audio/x-wav":
                    opt_string = opt_string.replace('"temporarypath"',
                                                    '"' + input_path + '"')
                    perc = 0.0
                else:
                    # Directory temporanea
                    tempdir = tempfile.mkdtemp()
                    #Pipeline per decodificare in wav
                    converter_pipe = Pipeline(input_path, "wav", None, None,
                                              None, tempdir + "/temp_file")

                    # Rimane nel ciclo finché la pipeline non è finita
                    while 1:
                        state, pending, timeout = converter_pipe.pipe.get_state(
                        )
                        if pending == gst.STATE_NULL:
                            print "Decodifica finita"
                            break
                        else:
                            position = converter_pipe.pipe.query_position(
                                gst.FORMAT_TIME, None)[0]
                            perc = float(
                                position) / converter_pipe.duration / 50
                            if perc > 1:
                                perc = 0
                            time.sleep(0.1)
                            self.amount_completed = perc
                    # Passa il file decodificato all'encoder esterno
                    opt_string = opt_string.replace(
                        '"temporarypath"', '"' + tempdir + '/temp_file.wav"')

                init_encoder_time = time.time()
                encoder_args = shlex.split(opt_string)
                encoder = Encoder(encoder_args)
                # Rimane nel ciclo finché il sub-processo non è finito
                while 1:
                    if encoder.process.poll() == 0:
                        print "Finito:", input_path
                        self.work_complete = True
                        gobject.source_remove(self.idevent)
                        break
                    else:
                        if (time.time() - init_encoder_time > 1):
                            if perc < 1:
                                tag = TagFinder("file://" + output_path)
                                encoding_done = tag.get_duration()
                                perc = float(
                                    encoding_done) / af.get_duration() / 2.1
                                print "PERCENTUALE: ", perc
                                if perc < 1:
                                    self.amount_completed = perc
                                else:
                                    self.amount_completed = 1
                            else:
                                self.amount_completed = 1
                        time.sleep(2)
                try:
                    walk = os.walk(tempdir)
                    for dirpath, subdir, filenames in walk:
                        for f in filenames:
                            os.remove(os.path.join(dirpath, f))
                    os.rmdir(tempdir)
                except:
                    pass

                # Scrive la playlist
                if bool(int(self.prefs.get_option("playlist"))):
                    if "/CD" in output_path:
                        self.savepath = os.path.split(output_path)[
                            0][:os.path.split(output_path)[0].index("/CD")]
                    else:
                        self.savepath = os.path.split(output_path)[0]
                    self.playlistname = af.get_tag(
                        "artist") + " - " + af.get_tag("album")
                    self.listsongs.append("#EXTINF:" +
                                          str(int(af.get_duration())) + "," +
                                          af.get_tag("artist") + " - " +
                                          af.get_tag("title") + "\n")
                    self.listsongs.append(output_path[len(self.savepath +
                                                          "/"):] + "\n")

                self.work_complete = True
            else:
                gobject.source_remove(self.idevent)
                self.msg = "nothing. No external encoder. Please choise a valid encoder"

            # Cancella i file originali se previsto
            if bool(int(self.prefs.get_option("delete-original-files"))):
                if af.get_uri()[:7] == "file://":
                    os.remove(af.get_filepath())

        self.queue_complete = True
        self.mainapp.on_ProgressBar()
    def __init__(self, uri, pointer=None):

        print "\n==== Istanza di AudioFile ====\n"

        # Puntatore esterno
        self.pointer = pointer

        # Indirizzo da usare per la riproduzione ('gstreamer')
        self.__uri = uri

        # Nome del file con o senza path e path derivati dall'uri
        (self.__folderuri, self.__filename) = os.path.split(self.__uri)
        if self.__folderuri == "cdda:":
            self.__foldername = "Audio CD"
            self.__filepath = self.__uri
        elif ("cdda:" in self.__folderuri) and self.__filename.endswith(".wav"):
            self.__folderuri = "cdda:"
            res = re.compile("\d+").findall(self.__filename)
            self.__uri = self.__folderuri + "//" + "%.02d" % (int(res[0]))
            self.__foldername = "Audio CD"
            self.__filename = "Track " + "%.02d" % (int(res[0])) + ".wav"
            self.__filepath = self.__uri
        elif self.__folderuri.startswith("file://"):
            self.__foldername = self.__folderuri[7:]
            self.__filepath = self.__foldername + "/" + self.__filename
        else:
            self.__foldername = self.__folderuri
            self.__filepath = self.__uri

        print "Uri: ", self.__uri
        print "Folder Uri: ", self.__folderuri
        print "Folder name: ", self.__foldername
        print "File name: ", self.__filename
        print "File path: ", self.__filepath

        # Inizializza i tag principali
        self.__tags_dict = {
            "track_number": "",
            "title": "",
            "artist": "",
            "album": "",
            "year": "",
            "genre": "",
            "comment": "",
            "album_artist": "",
            "composer": "",
            "track_count": "",
            "disc_number": "",
            "cover": None,
        }

        # Inizializza altri attributi
        self.__filesize = None
        # Durata in secondi (float)
        self.__duration = None
        # Durata come stringa "h:mm:ss,mil"
        self.__duration_mm_ss = None
        # Inizio e fine in un CD
        self.__start_time = None
        self.__end_time = None
        # Mime type
        self.__mime_type = None
        # Numero di canali
        self.__n_channels = None
        # Byte per campione
        self.__sampwidth_B = None
        # Bit per campione
        self.__sampwidth_b = None
        # Frequenza di campionamento
        self.__framerate = None
        # Numero di campioni
        self.__n_frames = None
        # Tipo di compressione (none per i file wav)
        self.__comp_type = None
        # Tipo ricavato con gstreamer
        self.__gst_type = None
        # Dizionario con i tag ricavati con gstreamer
        self.__gst_tags = None
        # Formato del contenitore (es. ogg)
        self.__container_format = None
        # Codec audio (es. H.264/AVC Video)
        self.__audio_codec = None
        # Codec video (es. vorbis)
        self.__video_codec = None
        # Bitrate file compressi
        self.__bitrate = None
        # Bitrate nominale file compressi (Vorbis comment)
        self.__nominal_bitrate = None
        # Stere o join stereo
        self.__channel_mode = None
        # CRC
        self.__has_crc = None
        # Encoder e versione
        self.__encoder = None
        self.__encoder_version = None
        self.__private_frame = None
        # Flac
        self.__extended_comment = None

        # Dimensioni del file
        if os.path.exists(self.__filepath):
            self.__filesize = os.stat(self.__filepath).st_size
        print "self.__filesize: ", self.__filesize
        # Trova il mimetype del file (usa il modulo "mimetypes")
        # Non funziona con i CD
        self.__mime_type = mimetypes.guess_type(self.__uri)[0]
        print "Mime type: ", self.__mime_type
        # Dovrebbero già essere stati filtrati in sede di apertura,
        # ma è meglio verificare
        if str(self.__mime_type) in MIME_WHITE_LIST:
            print "Mime type valido"
        else:
            print "Mime type non valido"

            # Trova il tipo di file con gstreamer
        if "cdda:" in self.__folderuri:
            self.__gst_type = "audio/x-raw-int"
        else:
            typeFinder = TypeFinder(self.__uri)
            self.__gst_type = typeFinder.get_type()
        print "self.__gst_type: ", self.__gst_type

        # Cerca i tag nel file con gst
        tagFinder = TagFinder(self.__uri)
        self.__gst_tags = tagFinder.get_tags()

        # Ricava la durata del brano in secondi
        self.__duration = tagFinder.get_duration()

        # Inizializza i dati audio SOLO per file wav (usa il modulo "wave")
        if self.__mime_type == "audio/x-wav":
            w = wave.open(self.__filepath)
            self.__n_channels = w.getnchannels()
            self.__sampwidth_B = w.getsampwidth()
            self.__sampwidth_b = self.__sampwidth_B * 8
            self.__framerate = w.getframerate()
            self.__n_frames = w.getnframes()
            w.close()
        else:
            infoFinder = InfoFinder(self.__uri, self.__gst_type)
            info = infoFinder.get_info()
            self.__n_channels = info["n_channels"]
            self.__sampwidth_B = info["sampwidth_B"]
            self.__sampwidth_b = info["sampwidth_b"]
            self.__framerate = info["framerate"]
            self.__n_frames = info["n_frames"]

        print "n_channels: ", self.__n_channels
        print "sampwidth_B: ", self.__sampwidth_B
        print "sampwidth_b: ", self.__sampwidth_b
        print "framerate: ", self.__framerate
        print "n_frames: ", self.__n_frames

        # Se gstreamer non è riuscito a calcolare la durata del brano
        if self.__duration == None:
            if self.__mime_type == "audio/x-wav":
                # Altrimenti prova a calcolare la durata per i file wav
                size = os.stat(self.__filepath + "/" + self.__filepath).st_size
                if self.__comp_type == "NONE":
                    self.__duration = float(float(self.__n_frames) / float(self.__framerate))
                    print "Duration from size: ", self.__duration

        if not (self.__duration == None):
            self.__duration_h = int(self.__duration / 3600)
            self.__duration_m = int(self.__duration / 60) - self.__duration_h * 60
            self.__duration_s = int(self.__duration) - self.__duration_m * 60 - self.__duration_h * 3600
            self.__duration_mil = int(round(1000 * (self.__duration - int(self.__duration))))
            mm_ss = (
                str(self.__duration_m)
                + ":"
                + "%(#)02d" % {"#": self.__duration_s}
                + "."
                + "%(#)03d" % {"#": self.__duration_mil}
            )
            if not (self.__duration_h == 0):
                self.__duration_mm_ss = str(self.__duration_h) + "h " + mm_ss
            else:
                self.__duration_mm_ss = mm_ss
            print "duration_mm_ss: ", self.__duration_mm_ss

            # Riempie i tag
        try:
            self.__tags_dict["track_number"] = self.__gst_tags["track-number"]
        except KeyError:
            # Se il tag "track-number" passato da gst è vuoto, cerca di
            # assegnare il numero di traccia se presente nel titolo come "nn" o "n".
            # Utile se i file sono tracce di CD o file nominati come
            # "Track nn.wav" oppure "Track nn.cda" oppure
            # "nn - Artist - Title.*" o simili.
            for ext in fileext:
                if self.__filename.endswith(ext):
                    print "self.__filename[-4:]: ", self.__filename[-4:]
                    if re.compile("\d+" + ext).findall(self.__filepath):
                        res = re.compile("\d+" + ext).findall(self.__filepath)
                        print "res: ", res
                        for e in res:
                            print "e: ", e
                            res = re.compile("\d+").findall(e)
                            for n in res:
                                print "n: ", n
                                self.__tags_dict["track_number"] = n
                elif re.compile("\d+").findall(self.__filename[0:2]):
                    res = re.compile("\d+").findall(self.__filename[0:2])
                    self.__tags_dict["track_number"] = res[0]
        try:
            # Mette uno zero davanti al numero se manca
            self.__tags_dict["track_number"] = "%.02d" % (self.__tags_dict["track_number"])
        except:
            pass
        try:
            self.__tags_dict["title"] = self.__gst_tags["title"]
        except KeyError:
            pass
        try:
            self.__tags_dict["artist"] = self.__gst_tags["artist"]
        except KeyError:
            pass
        try:
            self.__tags_dict["album"] = self.__gst_tags["album"]
        except KeyError:
            pass
        try:
            self.__tags_dict["year"] = self.__gst_tags["date"].year
        except KeyError:
            pass
        try:
            self.__tags_dict["genre"] = self.__gst_tags["genre"]
        except KeyError:
            pass
        try:
            self.__tags_dict["comment"] = self.__gst_tags["comment"]
        except KeyError:
            pass
        try:
            self.__tags_dict["album_artist"] = self.__gst_tags["album-artist"]
        except KeyError:
            pass
        try:
            self.__tags_dict["composer"] = self.__gst_tags["composer"]
        except KeyError:
            pass
        try:
            self.__tags_dict["track_count"] = str(self.__gst_tags["track-count"])
        except KeyError:
            pass
        try:
            self.__tags_dict["disc_number"] = self.__gst_tags["album-disc-number"]
        except KeyError:
            pass
        # Cover per mp3
        try:
            self.__tags_dict["cover"] = self.__gst_tags["image"]
        except KeyError:
            pass
        # Cover per ogg
        try:
            self.__tags_dict["cover"] = self.__gst_tags["preview-image"]
        except KeyError:
            pass

        # Altre proprietà del brano da gstreamer
        try:
            self.__container_format = self.__gst_tags["container-format"]
        except KeyError:
            pass
        try:
            self.__audio_codec = self.__gst_tags["audio-codec"]
        except KeyError:
            pass
        try:
            self.__video_codec = self.__gst_tags["video-codec"]
        except KeyError:
            pass
        try:
            self.__bitrate = self.__gst_tags["bitrate"]
        except KeyError:
            pass
        try:
            self.__nominal_bitrate = self.__gst_tags["nominal-bitrate"]
        except KeyError:
            pass
        try:
            self.__channel_mode = self.__gst_tags["channel-mode"]
        except KeyError:
            pass
        try:
            self.__has_crc = self.__gst_tags["has-crc"]
        except KeyError:
            pass
        try:
            self.__encoder = self.__gst_tags["encoder"]
        except KeyError:
            pass
        try:
            self.__encoder_version = self.__gst_tags["encoder-version"]
        except KeyError:
            pass
        try:
            self.__private_frame = self.__gst_tags["private-id3v2-frame"]
        except KeyError:
            pass
        try:
            self.__extended_comment = self.__gst_tags["extended-comment"]
        except KeyError:
            pass
Example #3
0
    def __init__(self, uri, pointer=None):

        print "\n==== Istanza di AudioFile ====\n"

        # Puntatore esterno
        self.pointer = pointer

        #Indirizzo da usare per la riproduzione ('gstreamer')
        self.__uri = uri

        # Nome del file con o senza path e path derivati dall'uri
        (self.__folderuri, self.__filename) = os.path.split(self.__uri)
        if self.__folderuri == "cdda:":
            self.__foldername = "Audio CD"
            self.__filepath = self.__uri
        elif self.__folderuri[:7] == "file://":
            self.__foldername = self.__folderuri[7:]
            self.__filepath = self.__foldername + "/" + self.__filename
        else:
            self.__foldername = self.__folderuri
            self.__filepath = self.__uri

        print "Uri: ", self.__uri
        print "Folder Uri: ", self.__folderuri
        print "Folder name: ", self.__foldername
        print "File name: ", self.__filename
        print "File path: ", self.__filepath

        # Inizializza i tag principali
        self.__tags_dict = {
            "track_number": "",
            "title": "",
            "artist": "",
            "album": "",
            "year": "",
            "genre": "",
            "comment": "",
            "album_artist": "",
            "composer": "",
            "track_count": "",
            "disc_number": "",
            "cover": None,
        }

        # Inizializza altri attributi
        self.__filesize = None
        # Durata in secondi (float)
        self.__duration = None
        # Durata come stringa "h:mm:ss,mil"
        self.__duration_mm_ss = None
        # Inizio e fine in un CD
        self.__start_time = None
        self.__end_time = None
        # Mime type
        self.__mime_type = None
        # Numero di canali
        self.__n_channels = None
        # Byte per campione
        self.__sampwidth_B = None
        # Bit per campione
        self.__sampwidth_b = None
        # Frequenza di campionamento
        self.__framerate = None
        # Numero di campioni
        self.__n_frames = None
        # Tipo di compressione (none per i file wav)
        self.__comp_type = None
        # Tipo ricavato con gstreamer
        self.__gst_type = None
        # Dizionario con i tag ricavati con gstreamer
        self.__gst_tags = None
        # Formato del contenitore (es. ogg)
        self.__container_format = None
        # Codec audio (es. H.264/AVC Video)
        self.__audio_codec = None
        # Codec video (es. vorbis)
        self.__video_codec = None
        # Bitrate file compressi
        self.__bitrate = None
        # Bitrate nominale file compressi (Vorbis comment)
        self.__nominal_bitrate = None
        # Stere o join stereo
        self.__channel_mode = None
        # CRC
        self.__has_crc = None
        # Encoder e versione
        self.__encoder = None
        self.__encoder_version = None
        self.__private_frame = None
        # Flac
        self.__extended_comment = None

        # Dimensioni del file
        if os.path.exists(self.__filepath):
            self.__filesize = os.stat(self.__filepath).st_size

        # Trova il mimetype del file (usa il modulo "mimetypes")
        # Non funziona con i CD
        self.__mime_type = mimetypes.guess_type(self.__uri)[0]
        print "Mime type: ", self.__mime_type
        # Dovrebbero già essere stati filtrati in sede di apertura,
        # ma è meglio verificare
        if str(self.__mime_type) in MIME_WHITE_LIST:
            print "Mime type valido"
        else:
            print "Mime type non valido"

        # Trova il tipo di file con gstreamer
        if self.__folderuri == "cdda:":
            self.__gst_type = "audio/x-raw-int"
        else:
            typeFinder = TypeFinder(self.__uri)
            self.__gst_type = typeFinder.get_type()
            print "__gst_type ", self.__gst_type

        # Cerca i tag nel file con gst
        tagFinder = TagFinder(self.__uri)
        self.__gst_tags = tagFinder.get_tags()
        print "self.__gst_tags ", self.__gst_tags

        # Ricava la durata del brano in secondi
        self.__duration = tagFinder.get_duration()

        #Inizializza i dati audio SOLO per file wav (usa il modulo "wave")
        if self.__mime_type == "audio/x-wav":
            w = wave.open(self.__filepath)
            self.__n_channels = w.getnchannels()
            self.__sampwidth_B = w.getsampwidth()
            self.__sampwidth_b = self.__sampwidth_B * 8
            self.__framerate = w.getframerate()
            self.__n_frames = w.getnframes()
            w.close()
        else:
            infoFinder = InfoFinder(self.__uri)
            info = infoFinder.get_info()
            self.__n_channels = info["n_channels"]
            self.__sampwidth_B = info["sampwidth_B"]
            self.__sampwidth_b = info["sampwidth_b"]
            self.__framerate = info["framerate"]
            self.__n_frames = info["n_frames"]

            print "n_channels: ", self.__n_channels
            print "sampwidth_B: ", self.__sampwidth_B
            print "sampwidth_b: ", self.__sampwidth_b
            print "framerate: ", self.__framerate
            print "n_frames: ", self.__n_frames

        # Se gstreamer non è riuscito a calcolare la durata del brano
        if self.__duration == None:
            if self.__mime_type == "audio/x-wav":
                # Altrimenti prova a calcolare la durata per i file wav
                size = os.stat(self.__filepath + "/" + self.__filepath).st_size
                if self.__comp_type == "NONE":
                    self.__duration = float(
                        float(self.__n_frames) / float(self.__framerate))
                    print "Duration from size: ", self.__duration

        if not (self.__duration == None):
            self.__duration_h = int(self.__duration / 3600)
            self.__duration_m = int(
                self.__duration / 60) - self.__duration_h * 60
            self.__duration_s = int(
                self.__duration
            ) - self.__duration_m * 60 - self.__duration_h * 3600
            self.__duration_mil = int(
                round(1000 * (self.__duration - int(self.__duration))))
            mm_ss = str(self.__duration_m) + ":" + '%(#)02d' % {
                "#": self.__duration_s
            } + "." + '%(#)03d' % {
                "#": self.__duration_mil
            }
            if not (self.__duration_h == 0):
                self.__duration_mm_ss = str(self.__duration_h) + "h " + mm_ss
            else:
                self.__duration_mm_ss = mm_ss
            print "duration_mm_ss: ", self.__duration_mm_ss

        # Riempie i tag
        try:
            self.__tags_dict["track_number"] = self.__gst_tags["track-number"]
        except KeyError:
            # Se il tag "track-number" passato da gst è vuoto, cerca di
            # assegnare il numero di traccia se presente nel titolo come "nn" o "n".
            # Utile se i file sono tracce di CD o file nominati come
            # "Track nn.wav" oppure "Track nn.cda" oppure
            # "nn - Artist - Title.*" o simili.
            for ext in fileext:
                if self.__filename[-4:] == ext:
                    print "self.__filename[-4:]: ", self.__filename[-4:]
                    if re.compile('\d+' + ext).findall(self.__filepath):
                        res = re.compile('\d+' + ext).findall(self.__filepath)
                        print "res: ", res
                        for e in res:
                            print "e: ", e
                            res = re.compile('\d+').findall(e)
                            for n in res:
                                print "n: ", n
                                self.__tags_dict["track_number"] = n
                elif re.compile('\d+').findall(self.__filename[0:2]):
                    res = re.compile('\d+').findall(self.__filename[0:2])
                    self.__tags_dict["track_number"] = res[0]
        try:
            # Mette uno zero davanti al numero se manca
            self.__tags_dict["track_number"] = "%.02d" % (
                self.__tags_dict["track_number"])
        except:
            pass
        try:
            self.__tags_dict["title"] = self.__gst_tags["title"]
        except KeyError:
            pass
        try:
            self.__tags_dict["artist"] = self.__gst_tags["artist"]
        except KeyError:
            pass
        try:
            self.__tags_dict["album"] = self.__gst_tags["album"]
        except KeyError:
            pass
        try:
            self.__tags_dict["year"] = self.__gst_tags["date"].year
        except KeyError:
            pass
        try:
            self.__tags_dict["genre"] = self.__gst_tags["genre"]
        except KeyError:
            pass
        try:
            self.__tags_dict["comment"] = self.__gst_tags["comment"]
        except KeyError:
            pass
        try:
            self.__tags_dict["album_artist"] = self.__gst_tags["album-artist"]
        except KeyError:
            pass
        try:
            self.__tags_dict["composer"] = self.__gst_tags["composer"]
        except KeyError:
            pass
        try:
            self.__tags_dict["track_count"] = str(
                self.__gst_tags["track-count"])
        except KeyError:
            pass
        try:
            self.__tags_dict["disc_number"] = self.__gst_tags[
                "album-disc-number"]
        except KeyError:
            pass
        # Cover per mp3
        try:
            self.__tags_dict["cover"] = self.__gst_tags["image"]
        except KeyError:
            pass
        # Cover per ogg
        try:
            self.__tags_dict["cover"] = self.__gst_tags["preview-image"]
        except KeyError:
            pass

        # Altre proprietà del brano da gstreamer
        try:
            self.__container_format = self.__gst_tags["container-format"]
        except KeyError:
            pass
        try:
            self.__audio_codec = self.__gst_tags["audio-codec"]
        except KeyError:
            pass
        try:
            self.__video_codec = self.__gst_tags["video-codec"]
        except KeyError:
            pass
        try:
            self.__bitrate = self.__gst_tags["bitrate"]
        except KeyError:
            pass
        try:
            self.__nominal_bitrate = self.__gst_tags["nominal-bitrate"]
        except KeyError:
            pass
        try:
            self.__channel_mode = self.__gst_tags["channel-mode"]
        except KeyError:
            pass
        try:
            self.__has_crc = self.__gst_tags["has-crc"]
        except KeyError:
            pass
        try:
            self.__encoder = self.__gst_tags["encoder"]
        except KeyError:
            pass
        try:
            self.__encoder_version = self.__gst_tags["encoder-version"]
        except KeyError:
            pass
        try:
            self.__private_frame = self.__gst_tags["private-id3v2-frame"]
        except KeyError:
            pass
        try:
            self.__extended_comment = self.__gst_tags["extended-comment"]
        except KeyError:
            pass
	def run(self):

		self.queue_complete = False
		while 1:
			# Blocca finché c'è qualcosa da processare nella coda
			request = self.request_queue.get()
			# Se l'elemento della coda è None esce
			if request is None:
				break
			# Estrae dall'elemento della coda da processare
			n, sel = request

			# Avanza la progressbar
			self.work_complete = False
			self.amount_completed = 0
			self.idevent = gobject.timeout_add(200, self.mainapp.on_ProgressBar)

			# Seleziona il file da processare
			af = sel[0]
			it = sel[1]
			try:
				self.mainapp.FileTable.tvSelection.select_iter(it)
			except: pass

			# Prepara il messaggio per la status bar
			self.n = n
			if af.get_tag("title") != "Unknown title" and af.get_tag("artist") != "Unknown artist":
				self.msg = af.get_tag("artist") + " - " + af.get_tag("title")
			else:
				self.msg = af.get_filename()

			# Percorso di ingresso
			if af.get_uri()[:7] == "file://":
				input_path = af.get_uri()[7:]
			elif af.get_uri()[:7] == "cdda://":
				input_path = af.get_uri()[7:]
			else:
				input_path = af.get_uri()

			# Se deve solo copiare i file wav dopo il ripping da CD
			if not bool(int(self.prefs.get_option("rip-compressed"))) and self.sorgente=="cd":
				# Estrae le opzioni per la conversione
				format, save_path, output_file_name = self.Options(af, self.prefs)
				# Copia il file wav nella directory definita e nel formato definito
				shutil.copy2(af.get_filepath(), save_path + "/" + output_file_name + "." + format)
				# Playlist
				af_output = AudioFile("file://" + save_path + "/" + output_file_name + "." + format)
				af_output.set_tags_as_dict(af.get_tags_as_dict())
				if bool(int(self.prefs.get_option("playlist"))):
					if "/CD" in save_path:
						self.savepath = save_path[:save_path.index("/CD")]
					else:
						self.savepath = save_path
					self.playlistname = af_output.get_tag("artist") + " - " + af_output.get_tag("album")
					self.listsongs.append("#EXTINF:" + str(int(af_output.get_duration())) + "," + af_output.get_tag("artist") + " - " + af_output.get_tag("title") + "\n")
					self.listsongs.append(af_output.get_filename() + "\n")
				self.work_complete = True

			# Se usa gstreamer per la conversione
			elif not bool(int(self.prefs.get_option("use-external-encoder"))):
				print "INTERNAL ENCODER"
				# Estrae le opzioni per la conversione
				#print self.Options(af, self.prefs)
				format, mode, qual, bitrate, save_path, output_file_name, tagsv1, tagsv2 = self.Options(af, self.prefs)
				# Pipeline
				print "Pipeline: ", input_path, format, mode, qual, bitrate, save_path + "/" + output_file_name
				converter_pipe = Pipeline(input_path, format, mode, qual, bitrate, save_path + "/" + output_file_name)
				# Rimane nel ciclo finché la pipeline non è finita
				while 1:
					state, pending, timeout = converter_pipe.pipe.get_state()
					if pending == gst.STATE_NULL:
						print "Finito:", input_path
						self.work_complete = True
						gobject.source_remove(self.idevent)
						break
					else:
						position = converter_pipe.pipe.query_position(gst.FORMAT_TIME, None)[0]
						perc = float(position)/converter_pipe.duration
						if perc > 1:
							perc = 0
						time.sleep(0.1)
						self.amount_completed = perc

				# Scrive i tags
				af_output = AudioFile("file://" + save_path + "/" + output_file_name + "." + format)
				if tagsv1:
					af_output.set_tags_as_dict(af.get_tags_as_dict())
					af_output.set_tag("comment", "X Audio Copy")
					af_output.write_metadata()
				else:
					af_output.remove_metadata()
				if tagsv2:
					af_output.write_ID3v2()

				if bool(int(self.prefs.get_option("playlist"))):
					if "/CD" in save_path:
						self.savepath = save_path[:save_path.index("/CD")]
					else:
						self.savepath = save_path
					self.playlistname = af_output.get_tag("artist") + " - " + af_output.get_tag("album")
					self.listsongs.append("#EXTINF:" + str(int(af_output.get_duration())) + ", " + af_output.get_tag("artist") + " - " + af_output.get_tag("title") + "\n")
					if "/CD" in save_path:
						self.listsongs.append(save_path[save_path.index("/CD") + 1:] + "/" + af_output.get_filename() + "\n")
					else:
						self.listsongs.append(af_output.get_filename() + "\n")
				self.work_complete = True

			# Se usa un encoder esterno. Prima decodifica il file.
			elif bool(int(self.prefs.get_option("use-external-encoder"))) and self.Options(af, self.prefs):
				print "EXTERNAL ENCODER"
				# Estrae le opzioni per la conversione
				opt_string, input_path, output_path, tagsv1, tagsv2 = self.Options(af, self.prefs)

				if af.get_type() == "audio/x-wav":
					opt_string = opt_string.replace('"temporarypath"', '"' + input_path + '"')
					perc = 0.0
				else:
					# Directory temporanea
					tempdir = tempfile.mkdtemp()
					#Pipeline per decodificare in wav
					converter_pipe = Pipeline(input_path, "wav", None, None, None, tempdir + "/temp_file")

					# Rimane nel ciclo finché la pipeline non è finita
					while 1:
						state, pending, timeout = converter_pipe.pipe.get_state()
						if pending == gst.STATE_NULL:
							print "Decodifica finita"
							break
						else:
							position = converter_pipe.pipe.query_position(gst.FORMAT_TIME, None)[0]
							perc = float(position)/converter_pipe.duration/50
							if perc > 1:
								perc = 0
							time.sleep(0.1)
							self.amount_completed = perc
					# Passa il file decodificato all'encoder esterno
					opt_string = opt_string.replace('"temporarypath"', '"' + tempdir + '/temp_file.wav"')

				init_encoder_time = time.time()
				encoder_args = shlex.split(opt_string)
				encoder = Encoder(encoder_args)
				# Rimane nel ciclo finché il sub-processo non è finito
				while 1:
					if encoder.process.poll() == 0:
						print "Finito:", input_path
						self.work_complete = True
						gobject.source_remove(self.idevent)
						break
					else:
						if (time.time() - init_encoder_time > 1):
							if perc < 1:
								tag = TagFinder("file://" + output_path)
								encoding_done = tag.get_duration()
								perc = float(encoding_done)/af.get_duration()/2.1
								print "PERCENTUALE: ", perc
								if perc < 1:
									self.amount_completed = perc
								else:
									self.amount_completed = 1
							else:
								self.amount_completed = 1
						time.sleep(2)
				try:
					walk = os.walk(tempdir)
					for dirpath, subdir, filenames in walk:
						for f in filenames:
							os.remove(os.path.join(dirpath, f))
					os.rmdir(tempdir)
				except: pass

				# Scrive la playlist
				if bool(int(self.prefs.get_option("playlist"))):
					if "/CD" in output_path:
						self.savepath = os.path.split(output_path)[0][:os.path.split(output_path)[0].index("/CD")]
					else:
						self.savepath = os.path.split(output_path)[0]
					self.playlistname = af.get_tag("artist") + " - " + af.get_tag("album")
					self.listsongs.append("#EXTINF:" + str(int(af.get_duration())) + "," + af.get_tag("artist") + " - " + af.get_tag("title") + "\n")
					self.listsongs.append(output_path[len(self.savepath + "/"):] + "\n")
				
				self.work_complete = True
			else:
				gobject.source_remove(self.idevent)
				self.msg = "nothing. No external encoder. Please choise a valid encoder"

			# Cancella i file originali se previsto
			if bool(int(self.prefs.get_option("delete-original-files"))):
				if af.get_uri()[:7] == "file://":
					os.remove(af.get_filepath())

		self.queue_complete = True
		self.mainapp.on_ProgressBar()