I am trying to convert a video with FFmpeg and everything works fine, but now I'm trying to do the converting process in the background, so I don't have to wait for the process to be done in a minute or so.
Is there any suggestion in how I can do this?
This is my current code in the controller:
$urlGenerator = new urlGenerator();
$user = $this->getUser ();
$userid = $user->getid ();
$username = $user->getFullname ();
$emailcomment = $this->container->getParameter ( 'mailer_sender_address' );
$ffmpeg = $this->get ( 'dubture_ffmpeg.ffmpeg' );
$ffprobe = $this->get ( 'dubture_ffmpeg.ffprobe' );
$currentDateTime = date ( 'YmdHis' );
$upload = new UploadVideo();
$em = $this->getDoctrine ()->getManager ();
$form = $this->createForm ( new UploadVideoType(), $upload );
$userids = $em->getReference ( 'HotelPlanBundle\Entity\User', $userid );
$form->handleRequest ( $request );
if ( $form->isValid () || TRUE ) {
$upload->upload ($userid);
// Start transcoding and save video
$upload->setUserid ( $userids );
$upload->setTitle ( 'No title' );
$upload->setCreatedDate ( new \DateTime() );
$duration = $ffprobe
->format ( $upload->getWebPath () )// extracts file informations
->get ( 'duration' );
$video = $ffmpeg->open ( $upload->getWebPath () );
$video
->frame ( TimeCode::fromSeconds ( 10 ) )
->save ( __DIR__ . '/../../../web/uploads/documents/' . $currentDateTime . '.png' );
$upload->setThumbnail ( $currentDateTime . '.png' );
//here is where the converting takes too long !!
$video->save ( new X264(), __DIR__ . '/../../../web/uploads/documents/' . $currentDateTime . '.mp4' );
$upload->setVideoPath ( $currentDateTime . '.mp4' );
$upload->setLink ( $urlGenerator->generateUrl () );
$upload->setResetLink ( $urlGenerator->generateUrl () );
try {
$em->persist ( $upload );
$em->flush ();
} catch ( \Exception $e ) {
if ( $e->getPrevious ()->getCode () == '23000' ) {
$upload->setLink ( $urlGenerator->generateUrl () );
$em->persist ( $upload );
$em->flush ();
}
}
$em->persist ( $upload );
$em->flush ();
return new JsonResponse( array (
'message' => 'Sucessfully Uploaded',
'last_id' => $upload->getId ()
), 200 );
}
First you should to move ffmpeg logic from the controller to a service. flush your "upload" with new "unconverted" flag.
New service should get "upload" entity by passed id (that was generated after flush)
Then you should to create a console command that will get that service and call "convert" public method with passed id as param.
The service will make same ffmpeg logic that you have in the controller + update "unconverted" flag (ofc if you need to track this state)
Your controller should call new console command in background, for details you can see my suggestion in this answer Asynchronously calling a Command in Symfony2