Using Zencoder with Zend Framework

Zencoder is an API-based online video and audio encoding service. Zencoder converts videos from your website, application, or video library into formats that are compatible with web playback, mobile phone, or any other device you need to support. Zencoder have friendly API and php library. We can use this library with Zend Framework after some modifications. Click here to download modified library.

First we must write js script, that will send ajax request to some Zend Framework controller and will receive response with information about created encoding job

$(document).ready(function(){
    $('#progressbar').css('width', '400px');
    $.post('/publish/zencoder', {convert: 1 }, function(data){
       if (!data) alert('Some thing wrong!');
       var html = '';
       if(data.success){
           for (i = 0; i < data.data.length; i++) {
               var  progress_bar =
                   '
 
<div class="progress_container">
 
<div id="progress'+data.data[i].id+'" class="progress">'+data.data[i].status.progress+'%</div>
</div>
 
 
 ';
               html = html+'
 
<div class="status'+data.data[i].id+'">'+ progress_bar+'</div>
 
 
<div id="tp2">(encoding progress)</div>
 
 
';
               $.post('/publish/zencoder', {url:  data.data[i].url},
                        function(data){ }, 'json');
               updateStatus(data.data[i].id);
            }
            $('#tp').after(html);
        }
        if(data.error){
        $('#error').text('We had a problem understanding your
                              audio file.  Please try again.');
    }
 
    }, 'json');
    return false;
})

Then write controller, that will create encoding job with some parameters, will update encoding job status or will save to session url of encoded file

public function zencoderAction()
    {
        $this->_helper->layout->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();
        $dataNamespace = new Zend_Session_Namespace('StepsNamespace');
        $convert = $this->getRequest()->getParam('convert');
        $updateStatus = $this->getRequest()->getParam('update_status');
        $url = $this->getRequest()->getParam('url');
        if(isset($convert)){
            $config = Zend_Registry::get('config');
            $inputFile = addslashes(''.$config['zencoder']['inputPath'].
                            ($dataNamespace->filename).'');
            $outputFile = addslashes(urlencode($dataNamespace->newname));
            $encoding_job = new Zencoder_ZencoderJob('
                {
                    "api_key": "'.$config['zencoder']['apiKey'].'",
                    "input": "'.$inputFile.'",
                    "outputs": [
                        {
                            "label": "Audio",
                            "url": "'.$config['zencoder']['s3Bucket'].
                            $outputFile.'.mp4",
                            "public": 1,
                            "audio_codec": "'.
                            $config['zencoder']['audioCodec'].'",
                            "audio_channels": "'.
                            $config['zencoder']['audioChannels'].'",
                            "audio_bitrate": "'.
                            $config['zencoder']['audioBitrate'].'"
 
                        }
                    ]
                }
            ');
            if ($encoding_job->created) {
            $files = array();
            $dataNamespace->id = $encoding_job->id;
            foreach ($encoding_job->outputs as $key => $value) {
                $files[]        = array('id'     => $value->id,
                                                'label' => $value->label,
                                                'url'     => $value->url,
                                                'status'=>
                                                $this->checkStatus($value->id),
                                                );
            }
 
            $data = array(
                                'success' => true,
                                'job_id'    => $encoding_job->id,
                                'data'      => $files,
                                );
            } else {
                $errors = array();
                foreach($encoding_job->errors as $error) {
                    $errors[] = $error;
                }
                $data['error'] = implode(',', $errors);
            }
            $this->getResponse()->setHeader('Content-Type',
             'application/json');
            $this->_helper->json($data);
            }
        elseif(isset($updateStatus)){
            $id = $this->getRequest()->getParam('id');
            $data = $this->checkStatus($id);
            $this->getResponse()->setHeader('Content-Type',
            'application/json');
            $this->_helper->json($data);
        }
        elseif(isset($url)){
            $dataNamespace->fileext = $url;
        }
 
    }

Update encoding status script will be as follows

function updateStatus(id){
             $.post('/publish/zencoder', {update_status: 1, id: id },
                                                  function(data){
                var status = data.event;
                var status_mes = "";
                switch(status){
                    case "Downloading": status_mes = "(downloading
                                                                   progress)";
                                                         break;
                    case "Inspecting": status_mes = "(inspecting
                                                                 progress)";
                                                         break;
                    case "Transcoding": status_mes = "(transcoding
                                                                  progress)";
                                                         break;
                    case "Uploading": status_mes = "(uploading
                                                               progress)";
                                                         break;
                    case "processing": status_mes = "(processing
                                                                progress)";
                                                         break;
                }
                $('#tp2').html(status_mes);
                if(data.event != 'processing'){
                    $('#progress'+id).html(data.progress+'%');
                    $('#progress'+id).css('width', data.progress+'%');
                }
                if(!data.finished){
                    updateStatus(id);
                }else{
                     window.location.href = '/publish/audio-step2';
                }
            }, 'json');            
 
        }

And last, function that retrieves the current encoding status

  protected function checkStatus($id)
    {
        $config = Zend_Registry::get('config');
        $request = new Zencoder_ZencoderRequest(
                  'https://app.zencoder.com/api/outputs/'. $id .'/progress.xml',
                  ''.$config['zencoder']['apiKey'].''
                );
        //get progress:
        $event = '';
        $progress = '';
        preg_match_all('"<[^>]+>(.*)<!--[^-->]+>"',$request->raw_results, $matches);
        if(is_array($matches)){
            $event = $matches[1][0];
            @$progress = $matches[1][1];
        }
        if($progress == 'finished') $progress = 100;
        return array('successful' => $request->successful,
                            'finished'      => ($event == 'Uploading' &amp;&amp; $progress == 100) ? 1 : 0,
                            'event'          =>     $event,
                            'progress'     =>     $progress ? intval($progress) : 1,
                            );
    }

Official zencoder api documentation: https://app.zencoder.com/docs/api
Author: Sergey Gerashchenko

  • Jack

    Just a quick question… How did you modify the Zencoder PHP API? It looks like there isn’ta link provided to the changes you made to the API.

  • admin

    Hi, Jack. I fixed link in the post, so you can download zip with library now (http://lamp-dev.com/wp-content/uploads/2011/04/Zencoder.zip). Thanks for you reply.

Leave a Reply

Your email address will not be published. Required fields are marked *