All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.day.cq.dam.handler.standard.mp3.Mp3Handler Maven / Gradle / Ivy

/*
 * Copyright 1997-2008 Day Management AG
 * Barfuesserplatz 6, 4001 Basel, Switzerland
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Day Management AG, ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Day.
 */
package com.day.cq.dam.handler.standard.mp3;

import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.Rendition;
import com.day.cq.dam.api.metadata.ExtractedMetadata;
import com.day.cq.dam.commons.handler.AbstractAssetHandler;
import com.day.image.Font;
import com.day.image.Layer;
import de.vdheide.mp3.MP3File;
import org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * The Mp3Handler class ...
 */
@Component(inherit = true, metatype = false)
@Service
public class Mp3Handler extends AbstractAssetHandler {

    /**
     * the default logger
     */
    private static final Logger log = LoggerFactory.getLogger(Mp3Handler.class);

    /**
     * Mime type
     */
    public static final String CONTENT_MIMETYPE = "audio/mpeg";

    /**
     * Music icon margin
     */
    private static final int MARGIN = 10;

    public ExtractedMetadata extractMetadata(final Asset asset) {

        final ExtractedMetadata metadata = new ExtractedMetadata();
        log.debug("extractMetadata: importing asset [{}]...", asset.getPath());

        // extract metadata
        final InputStream is = asset.getOriginal().getStream();
        File tmpFile = null;

        try {
            // helliker only handles files, so spool to tmp file first
            FileOutputStream out = null;
            try {
                tmpFile = File.createTempFile("__example", ".mp3");
                out = new FileOutputStream(tmpFile);
                IOUtils.copy(is, out);
            } finally {
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(is);
            }

            MP3File mp3File = null;
            try {
				mp3File = new MP3File(tmpFile.getAbsolutePath());

				// set properties fed from mp3 id3 header
				addNonNullMetadataValue(metadata, "Album", mp3File.getAlbum()
						.getTextContent());
				addNonNullMetadataValue(metadata, "Artist", mp3File.getArtist()
						.getTextContent());
				addNonNullMetadataValue(metadata, "BitRate",
						String.valueOf(mp3File.getBitrate()));
				addNonNullMetadataValue(metadata, "Comment", mp3File
						.getComments().getTextContent());
				addNonNullMetadataValue(metadata, "Composer", mp3File
						.getComposer().getTextContent());
				addNonNullMetadataValue(metadata, "CopyrightInfo", mp3File
						.getCopyrightText().getTextContent());
				addNonNullMetadataValue(metadata, "EncodedBy", mp3File
						.getEncodedBy().getTextContent());
				addNonNullMetadataValue(metadata, "Genre", mp3File.getGenre()
						.getTextContent());
				addNonNullMetadataValue(metadata, "OriginalArtist", mp3File
						.getOriginalArtist().getTextContent());
				addNonNullMetadataValue(metadata, "PlayingTime", mp3File
						.getTime().getTextContent());
				addNonNullMetadataValue(metadata, "Title", mp3File.getTitle()
						.getTextContent());
				addNonNullMetadataValue(metadata, "TrackNumber", mp3File
						.getTrack().getTextContent());
				addNonNullMetadataValue(metadata, "UserDefinedURL", mp3File
						.getUserDefinedURL().getTextContent());
				addNonNullMetadataValue(metadata, "Year", mp3File.getYear()
						.getTextContent());
				addNonNullMetadataValue(metadata, "Lyricist", mp3File
						.getLyricist().getTextContent());
				addNonNullMetadataValue(metadata, "MediaType", mp3File
						.getMediaType().getTextContent());
				addNonNullMetadataValue(metadata, "HasCopyRight",
						String.valueOf(mp3File.getCopyright()));
				addNonNullMetadataValue(metadata, "SamplerRate",
						String.valueOf(mp3File.getSamplerate()));
				addNonNullMetadataValue(metadata, "Length",
						String.valueOf(mp3File.getLength()));
				addNonNullMetadataValue(metadata, "MPEG Level",
						String.valueOf(mp3File.getMPEGLevel()));
				addNonNullMetadataValue(metadata, "Layer",
						String.valueOf(mp3File.getLayer()));
				addNonNullMetadataValue(metadata, "Mode",
						String.valueOf(mp3File.getMode()));
				addNonNullMetadataValue(metadata, "Padding",
						String.valueOf(mp3File.getPadding()));
				addNonNullMetadataValue(metadata, "Original",
						String.valueOf(mp3File.getOriginal()));
				
				// mp3 pic
				// get Thumbnail
				byte[] picture = mp3File.getPicture().getBinaryContent();
				if (picture != null) {
					metadata.setProperty("picture", picture);
				}
			} finally {
				if (mp3File != null) {
					mp3File.delete();
				}
			}
            } catch (Exception e) {
            metadata.cleanup();
            log.error("extractMetadata: unable to read MP3 metadata for asset [{}]: ", asset.getPath(), e);
        } finally {
            if (tmpFile != null) {
                tmpFile.delete();
            }
        }

        //Get XMP
        execGenericProcessor(asset.getOriginal().getStream(), metadata);
        setMimetype(metadata, asset);
        return metadata;
    }
    
	private void addNonNullMetadataValue(final ExtractedMetadata metadata,
			final String metaDatakey, final String metaDataValue) {
		if (metaDataValue != null) {
			metadata.setMetaDataProperty(metaDatakey, metaDataValue);
		}
	}

    public BufferedImage getImage(final Rendition rendition) throws IOException {
        final ExtractedMetadata metadata = extractMetadata(rendition.getAsset());
        final InputStream is = rendition.getStream();
        File tmpFile = null;

        try {
            // helliker only handles files, so spool to tmp file first
            FileOutputStream out = null;
            try {
                tmpFile = File.createTempFile("__example", ".mp3");
                out = new FileOutputStream(tmpFile);
                IOUtils.copy(is, out);
            } finally {
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(is);
            }

            MP3File mp3File = null;
            try {
                mp3File = new MP3File(tmpFile.getAbsolutePath());

                // get Thumbnail
                byte[] picture = mp3File.getPicture().getBinaryContent();
                if (picture != null) {
                    String title = (String) metadata.getMetaDataProperties().get("Title");
                    Layer music = null;
                    InputStream musicin = null;
                    Layer layer;
                    try {
                        // mp3 pic
                        layer = new Layer(new ByteArrayInputStream(picture));
                        int width = layer.getWidth();
                        int height = layer.getHeight();

                        int newWidth, newHeight;
                        if (height > width) {
                            newHeight = 270;          // TODO: why?
                            newWidth = (width * 270 / height);
                        } else {
                            newWidth = 270;
                            newHeight = (height * 270 / width);
                        }

                        layer.resize(newWidth, newHeight);

                        // music icon
                        musicin = Mp3Handler.class.getClassLoader().getResourceAsStream(
                                "com/day/cq/dam/media/handler/mp3/document_music.png");
                        music = new Layer(musicin);
                        music.setX(MARGIN);
                        music.setY(MARGIN);
                        layer.merge(music);

                        // draw title
                        title = (title != null && !"".equals(title)) ? title : rendition.getName();
                        Font font = new Font("Tahoma", 10, Font.BOLD);
                        // black
                        layer.setPaint(Color.black);
                        layer.drawText(61, 11, layer.getWidth() - 79, 0, title, font, Font.ALIGN_LEFT, 0, 0);
                        // white
                        layer.setPaint(Color.white);
                        layer.drawText(60, 10, layer.getWidth() - 80, 0, title, font, Font.ALIGN_LEFT, 0, 0);

                        return layer.getImage();
                    } catch (IOException e) {
                        log.error("getImage: error while getting image for [{}]: ", rendition.getPath(), e);
                    } finally {
                        if (music != null) {
                            music.dispose();
                        }
                        IOUtils.closeQuietly(musicin);
                    }
                }
            } finally {
                if (mp3File != null) {
                    mp3File.delete();
                }
            }
        } catch (Exception e) {
            log.error("getImage: unable to create thumbnail from MP3 [{}]: ", rendition.getPath(), e);
        } finally {
            if (tmpFile != null) {
                tmpFile.delete();
            }
        }
        return null;
    }

    public String[] getMimeTypes() {
        return new String[]{CONTENT_MIMETYPE};
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy