Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.bump.util.mediainfo;
- import com.mpatric.mp3agic.*;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import ru.bump.core.util.ArgumentAssertUtil;
- import ru.bump.util.process.ProcessRunException;
- import ru.bump.util.process.ProcessRunner;
- import ru.bump.util.string.StringUtil;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.util.Arrays;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.List;
- import java.util.concurrent.TimeoutException;
- public final class MediaInfoUtil {
- private static final String UTILITY_NAME = "mediainfo";
- private static final String TEMPLATE = "--Inform={0};";
- private static final String TEMPLATE_GENERAL = StringUtil.getFormatedString(TEMPLATE, "General");
- private static final String TEMPLATE_VIDEO = StringUtil.getFormatedString(TEMPLATE, "Video");
- private static final String TEMPLATE_AUDIO = StringUtil.getFormatedString(TEMPLATE, "Audio");
- private static final String TEMPLATE_IMAGE = StringUtil.getFormatedString(TEMPLATE, "Image");
- private static final String FORMAT = "%Format%";
- private static final String FORMAT_PROFILE = "%Format_Profile%";
- private static final String FORMAT_PARAMETER = TEMPLATE_GENERAL.concat(FORMAT);
- private static final String FORMAT_PROFILE_PARAMETER = TEMPLATE_GENERAL.concat(FORMAT_PROFILE);
- private static final String DURATION_PARAMETER = TEMPLATE_GENERAL.concat("%Duration%");
- private static final String ARTIST_PARAMETER = TEMPLATE_GENERAL.concat("%Performer%");
- private static final String TRACK_NAME_PARAMETER = TEMPLATE_GENERAL.concat("%Track%");
- private static final String FRAME_RATE_PARAMETER = TEMPLATE_VIDEO.concat("%FrameRate%");
- private static final String HEIGHT_PARAMETER = TEMPLATE_VIDEO.concat("%Height%");
- private static final String WIDTH_PARAMETER = TEMPLATE_VIDEO.concat("%Width%");
- private static final String VIDEO_FORMAT_PARAMETER = TEMPLATE_VIDEO.concat(FORMAT);
- private static final String VIDEO_BIT_RATE_PARAMETER = TEMPLATE_VIDEO.concat("%BitRate%");
- private static final String VIDEO_CODEC_ID_PARAMETER = TEMPLATE_VIDEO.concat("%CodecID%");
- private static final String AUDIO_CHANNELS_PARAMETER = TEMPLATE_AUDIO.concat("%Channel(s)%");
- private static final String AUDIO_CODEC_ID_PARAMETER = TEMPLATE_AUDIO.concat("%CodecID%");
- private static final String IMAGE_HEIGHT_PARAMETER = TEMPLATE_IMAGE.concat("%Height%");
- private static final String IMAGE_WIDTH_PARAMETER = TEMPLATE_IMAGE.concat("%Width%");
- private static final Logger LOG = LoggerFactory.getLogger(MediaInfoUtil.class);
- private static final byte TEXT_ENCODING_WINDOWS_1251 = 0;
- private static final byte TEXT_ENCODING_UTF_16 = 1;
- private static final byte TEXT_ENCODING_UTF_16BE = 2;
- private static final byte TEXT_ENCODING_UTF_8 = 3;
- private static final String[] ENCODING_CHARSETS = {"windows-1251", "UTF-16LE", "UTF-16BE", "UTF-8"};
- // -------------------------------------------------------
- // - LOGIC -
- // -------------------------------------------------------
- private MediaInfoUtil() {
- }
- private static List<String> getMediaInfo(String parameter, String filePath) {
- try {
- return new ProcessRunner(UTILITY_NAME)
- .addParameter(parameter)
- .addParameter(filePath)
- .run();
- } catch (IOException e) {
- LOG.error("Error get media info. I/O problem. Parameter = `{}`, filePath = `{}`.", e, parameter, filePath);
- } catch (InterruptedException e) {
- LOG.error("Error get media info. Process is interrupted. Parameter = `{}`, filePath = `{}`.", e,
- parameter, filePath);
- } catch (ProcessRunException e) {
- LOG.error("Error get media info. Parameter = `{}`, filePath = `{}`.", e, parameter, filePath);
- } catch (TimeoutException e) {
- LOG.error("Error get media info. Timeout is expired. Parameter = `{}`, filePath = `{}`.", e,
- parameter, filePath);
- }
- return Collections.EMPTY_LIST;
- }
- private static String getMediaInfoOneLine(String parameter, String filePath) {
- List<String> outputLines = getMediaInfo(parameter, filePath);
- if (outputLines.size() > 0) {
- String line = outputLines.get(0);
- LOG.info("MediaInfoOneLine: `{}`, parameter: `{}`, filePath : `{}`", line, parameter, filePath);
- return line;
- } else {
- LOG.warn("MediaInfoOneLine is empty");
- }
- return "";
- }
- public static MediaInfoFormat getMediaInfoFormat(String filePath) {
- List<String> allMediaInfo = getMediaInfo("", filePath);
- HashMap<String, HashMap<String, String>> sections = new HashMap<String, HashMap<String, String>>();
- String currentSection = "";
- HashMap<String, String> currentSectionElements = new HashMap<String, String>();
- for (String mediaInfo : allMediaInfo) {
- if (mediaInfo.equals("General") || mediaInfo.equals("Video")
- || mediaInfo.equals("Audio") || mediaInfo.equals("Text")
- || mediaInfo.equals("Chapter") || mediaInfo.equals("Image")
- || mediaInfo.equals("Menu")) {
- currentSection = mediaInfo;
- continue;
- }
- if (mediaInfo.equals("")) {
- if (!currentSectionElements.isEmpty()) {
- sections.put(currentSection, currentSectionElements);
- currentSectionElements = new HashMap<String, String>();
- }
- continue;
- }
- mediaInfo = mediaInfo.trim().replaceAll(" +", " ");
- String[] splittedMediaInfo = mediaInfo.split(":", 2);
- if (splittedMediaInfo.length < 2) {
- continue;
- }
- currentSectionElements.put(splittedMediaInfo[0].trim(), splittedMediaInfo[1].trim());
- }
- HashMap<String, String> generalSection = sections.get("General");
- if (generalSection == null) {
- throw new RuntimeException("Can't find general section");
- }
- String generalFormat = generalSection.get("Format");
- String generalFormatProfile = generalSection.get("Format profile");
- if (generalFormat == null) {
- generalFormat = "";
- }
- if (generalFormatProfile == null) {
- generalFormatProfile = "";
- }
- MediaInfoFormat mediaInfoFormat = MediaInfoFormat.getFormat(generalFormat, generalFormatProfile);
- //this fix for WMV format, if video stream excepted
- if (mediaInfoFormat.equals(MediaInfoFormat.WINDOWS_MEDIA)) {
- HashMap<String, String> videoSection = sections.get("Video");
- String videoFormat = "";
- if (videoSection != null) {
- if (videoSection.get("Format") != null) {
- videoFormat = videoSection.get("Format");
- }
- }
- if ("".equalsIgnoreCase(videoFormat.trim())) {
- return MediaInfoFormat.WINDOWS_MEDIA_AUDIO;
- }
- }
- return mediaInfoFormat;
- }
- public static long getMediaInfoDuration(String filePath) {
- return Long.valueOf(getMediaInfoOneLine(DURATION_PARAMETER, filePath));
- }
- public static String getMediaInfoArtist(String filePath) {
- return getMediaInfoOneLine(ARTIST_PARAMETER, filePath);
- }
- public static String getMediaInfoTrackName(String filePath) {
- return getMediaInfoOneLine(TRACK_NAME_PARAMETER, filePath);
- }
- public static String getFrameRate(String filePath) {
- return getMediaInfoOneLine(FRAME_RATE_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getVideoHeight(String filePath) {
- return getMediaInfoOneLine(HEIGHT_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getImageHeight(String filePath) {
- return getMediaInfoOneLine(IMAGE_HEIGHT_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getImageWidth(String filePath) {
- return getMediaInfoOneLine(IMAGE_WIDTH_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getVideoWidth(String filePath) {
- return getMediaInfoOneLine(WIDTH_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getImageFormat(String filePath) {
- return getMediaInfoOneLine(FORMAT_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getAudioChannels(String filePath) {
- return getMediaInfoOneLine(AUDIO_CHANNELS_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getVideoBitRate(String filePath) {
- return getMediaInfoOneLine(VIDEO_BIT_RATE_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getVideoCodecId(String filePath) {
- return getMediaInfoOneLine(VIDEO_CODEC_ID_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static String getAudioCodecId(String filePath) {
- return getMediaInfoOneLine(AUDIO_CODEC_ID_PARAMETER, filePath).replaceAll("\n", "").replaceAll("\r", "");
- }
- public static boolean isImage(MediaInfoFormat mediaInfoFormat) {
- ArgumentAssertUtil.nullCheck("mediaInfoFormat", mediaInfoFormat);
- switch (mediaInfoFormat) {
- case BITMAP:
- case DIB:
- case GIF:
- case ICO:
- case JNG:
- case JPEG:
- case JPEG2000:
- case LZ77:
- case MNG:
- case RIFF:
- case PNG:
- case RLE:
- case TIFF:
- return true;
- default:
- return false;
- }
- }
- public static String getArtist(String filePath) {
- String artist = getId3tag(filePath, "TPE1");
- if (artist == null) {
- return getMediaInfoArtist(filePath);
- } else {
- return artist;
- }
- }
- public static String getTrackName(String filePath) {
- String trackName = getId3tag(filePath, "TIT2");
- if (trackName == null) {
- return getMediaInfoTrackName(filePath);
- } else {
- return trackName;
- }
- }
- public static String getId3tag (String filePath, String tagName) {
- String tagValue = null;
- try {
- Mp3File mp3file = new Mp3File(filePath);
- if (mp3file.hasId3v2Tag()) {
- ID3v2 id3v2Tag = mp3file.getId3v2Tag();
- byte[] data = id3v2Tag.getFrameSets().get(tagName).getFrames().get(0).getData();
- tagValue = getStringFromTagData(Arrays.copyOfRange(data, 1, data.length), data[0]);
- }
- } catch (Exception e) {
- LOG.warn("Error reading mp3 tags, trying other methods, {}, file: {}", e, filePath);
- }
- return tagValue;
- }
- private static String getStringFromTagData(byte[] value, byte textEncoding) throws UnsupportedEncodingException {
- byte[][] terminators = {
- {0},
- {0, 0},
- {0, 0},
- {0}
- };
- int leadingCharsToRemove = 0;
- // if encoding type 1 and big endian BOM is present, switch to big endian
- if ((textEncoding == TEXT_ENCODING_UTF_16) &&
- (textEncodingForBytesFromBOM(value) == TEXT_ENCODING_UTF_16BE)) {
- textEncoding = TEXT_ENCODING_UTF_16BE;
- }
- if (value.length >= 2 && ((value[0] == (byte) 0xfe && value[1] == (byte) 0xff) || (value[0] == (byte) 0xff && value[1] == (byte) 0xfe))) {
- leadingCharsToRemove = 2;
- } else if (value.length >= 3 && (value[0] == (byte) 0xef && value[1] == (byte) 0xbb && value[2] == (byte) 0xbf)) {
- leadingCharsToRemove = 3;
- }
- int trailingCharsToRemove = 0;
- byte[] terminator = terminators[textEncoding];
- if (value.length - leadingCharsToRemove >= terminator.length) {
- boolean haveTerminator = true;
- for (int i = 0; i < terminator.length; i++) {
- if (value[value.length - terminator.length + i] != terminator[i]) {
- haveTerminator = false;
- break;
- }
- }
- if (haveTerminator) {
- trailingCharsToRemove = terminator.length;
- }
- }
- if (leadingCharsToRemove + trailingCharsToRemove > 0) {
- int newLength = value.length - leadingCharsToRemove - trailingCharsToRemove;
- byte[] newValue = new byte[newLength];
- if (newLength > 0) {
- System.arraycopy(value, leadingCharsToRemove, newValue, 0, newValue.length);
- }
- value = newValue;
- }
- return new String(value, ENCODING_CHARSETS[textEncoding]);
- }
- private static byte textEncodingForBytesFromBOM(byte[] value) {
- if (value.length >= 2 && value[0] == (byte) 0xff && value[1] == (byte) 0xfe) {
- return TEXT_ENCODING_UTF_16;
- } else if (value.length >= 2 && value[0] == (byte) 0xfe && value[1] == (byte) 0xff) {
- return TEXT_ENCODING_UTF_16BE;
- } else if (value.length >= 3 && (value[0] == (byte) 0xef && value[1] == (byte) 0xbb && value[2] == (byte) 0xbf)) {
- return TEXT_ENCODING_UTF_8;
- } else {
- return TEXT_ENCODING_WINDOWS_1251;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement