<?php
/*
 * $RCSfile: FfmpegToolkitHelper.class,v $
 *
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2005 Bharat Mediratta
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA  02110-1301, USA.
 */
/**
 * @version $Revision: 1.21 $ $Date: 2005/08/23 03:49:42 $
 * @package Ffmpeg
 * @author Bharat Mediratta <bharat@menalto.com>
 */

/**
 * A helper class for the FfmpegToolkit class
 *
 * @package Ffmpeg
 * @subpackage Classes
 */
class FfmpegToolkitHelper {

    /**
     * Figure out what operations and properties are supported by the
     * FfmpegToolkit and return them.
     *
     * @return object GalleryStatus a status code
     *         array('operations' => ...
     *               'properties' => ...)
     * @static
     */
    function getOperationsAndProperties() {
	global $gallery;

	list ($ret, $ffmpegPath) = GalleryCoreApi::getPluginParameter('module', 'ffmpeg', 'path');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	if (empty($ffmpegPath)) {
	    return array(GalleryStatus::error(ERROR_MISSING_VALUE,
					      __FILE__, __LINE__),
			 null);
	}

	list ($ret, $tests, $mimeTypes, $supportsOffset) =
	    FfmpegToolkitHelper::testBinary($ffmpegPath);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	/*
	 * -------------------- Operations --------------------
	 */

	/* extract */
	$operations['convert-to-image/jpeg']['params'] = array();
	$operations['convert-to-image/jpeg']['description'] = $gallery->i18n('Convert to a JPEG');
	$operations['convert-to-image/jpeg']['mimeTypes'] = $mimeTypes;
	$operations['convert-to-image/jpeg']['outputMimeType'] = 'image/jpeg';

	if ($supportsOffset) {
	    $operations['select-offset'] = array(
		'params' => array(array('type' => 'float',
					'description' => $gallery->i18n('offset in seconds'))),
		'description' => $gallery->i18n('Select time offset in movie file'),
		'mimeTypes' => $mimeTypes,
		'outputMimeType' => null);
	}

	/*
	 * -------------------- Properties --------------------
	 */

	/* Dimensions */
	$properties['dimensions']['type'] = 'int,int';
	$properties['dimensions']['description'] =
	    $gallery->i18n('Get the width and height of the movie');
	$properties['dimensions']['mimeTypes'] = $mimeTypes;

	$properties['dimensions-and-duration']['type'] = 'int,int,float';
	$properties['dimensions-and-duration']['description'] =
	    $gallery->i18n('Get the width, height and duration of the movie');
	$properties['dimensions-and-duration']['mimeTypes'] = $mimeTypes;

	return array(GalleryStatus::success(), array('operations' => $operations,
						     'properties' => $properties));
    }

    /**
     * Test if the given path has a working Ffmpeg binary.
     *
     * This is done by calling the binary with the -formats flag and
     * making sure it runs properly.
     *
     * @param string path to the Ffmpeg we are testing
     * @return array object GalleryStatus general status of tests
     *	       array of array ('name' => string: the name of the binary,
     *		               'success' => boolean: test successfull?
     *		               'results' => string: the ffmpeg output
     *	                )
     *         array hash map of mime types
     *         boolean true if ffmpeg supports -ss time_offset
     *
     * @static
     */
    function testBinary($ffmpegPath) {
	global $gallery;
	$platform = $gallery->getPlatform();

	/*
	 * If the path is not restricted by open_basedir, then verify that it's
	 * legal.  Else just hope that it's valid and use it.
	 */
	if (!$platform->isRestrictedByOpenBaseDir($ffmpegPath)) {
	    if (!$platform->file_exists($ffmpegPath) || !$platform->is_file($ffmpegPath)) {
		return array(GalleryStatus::error(ERROR_BAD_PATH, __FILE__, __LINE__),
			     null, null, null);
	    }
	}

	/* We only care about video for now */
	$relevantTypes['mpeg'] = 'mpeg';
	$relevantTypes['asf'] = 'asf';
	$relevantTypes['avi'] = 'avi';
	$relevantTypes['mov'] = 'mov';
	$relevantTypes['wmv1'] = 'wmv';
	list ($ignored, $results) = $platform->exec(array(array($ffmpegPath, '-formats')));
	$mimeTypes = array();

	$success = false;
	$i = 0;
	while ($i < sizeof($results)) {
	    $resultLine = $results[$i++];
	    /*
	     * ffmpeg 0.4.6 says:
	     * File formats:
	     *   Decoding: mpeg mpegts pgm pgmyuv ppm .Y.U.V pgmpipe pgmyuvpipe
	     * ppmpipe mp3 ac3 m4v mpegvideo mjpeg s16le s16be u16le u16be s8 u8 mulaw alaw
	     * rawvideo rm asf avi wav swf au mov jpeg dv ffm video_grab_device
	     * audio_device rtsp redir sdp rtp
	     * [multiple lines]
	     * Codecs:
	     * ....
	     *
	     * ffmpeg 0.4.7 says:
	     * Input audio/video file formats: mpeg mpegts image ...
	     * [all on one line]
	     *
	     * ffmpeg 0.4.8 says:
	     * File formats:
	     *   E 3gp
	     *  D  4xm
	     *  D  RoQ
	     *  DE ac3
	     *  DE ala
	     *  DE asf
	     *  E asf
	     * ...
	     * Image formats:
	     *  D  pnm
	     *   E pbm
	     *   E pgm
	     * ...
	     * Codecs:
	     *  D V    4xm
	     *  D V D  8bps
	     *   EA    ac3
	     *  DEA    adpcm_4xm
	     */
	    if (preg_match('|Input audio/video file formats: (.*)$|', $resultLine, $regs)) {
		foreach (explode(' ', $regs[1]) as $type) {
		    if (isset($relevantTypes[$type])) {
			list ($ret, $mime) =
			    GalleryCoreApi::convertExtensionToMime($relevantTypes[$type]);
			if ($ret->isError()) {
			    return array($ret->wrap(__FILE__, __LINE__), null, null, null);
			}
			$mimeTypes[$mime] = 1;
		    }
		}
		$success = true;
	    } else if (preg_match('/  Decod(?:ing|ers): (.*)$/', $resultLine, $regs)) {
		do {
		    foreach (explode(' ', $regs[1]) as $type) {
			if (isset($relevantTypes[$type])) {
			    list ($ret, $mime) = GalleryCoreApi::convertExtensionToMime(
				$relevantTypes[$type]);
			    if ($ret->isError()) {
				return array($ret->wrap(__FILE__, __LINE__), null, null, null);
			    }
			    $mimeTypes[$mime] = 1;
			}
		    }
		    $resultLine = $results[$i++];
		} while ($i < sizeof($results) && !preg_match('|Codecs:|', $resultLine));
		$success = true;
	    } else if (preg_match('/(File formats|Codecs):/', $resultLine, $regs)) {
		$resultLine = $results[$i++];
		if (preg_match('/^  \w+: /', $resultLine)) {
		    /* We have found 0.4.6 format */
		    continue;
		}
		do {
		    list($capabilities, $types) =
			preg_split('/\s+/', $resultLine, -1, PREG_SPLIT_NO_EMPTY);
		    foreach (explode(',', $types) as $type) {
			if (isset($relevantTypes[$type])) {
			    if (preg_match('|D|', $capabilities)) {
				list ($ret, $mime) = GalleryCoreApi::convertExtensionToMime(
				    $relevantTypes[$type]);
				if ($ret->isError()) {
				    return array($ret->wrap(__FILE__, __LINE__), null, null, null);
				}
				$mimeTypes[$mime] = 1;
			    }
			}
		    }

		    $resultLine = $results[$i++];
		} while (!empty($resultLine));
		$success = true;
	    }
	}
	$tests[] = array('name' => 'ffmpeg',
			 'success' => $success,
			 'results' => $results);

	/* Test if this ffmpeg supports -ss flag.. */
	$supportsOffset = false;
	list ($ok, $flags) = $platform->exec(array(array($ffmpegPath, '-h')));
	foreach ($flags as $line) {
	    if (!strncmp($line, '-ss ', 4)) {
		$supportsOffset = true;
		break;
	    }
	}

	return array(GalleryStatus::success(), $tests, array_keys($mimeTypes), $supportsOffset);
    }
}
?>
