PICARD-1809: Load based on extensions, fallback to guessing if it fails

This commit is contained in:
Gabriel Ferreira
2020-04-30 11:41:21 -03:00
committed by Philipp Wolfer
parent 4138db5430
commit 1e07495c26
2 changed files with 18 additions and 8 deletions

View File

@@ -165,7 +165,16 @@ class File(QtCore.QObject, Item):
if self.tagger.stopping:
log.debug("File not loaded because %s is stopping: %r", PICARD_APP_NAME, self.filename)
return None
return self._load(filename)
try:
# Try loading based on extension first
return self._load(filename)
except Exception:
from picard.formats import guess_format
# If it fails, force format guessing and try loading again
file_format = guess_format(filename)
if not file_format and type(file_format) == type(self):
raise
return file_format._load(filename)
def _load(self, filename):
"""Load metadata from the file."""

View File

@@ -79,15 +79,16 @@ def guess_format(filename, options=_formats):
def open_(filename):
"""Open the specified file and return a File instance with the appropriate format handler, or None."""
try:
# First try to guess the format on the basis of file headers
audio_file = guess_format(filename)
if not audio_file:
i = filename.rfind(".")
if i < 0:
return None
# Use extension based opening as default
i = filename.rfind(".")
if i >= 0:
ext = filename[i+1:].lower()
# Switch to extension based opening if guess_format fails
audio_file = _extensions[ext](filename)
else:
# If there is no extension, try to guess the format based on file headers
audio_file = guess_format(filename)
if not audio_file:
return None
return audio_file
except KeyError:
# None is returned if both the methods fail