© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu
Quick Links
Easy Studies

Transcoding of MPEG files to avi Using Java

Description:

This program is based the conversion of multimedia contents.This program takes a MPEG file as input and translates into avi file. The encoding quality on the JPEG encoder is 0.5.Transcodibg is the process of converting a file from one format to another or from one quality to another quality. We'll loop through the tracks and try to find a track that can be converted to the given format. While transcoding a MPEG file into avi file, the encoding quality is set to the default value. After the conversion of tracks, Convert a file name to a content type. The extension is parsed to determine the content type.Methods used for the conversion are setTrackFormats (), setEachTrackFormat (), setJPEGQuality ().

Transcoding of MPEG files to avi Using Java :

/* * NewJFrame1.java * * Created on March 23, 2009, 6:02 PM */ import javax.swing.*; import java.io.*; import javax.media.*; import java.util.*; /** * * @author Administrator */ public class NewJFrame1 extends javax.swing.JFrame { /** Creates new form NewJFrame1 */ public NewJFrame1() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // //GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(100,120,75)); jLabel1.setText("TransCoding"); jButton1.setText("Input"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Output"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Transcode"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); //jTextField1.setBounds(); jLabel2.setText("Input File"); jLabel3.setText("Output File"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1.setBackground(new java.awt.Color(0, 153, 153)); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(48, 48, 48) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(115, 115, 115) .addComponent(jButton3))) .addContainerGap(106, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButton2)) .addGap(31, 31, 31) .addComponent(jButton3) .addContainerGap(123, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); getContentPane().setBackground(new java.awt.Color(0, 153, 153)); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// //GEN-END:initComponents private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed JFileChooser chooser=new JFileChooser(); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { jTextField1.setText(chooser.getSelectedFile().getAbsolutePath()); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed JFileChooser chooser=new JFileChooser(); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { jTextField2.setText(chooser.getSelectedFile().getAbsolutePath()); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed String inputURL = null, outputURL = null; int mediaStart = -1, mediaEnd = -1; Vector audFmt = new Vector(), vidFmt = new Vector(); inputURL="file:\\"+jTextField1.getText(); outputURL="file:\\"+jTextField2.getText(); int j=0; vidFmt.addElement("mjpg"); Format fmts[] = new Format[audFmt.size() + vidFmt.size()]; Format fmt; Transcode transcode = new Transcode(); for (int i = 0; i < vidFmt.size(); i++) { if ((fmt =transcode.parseVideoFormat((String)vidFmt.elementAt(i))) == null) { } fmts[j++] = fmt; } MediaLocator iml, oml; if ((iml = createMediaLocator(inputURL)) == null) { System.err.println("Cannot build media locator from: " + inputURL); System.exit(0); } if ((oml = createMediaLocator(outputURL)) == null) { System.err.println("Cannot build media locator from: " + outputURL); System.exit(0); } if (!transcode.doIt(iml, oml, fmts, mediaStart, mediaEnd)) { System.err.println("Transcoding failed"); } }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame1().setVisible(true); } }); } static MediaLocator createMediaLocator(String url) { MediaLocator ml; if (url.indexOf(":") > 0 && (ml = new MediaLocator(url)) != null) return ml; if (url.startsWith(File.separator)) { if ((ml = new MediaLocator("file:" + url)) != null) return ml; } else { String file = "file:" + System.getProperty("user.dir") + File.separator + url; if ((ml = new MediaLocator(file)) != null) return ml; } return null; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables } /*Transcode*/ import java.awt.*; import java.util.Vector; import java.io.File; import javax.media.*; import javax.media.control.TrackControl; import javax.media.control.QualityControl; import javax.media.Format; import javax.media.format.*; import javax.media.datasink.*; import javax.media.protocol.*; import javax.media.protocol.DataSource; import java.io.IOException; import com.sun.media.format.WavAudioFormat; /** * A sample program to transcode an input source to an output location * with different data formats. */ public class Transcode implements ControllerListener, DataSinkListener { public boolean doIt(MediaLocator inML, MediaLocator outML, Format fmts[], int start, int end) { Processor p; try { System.err.println("- create processor for: " + inML); p = Manager.createProcessor(inML); } catch (Exception e) { System.err.println("Yikes! Cannot create a processor from the given url: " + e); return false; } p.addControllerListener(this); // Put the Processor into configured state. p.configure(); if (!waitForState(p, p.Configured)) { System.err.println("Failed to configure the processor."); return false; } setContentDescriptor(p, outML); if (!setTrackFormats(p, fmts)) return false; p.realize(); if (!waitForState(p, p.Realized)) { System.err.println("Failed to realize the processor."); return false; } // Set the JPEG quality to .5. setJPEGQuality(p, 0.5f); // Now, we'll need to create a DataSink. DataSink dsink; if ((dsink = createDataSink(p, outML)) == null) { System.err.println("Failed to create a DataSink for the given output MediaLocator: " + outML); return false; } dsink.addDataSinkListener(this); fileDone = false; // Set the start time if there's one set. if (start > 0) p.setMediaTime(new Time((double)start)); // Set the stop time if there's one set. if (end > 0) p.setStopTime(new Time((double)end)); System.err.println("start transcoding..."); // OK, we can now start the actual transcoding. try { p.start(); dsink.start(); } catch (IOException e) { System.err.println("IO error during transcoding"); return false; } // Wait for EndOfStream event. waitForFileDone(); // Cleanup. try { dsink.close(); } catch (Exception e) {} p.removeControllerListener(this); System.err.println("...done transcoding."); return true; } /** * Set the content descriptor based on the given output MediaLocator. */ void setContentDescriptor(Processor p, MediaLocator outML) { ContentDescriptor cd; if ((cd = fileExtToCD(outML.getRemainder())) != null) { System.err.println("- set content descriptor to: " + cd); if ((p.setContentDescriptor(cd)) == null) { p.setContentDescriptor(new ContentDescriptor(ContentDescriptor.RAW)); } } } /** * Set the target transcode format on the processor. */ boolean setTrackFormats(Processor p, Format fmts[]) { if (fmts.length == 0) return true; TrackControl tcs[]; if ((tcs = p.getTrackControls()) == null) { System.err.println("The Processor cannot transcode the tracks to the given formats"); return false; } for (int i = 0; i < fmts.length; i++) { System.err.println("- set track format to: " + fmts[i]); if (!setEachTrackFormat(p, tcs, fmts[i])) { System.err.println("Cannot transcode any track to: " + fmts[i]); return false; } } return true; } /** * We'll loop through the tracks and try to find a track * that can be converted to the given format. */ boolean setEachTrackFormat(Processor p, TrackControl tcs[], Format fmt) { Format supported[]; Format f; for (int i = 0; i < tcs.length; i++) { supported = tcs[i].getSupportedFormats(); if (supported == null) continue; for (int j = 0; j < supported.length; j++) { if (fmt.matches(supported[j]) && (f = fmt.intersects(supported[j])) != null && tcs[i].setFormat(f) != null) { // Success. return true; } } } return false; } /** * Setting the encoding quality to the specified value on the JPEG encoder. * 0.5 is a good default. */ void setJPEGQuality(Player p, float val) { Control cs[] = p.getControls(); QualityControl qc = null; VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG); // Loop through the controls to find the Quality control for // the JPEG encoder. for (int i = 0; i < cs.length; i++) { if (cs[i] instanceof QualityControl && cs[i] instanceof Owned) { Object owner = ((Owned)cs[i]).getOwner(); if (owner instanceof Codec) { Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null); for (int j = 0; j < fmts.length; j++) { if (fmts[j].matches(jpegFmt)) { qc = (QualityControl)cs[i]; qc.setQuality(val); System.err.println("- Set quality to " + val + " on " + qc); break; } } } if (qc != null) break; } } } /** * Create the DataSink. */ DataSink createDataSink(Processor p, MediaLocator outML) { DataSource ds; if ((ds = p.getDataOutput()) == null) { System.err.println("Something is really wrong: the processor does not have an output DataSource"); return null; } DataSink dsink; try { System.err.println("- create DataSink for: " + outML); dsink = Manager.createDataSink(ds, outML); dsink.open(); } catch (Exception e) { System.err.println("Cannot create the DataSink: " + e); return null; } return dsink; } Object waitSync = new Object(); boolean stateTransitionOK = true; /** * Block until the processor has transitioned to the given state. * Return false if the transition failed. */ boolean waitForState(Processor p, int state) { synchronized (waitSync) { try { while (p.getState() < state && stateTransitionOK) waitSync.wait(); } catch (Exception e) {} } return stateTransitionOK; } /** * Controller Listener. */ public void controllerUpdate(ControllerEvent evt) { if (evt instanceof ConfigureCompleteEvent || evt instanceof RealizeCompleteEvent || evt instanceof PrefetchCompleteEvent) { synchronized (waitSync) { stateTransitionOK = true; waitSync.notifyAll(); } } else if (evt instanceof ResourceUnavailableEvent) { synchronized (waitSync) { stateTransitionOK = false; waitSync.notifyAll(); } } else if (evt instanceof EndOfMediaEvent) { evt.getSourceController().close(); } else if (evt instanceof MediaTimeSetEvent) { System.err.println("- mediaTime set: " + ((MediaTimeSetEvent)evt).getMediaTime().getSeconds()); } else if (evt instanceof StopAtTimeEvent) { System.err.println("- stop at time: " + ((StopAtTimeEvent)evt).getMediaTime().getSeconds()); evt.getSourceController().close(); } } Object waitFileSync = new Object(); boolean fileDone = false; boolean fileSuccess = true; /** * Block until file writing is done. */ boolean waitForFileDone() { System.err.print(" "); synchronized (waitFileSync) { try { while (!fileDone) { waitFileSync.wait(1000); System.err.print("."); } } catch (Exception e) {} } System.err.println(""); return fileSuccess; } /** * Event handler for the file writer. */ public void dataSinkUpdate(DataSinkEvent evt) { if (evt instanceof EndOfStreamEvent) { synchronized (waitFileSync) { fileDone = true; waitFileSync.notifyAll(); } } else if (evt instanceof DataSinkErrorEvent) { synchronized (waitFileSync) { fileDone = true; fileSuccess = false; waitFileSync.notifyAll(); } } } /** * Convert a file name to a content type. The extension is parsed * to determine the content type. */ ContentDescriptor fileExtToCD(String name) { String ext; int p; // Extract the file extension. if ((p = name.lastIndexOf('.')) < 0) return null; ext = (name.substring(p + 1)).toLowerCase(); String type; // Use the MimeManager to get the mime type from the file extension. if ( ext.equals("mp3")) { type = FileTypeDescriptor.MPEG_AUDIO; } else { if ((type = com.sun.media.MimeManager.getMimeType(ext)) == null) return null; type = ContentDescriptor.mimeTypeToPackageName(type); } return new FileTypeDescriptor(type); } /** * Main program */ public static void main(String [] args) { System.exit(0); } /** * Create a media locator from the given string. */ static MediaLocator createMediaLocator(String url) { MediaLocator ml; if (url.indexOf(":") > 0 && (ml = new MediaLocator(url)) != null) return ml; if (url.startsWith(File.separator)) { if ((ml = new MediaLocator("file:" + url)) != null) return ml; } else { String file = "file:" + System.getProperty("user.dir") + File.separator + url; if ((ml = new MediaLocator(file)) != null) return ml; } return null; } /** * Parse the video format specifier and generate an VideoFormat. * A valid video format specifier is of the form: * [encoding]:[widthXheight] */ static Format parseVideoFormat(String fmtStr) { String encodeStr = null, sizeStr = null; // Parser the media locator to extract the requested format. if (fmtStr != null && fmtStr.length() > 0) { while (fmtStr.length() > 1 && fmtStr.charAt(0) == ':') fmtStr = fmtStr.substring(1); // Now see if there's a encode rate specified. int off = fmtStr.indexOf(':'); if (off == -1) { if (!fmtStr.equals("")) encodeStr = fmtStr; } else { encodeStr = fmtStr.substring(0, off); sizeStr = fmtStr.substring(off + 1); } } if (encodeStr == null || encodeStr.equals("")) prUsage(); if (sizeStr == null) return new VideoFormat(encodeStr); int width = 320, height = 240; int off = sizeStr.indexOf('X'); if (off == -1) off = sizeStr.indexOf('x'); if (off == -1) { System.err.println("Video dimension is not correctly specified: " + sizeStr); prUsage(); } else { String widthStr = sizeStr.substring(0, off); String heightStr = sizeStr.substring(off + 1); try { Integer integer = Integer.valueOf(widthStr); if (integer != null) width = integer.intValue(); integer = Integer.valueOf(heightStr); if (integer != null) height = integer.intValue(); } catch (Throwable t) { prUsage(); } return new VideoFormat(encodeStr, new Dimension(width, height), VideoFormat.NOT_SPECIFIED, // maxDataLen null, // data class VideoFormat.NOT_SPECIFIED // FrameRate ); } return null; } static void prUsage() { System.err.println("Usage: java Transcode -o -a

Sample ScreenShot:

 
SLogix Student Projects


⇓Student Projects⇓
⇑Student Projects⇑
bottom