Recherche avancée

Médias (3)

Mot : - Tags -/collection

Autres articles (69)

  • Publier sur MédiaSpip

    13 juin 2013

    Puis-je poster des contenus à partir d’une tablette Ipad ?
    Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir

  • MediaSPIP 0.1 Beta version

    25 avril 2011, par

    MediaSPIP 0.1 beta is the first version of MediaSPIP proclaimed as "usable".
    The zip file provided here only contains the sources of MediaSPIP in its standalone version.
    To get a working installation, you must manually install all-software dependencies on the server.
    If you want to use this archive for an installation in "farm mode", you will also need to proceed to other manual (...)

  • Submit bugs and patches

    13 avril 2011

    Unfortunately a software is never perfect.
    If you think you have found a bug, report it using our ticket system. Please to help us to fix it by providing the following information : the browser you are using, including the exact version as precise an explanation as possible of the problem if possible, the steps taken resulting in the problem a link to the site / page in question
    If you think you have solved the bug, fill in a ticket and attach to it a corrective patch.
    You may also (...)

Sur d’autres sites (12739)

  • Call bash function in Java

    16 mai 2023, par ilie alexandru

    I have been using Java with bash in order to make some things easier, some examples :

    


    From the main class to call a subclass in order to use bash commands :

    


    Main classs :

    


        //Checking if the server already has the user or not
    CheckUser checkUser = new CheckUser();
    int checuser= checkUser.CheckUserMethod(user);
    if( 1 != checuser) { // Yoda notation

        //Making the directory for the user
        File userDirectory = new File(this.directory);
        userDirectory.mkdir();
    }


    


    The class that will call the ".sh" file :

    


    public class CheckUser {

protected int CheckUserMethod(String user){
    try {

        Process p = Runtime.getRuntime().exec(new String[]{"bash", "-c", "cd ~/Final-Year-Spring/src/main/java/query && ./checkuser.sh " + user});
        BufferedReader srdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String s =srdInput.readLine();
        if(s==null){
            return 0;
        }else {
            return Integer.parseInt(s);
        }
    }catch (Exception e){
        throw new RuntimeException(e);
    }
}


    


    


    The bash file :

    


    #!/bin/bash

# shellcheck disable=SC2237
if ! [ -z "$1" ]
then
  cd ~/Final-Year-Spring/maps/ && find "$1" -maxdepth 0 -type d -printf 1
fi


    


    Now you have a context.

    


    I am trying to call a bash file that will execute a ffmpeg command. For instance, the same command when I am using the terminal :

    


    ffmpeg -ss 00:00:00.75 -to 00:00:00.93 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00009.mp4 -ss 00:00:01.71 -to 00:00:01.82 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00009.mp4 ~/IdeaProjects/Final-Year-Spring/maps/output.mp4S


    


    Also a screenshot with the command in the cli :

    


    enter image description here

    


    The result of the cli command :

    


    enter image description here

    


    Now I am trying to do the same thing for multiple videos using Java and Bash.

    


    The class that will create the input and the time :

    


    public String CreateNewVideoMethod()

    


    ArrayList<string> arrayList = new ArrayList&lt;>();&#xA;&#xA;MainSearch mainSearch = new MainSearch(this.array, this.search);&#xA;HashMap>>> map = new HashMap&lt;>();&#xA;        map = mainSearch.SearchInVideous();&#xA;&#xA;&#xA;HashMap>> file = new HashMap&lt;>();&#xA;file=map.get(this.array.get(1));&#xA;&#xA;file.forEach((k,v)->{&#xA;    StringBuilder stringBuilder = new StringBuilder(this.defaultpth);&#xA;    stringBuilder.append("/")&#xA;            .append(this.array.get(0))&#xA;            .append("/")&#xA;            .append(this.array.get(1))&#xA;            .append("/")&#xA;            .append(k)&#xA;            .append("/")&#xA;            .append("InfoVideo.txt");&#xA;&#xA;    GetVideoPath getVideoPath = new GetVideoPath();&#xA;    String videoPath = getVideoPath.GetVideoPathMethod(stringBuilder);&#xA;&#xA;    v.forEach((k1,v1)->{ // iterate though the words&#xA;        v1.forEach((k2,v2)->{ // iterate though the times&#xA;&#xA;            String doubleAsStringForKey = String.valueOf(k2);&#xA;            String[] arr = doubleAsStringForKey.split("\\.");&#xA;&#xA;            String doubleASStringForValue = String.valueOf(v2);&#xA;            String[] arr2 = doubleASStringForValue.split("\\.");&#xA;&#xA;            if(k2>10){&#xA;&#xA;                StringBuilder stringBuilder1 = new StringBuilder();&#xA;                stringBuilder1.append(" -ss ")&#xA;                        .append("00:00:")&#xA;                        .append(arr[0])&#xA;                        .append(".")&#xA;                        .append(arr[1])&#xA;                        .append(" -to ")&#xA;                        .append(" 00:00:")&#xA;                        .append(arr2[0])&#xA;                        .append(".")&#xA;                        .append(arr2[1])&#xA;                        .append(" -i ")&#xA;                        .append(videoPath);&#xA;                arrayList.add(String.valueOf(stringBuilder1));&#xA;            }&#xA;                else{&#xA;&#xA;                    StringBuilder stringBuilder1 = new StringBuilder();&#xA;                    stringBuilder1.append(" -ss ")&#xA;                            .append("00:00:0")&#xA;                            .append(arr[0])&#xA;                            .append(".")&#xA;                            .append(arr[1])&#xA;                            .append(" -to ")&#xA;                            .append("00:00:0")&#xA;                            .append(arr2[0])&#xA;                            .append(".")&#xA;                            .append(arr2[1])&#xA;                            .append(" -i ")&#xA;                            .append(videoPath);&#xA;                    arrayList.add(String.valueOf(stringBuilder1));&#xA;                }&#xA;&#xA;        });&#xA;    });&#xA;&#xA;});&#xA;&#xA;BashFIleForCreatingNewVideo bashFIleForCreatingNewVideo = new BashFIleForCreatingNewVideo();&#xA;bashFIleForCreatingNewVideo.BashFileForCreatingNewVideo(arrayList);&#xA;</string>

    &#xA;

    The class that must call the ".sh" file :

    &#xA;

    public class BashFIleForCreatingNewVideo {&#xA;&#xA;    protected String BashFileForCreatingNewVideo(ArrayList<string> arrayList){&#xA;        try {&#xA;&#xA;        StringBuilder stringBuilder = new StringBuilder();&#xA;&#xA;        for(String str : arrayList){&#xA;            stringBuilder.append(str);&#xA;        }&#xA;        Process p = Runtime.getRuntime().exec(new String[]{"bash", "-c", "cd ~/IdeaProjects/Final-Year-Spring/src/main/java/com/FinalYearProjectServer/Get_Requests/CreateNewVideo &amp;&amp; ./createNewVideo.sh ", String.valueOf(stringBuilder), String.valueOf(arrayList.size()-1), "./maps/outputstream.mp4"});&#xA;        BufferedReader srdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));&#xA;        String s =srdInput.readLine();&#xA;&#xA;        if(s==null){&#xA;            return "Error";&#xA;        }else {&#xA;            System.out.println(s);&#xA;            return s;&#xA;        }&#xA;&#xA;        } catch (IOException e) {&#xA;            throw new RuntimeException(e);&#xA;        }&#xA;&#xA;    }&#xA;}&#xA;</string>

    &#xA;

    The script file :

    &#xA;

    #!/bin/bash&#xA;&#xA;arr=( "$@" )&#xA;&#xA;echo "${arr[*]}"&#xA;&#xA;ffmpeg "${arr[0]}" -filter_complex concat=n="${arr[1]}":v=1:a=1 "${arr[2]}"&#xA;

    &#xA;

    What is passed to the script, small exaple, this is a string :

    &#xA;

     -ss 00:00:00.75 -to 00:00:00.93 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00009.mp4 -ss 00:00:01.71 -to 00:00:01.82 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00009.mp4 -ss 00:00:00.09 -to 00:00:00.34 -i ~/IdeaProjects/Final-Year-Spring/datassets/Alex/check/5535415699068794046/00027.mp4&#xA;

    &#xA;

    The next parameter is the number of videos that must concatenate and the last parameter is where the output must be.

    &#xA;

    My problem is the Bash file is not executing even the echo command or doing something. Do you have any suggestion, because I thing is about the way of how I am passing the array to the Bash file.

    &#xA;

    Ok so I am trying to use ProcessBuilder :

    &#xA;

            String[] command = {"bash","ffmpeg", String.valueOf(stringBuilder), "-filter_complex concat=n="&#x2B;String.valueOf(arrayList.size()-1)&#x2B;":v=1:a=1", "~/IdeaProjects/Final-Year-Spring/maps/output1.mp4"};&#xA;        ProcessBuilder p = new ProcessBuilder(command);&#xA;        Process p2 = p.start();&#xA;        BufferedReader srdInput;&#xA;        srdInput = new BufferedReader(new InputStreamReader(p2.getInputStream()));&#xA;        String s =srdInput.readLine();&#xA;

    &#xA;

  • Video encoding task not working with Django Celery Redis FFMPEG and GraphQL

    18 juin 2023, par phanio

    I'm having a hard time trying to understand how is this FFMPEG encoding works while using Django, Celery, Redis, GraphQL and Docker too.

    &#xA;

    I have this video / courses platform project and want I'm trying to do using FFMPEG, Celery and Redis is to create different video resolutions so I can display them the way Youtube does inside the videoplayer ( the videoplayer is handled in frontend by Nextjs and Apollo Client ), now on the backend I've just learned that in order to use properly the FFMPEG to resize the oridinal video size, I need to use Celery and Redis to perform asyncronus tasks. I've found a few older posts here on stackoverflow and google, but is not quite enough info for someone who is using the ffmpeg and clery and redis for the first time ( I've started already step by step and created that example that adds two numbers together with celery, that works well ). Now I'm not sure what is wrong with my code, because first of all I'm not really sure where should I trigger the task from, I mean from which file, because at the end of the task I want to send the data through api using GrapQL Strawberry.

    &#xA;

    This is what I've tried by now :

    &#xA;

    So first things first my project structure looks like this

    &#xA;

    - backend #root directory&#xA; --- backend&#xA;    -- __init__.py&#xA;    -- celery.py&#xA;    -- settings.py&#xA;    -- urls.py&#xA;      etc..&#xA;&#xA; --- static&#xA;   -- videos&#xA;&#xA; --- video&#xA;   -- models.py&#xA;   -- schema.py&#xA;   -- tasks.py&#xA;   -- types.py&#xA;   etc..&#xA;&#xA; --- .env&#xA;&#xA; --- db.sqlite3&#xA;&#xA; --- docker-compose.yml&#xA;&#xA; --- Dockerfile&#xA;&#xA; --- manage.py&#xA;&#xA; --- requirements.txt&#xA;

    &#xA;

    here is my settings.py file :

    &#xA;

    from pathlib import Path&#xA;import os&#xA;&#xA;# Build paths inside the project like this: BASE_DIR / &#x27;subdir&#x27;.&#xA;BASE_DIR = Path(__file__).resolve().parent.parent&#xA;&#xA;DEBUG = True&#xA;&#xA;ALLOWED_HOSTS=["localhost", "0.0.0.0", "127.0.0.1"]&#xA;&#xA;DEFAULT_AUTO_FIELD = &#x27;django.db.models.BigAutoField&#x27;&#xA;&#xA;&#xA;# Application definition&#xA;&#xA;INSTALLED_APPS = [&#xA;    "corsheaders",&#xA;    &#x27;django.contrib.admin&#x27;,&#xA;    &#x27;django.contrib.auth&#x27;,&#xA;    &#x27;django.contrib.contenttypes&#x27;,&#xA;    &#x27;django.contrib.sessions&#x27;,&#xA;    &#x27;django.contrib.messages&#x27;,&#xA;    &#x27;django.contrib.staticfiles&#x27;,&#xA;&#xA;    "strawberry.django",&#xA;    "video"&#xA;]&#xA;&#xA;etc...&#xA;&#xA;STATIC_URL = &#x27;/static/&#x27;&#xA;MEDIA_URL = &#x27;/videos/&#x27;&#xA;&#xA;STATICFILES_DIRS = [&#xA;    BASE_DIR / &#x27;static&#x27;,&#xA;    # BASE_DIR / &#x27;frontend/build/static&#x27;,&#xA;]&#xA;&#xA;MEDIA_ROOT = BASE_DIR / &#x27;static/videos&#x27;&#xA;&#xA;STATIC_ROOT = BASE_DIR / &#x27;staticfiles&#x27;&#xA;&#xA;STATICFILES_STORAGE = &#x27;whitenoise.storage.CompressedManifestStaticFilesStorage&#x27;&#xA;&#xA;CORS_ALLOW_ALL_ORIGINS = True&#xA;&#xA;&#xA;CELERY_BEAT_SCHEDULER = &#x27;django_celery_beat.schedulers:DatabaseScheduler&#x27;&#xA;&#xA;# REDIS CACHE&#xA;CACHES = {&#xA;    "default": {&#xA;        "BACKEND": "django_redis.cache.RedisCache",&#xA;        "LOCATION": f"redis://127.0.0.1:6379/1",&#xA;        "OPTIONS": {&#xA;            "CLIENT_CLASS": "django_redis.client.DefaultClient",&#xA;        },&#xA;    }&#xA;}&#xA;&#xA;# Docker&#xA;CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379/0")&#xA;CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", "redis://redis:6379/0")&#xA;

    &#xA;

    This is my main urls.py file :

    &#xA;

    from django.contrib import admin&#xA;from django.conf import settings&#xA;from django.conf.urls.static import static&#xA;from django.urls import path&#xA;from django.urls.conf import include&#xA;from strawberry.django.views import GraphQLView&#xA;&#xA;from video.schema import schema&#xA;&#xA;urlpatterns = [&#xA;    path(&#x27;admin/&#x27;, admin.site.urls),&#xA;    path("graphql", GraphQLView.as_view(schema=schema)),&#xA;]&#xA;&#xA;if settings.DEBUG:&#xA;    urlpatterns &#x2B;= static(settings.MEDIA_URL,&#xA;                          document_root=settings.MEDIA_ROOT)&#xA;    urlpatterns &#x2B;= static(settings.STATIC_URL,&#xA;                          document_root=settings.STATIC_ROOT)&#xA;

    &#xA;

    This is my celery.py file :

    &#xA;

    from __future__ import absolute_import, unicode_literals&#xA;import os&#xA;from celery import Celery&#xA;from django.conf import settings&#xA;&#xA;os.environ.setdefault(&#x27;DJANGO_SETTINGS_MODULE&#x27;, &#x27;backend.settings&#x27;)&#xA;&#xA;backend = Celery(&#x27;backend&#x27;)&#xA;&#xA;backend.config_from_object(&#x27;django.conf:settings&#x27;, namespace="CELERY")&#xA;&#xA;backend.autodiscover_tasks()&#xA;&#xA;@backend.task(bind=True)&#xA;def debug_task(self):&#xA;    print(&#x27;Request: {0!r}&#x27;.format(self.request))&#xA;

    &#xA;

    This is my init.py file :

    &#xA;

    from .celery import backend as celery_backend&#xA;&#xA;__all__ = (&#x27;celery_backend&#x27;,)&#xA;

    &#xA;

    This is my Dockerfile :

    &#xA;

    FROM python:3&#xA;ENV PYTHONUNBUFFERED=1&#xA;&#xA;WORKDIR /usr/src/backend&#xA;&#xA;RUN apt-get -y update&#xA;RUN apt-get -y upgrade&#xA;RUN apt-get install -y ffmpeg&#xA;&#xA;COPY requirements.txt ./&#xA;RUN pip install -r requirements.txt&#xA;

    &#xA;

    This is my docker-compose.yml file :

    &#xA;

    version: "3.8"&#xA;&#xA;services:&#xA;  django:&#xA;    build: .&#xA;    container_name: django&#xA;    command: python manage.py runserver 0.0.0.0:8000&#xA;    volumes:&#xA;      - .:/usr/src/backend/&#xA;    ports:&#xA;      - "8000:8000"&#xA;    environment:&#xA;      - DEBUG=1&#xA;      - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]&#xA;      - CELERY_BROKER=redis://redis:6379/0&#xA;      - CELERY_BACKEND=redis://redis:6379/0&#xA;    depends_on:&#xA;      - pgdb&#xA;      - redis&#xA;&#xA;  celery:&#xA;    build: .&#xA;    command: celery -A backend worker -l INFO&#xA;    volumes:&#xA;      - .:/usr/src/backend&#xA;    depends_on:&#xA;      - django&#xA;      - redis&#xA;&#xA;  pgdb:&#xA;    image: postgres&#xA;    container_name: pgdb&#xA;    environment:&#xA;      - POSTGRES_DB=postgres&#xA;      - POSTGRES_USER=postgres&#xA;      - POSTGRES_PASSWORD=postgres&#xA;    volumes:&#xA;      - pgdata:/var/lib/postgresql/data/&#xA;&#xA;  redis:&#xA;    image: "redis:alpine"&#xA;&#xA;volumes:&#xA;  pgdata:&#xA;

    &#xA;

    And now inside my video app folder :

    &#xA;

    My models.py file :

    &#xA;

      &#xA;
    • here I've created separated fields for all resolution sizes, from video_file_2k to video_file_144, I was thinking that maybe after the process of the encoding this will populate those fields..
    • &#xA;

    &#xA;

    from django.db import models&#xA;from django.urls import reverse&#xA;&#xA;&#xA;class Video(models.Model):&#xA;    video_id = models.AutoField(primary_key=True, editable=False)&#xA;    slug = models.SlugField(max_length=255)&#xA;    title = models.CharField(max_length=150, blank=True, null=True)&#xA;    description = models.TextField(blank=True, null=True)&#xA;    video_file = models.FileField(null=False, blank=False)&#xA;    video_file_2k = models.FileField(null=True, blank=True)&#xA;    video_file_fullhd = models.FileField(null=True, blank=True)&#xA;    video_file_hd = models.FileField(null=True, blank=True)&#xA;    video_file_480 = models.FileField(null=True, blank=True)&#xA;    video_file_360 = models.FileField(null=True, blank=True)&#xA;    video_file_240 = models.FileField(null=True, blank=True)&#xA;    video_file_144 = models.FileField(null=True, blank=True)&#xA;    category = models.CharField(max_length=64, blank=False, null=False)&#xA;    created_at = models.DateTimeField(&#xA;        ("Created at"), auto_now_add=True, editable=False)&#xA;    updated_at = models.DateTimeField(("Updated at"), auto_now=True)&#xA;&#xA;    class Meta:&#xA;        ordering = ("-created_at",)&#xA;        verbose_name = ("Video")&#xA;        verbose_name_plural = ("Videos")&#xA;&#xA;    def get_absolute_url(self):&#xA;        return reverse("store:video_detail", args=[self.slug])&#xA;&#xA;    def __str__(self):&#xA;        return self.title&#xA;

    &#xA;

    This is my schema.py file :

    &#xA;

    import strawberry&#xA;from strawberry.file_uploads import Upload&#xA;from typing import List&#xA;from .types import VideoType&#xA;from .models import Video&#xA;from .tasks import task_video_encoding_1080p, task_video_encoding_720p&#xA;&#xA;&#xA;@strawberry.type&#xA;class Query:&#xA;    @strawberry.field&#xA;    def videos(self, category: str = None) -> List[VideoType]:&#xA;        if category:&#xA;            videos = Video.objects.filter(category=category)&#xA;            return videos&#xA;        return Video.objects.all()&#xA;&#xA;    @strawberry.field&#xA;    def video(self, slug: str) -> VideoType:&#xA;        if slug == slug:&#xA;            video = Video.objects.get(slug=slug)&#xA;            return video&#xA;&#xA;    @strawberry.field&#xA;    def video_by_id(self, video_id: int) -> VideoType:&#xA;        if video_id == video_id:&#xA;            video = Video.objects.get(pk=video_id)&#xA;&#xA;          # Here I&#x27;ve tried to trigger my tasks, when I visited 0.0.0.0:8000/graphql url&#xA;          # and I was querying for a video by it&#x27;s id , then I&#x27;ve got the error from celery &#xA;            task_video_encoding_1080p.delay(video_id)&#xA;            task_video_encoding_720p.delay(video_id)&#xA;&#xA;            return video&#xA;&#xA;&#xA;@strawberry.type&#xA;class Mutation:&#xA;    @strawberry.field&#xA;    def create_video(self, slug: str, title: str, description: str, video_file: Upload, video_file_2k: str, video_file_fullhd: str, video_file_hd: str, video_file_480: str, video_file_360: str, video_file_240: str, video_file_144: str, category: str) -> VideoType:&#xA;&#xA;        video = Video(slug=slug, title=title, description=description,&#xA;                      video_file=video_file, video_file_2k=video_file_2k, video_file_fullhd=video_file_fullhd, video_file_hd=video_file_hd, video_file_480=video_file_480, video_file_360=video_file_360, video_file_240=video_file_240, video_file_144=video_file_144,category=category)&#xA;        &#xA;        video.save()&#xA;        return video&#xA;&#xA;    @strawberry.field&#xA;    def update_video(self, video_id: int, slug: str, title: str, description: str, video_file: str, category: str) -> VideoType:&#xA;        video = Video.objects.get(video_id=video_id)&#xA;        video.slug = slug&#xA;        video.title = title&#xA;        video.description = description&#xA;        video.video_file = video_file&#xA;        video.category = category&#xA;        video.save()&#xA;        return video&#xA;&#xA;    @strawberry.field&#xA;    def delete_video(self, video_id: int) -> bool:&#xA;        video = Video.objects.get(video_id=video_id)&#xA;        video.delete&#xA;        return True&#xA;&#xA;&#xA;schema = strawberry.Schema(query=Query, mutation=Mutation)&#xA;

    &#xA;

    This is my types.py file ( strawberry graphql related ) :

    &#xA;

    import strawberry&#xA;&#xA;from .models import Video&#xA;&#xA;&#xA;@strawberry.django.type(Video)&#xA;class VideoType:&#xA;    video_id: int&#xA;    slug: str&#xA;    title: str&#xA;    description: str&#xA;    video_file: str&#xA;    video_file_2k: str&#xA;    video_file_fullhd: str&#xA;    video_file_hd: str&#xA;    video_file_480: str&#xA;    video_file_360: str&#xA;    video_file_240: str&#xA;    video_file_144: str&#xA;    category: str&#xA;

    &#xA;

    And this is my tasks.py file :

    &#xA;

    from __future__ import absolute_import, unicode_literals&#xA;import os, subprocess&#xA;from django.conf import settings&#xA;from django.core.exceptions import ValidationError&#xA;from celery import shared_task&#xA;from celery.utils.log import get_task_logger&#xA;from .models import Video&#xA;FFMPEG_PATH = os.environ["IMAGEIO_FFMPEG_EXE"] = "/opt/homebrew/Cellar/ffmpeg/6.0/bin/ffmpeg"&#xA;&#xA;logger = get_task_logger(__name__)&#xA;&#xA;&#xA;# CELERY TASKS&#xA;@shared_task&#xA;def add(x,y):&#xA;    return x &#x2B; y&#xA;&#xA;&#xA;@shared_task&#xA;def task_video_encoding_720p(video_id):&#xA;    logger.info(&#x27;Video Processing started&#x27;)&#xA;    try:&#xA;        video = Video.objects.get(video_id=video_id)&#xA;        input_file_path = video.video_file.path&#xA;        input_file_url = video.video_file.url&#xA;        input_file_name = video.video_file.name&#xA;&#xA;        # get the filename (without extension)&#xA;        filename = os.path.basename(input_file_url)&#xA;&#xA;        # path to the new file, change it according to where you want to put it&#xA;        output_file_name = os.path.join(&#x27;videos&#x27;, &#x27;mp4&#x27;, &#x27;{}.mp4&#x27;.format(filename))&#xA;        output_file_path = os.path.join(settings.MEDIA_ROOT, output_file_name)&#xA;&#xA;        # 2-pass encoding&#xA;        for i in range(1):&#xA;           new_video_720p = subprocess.call([FFMPEG_PATH, &#x27;-i&#x27;, input_file_path, &#x27;-s&#x27;, &#x27;1280x720&#x27;, &#x27;-vcodec&#x27;, &#x27;mpeg4&#x27;, &#x27;-acodec&#x27;, &#x27;libvo_aacenc&#x27;, &#x27;-b&#x27;, &#x27;10000k&#x27;, &#x27;-pass&#x27;, i, &#x27;-r&#x27;, &#x27;30&#x27;, output_file_path])&#xA;        #    new_video_720p = subprocess.call([FFMPEG_PATH, &#x27;-i&#x27;, input_file_path, &#x27;-s&#x27;, &#x27;{}x{}&#x27;.format(height * 16/9, height), &#x27;-vcodec&#x27;, &#x27;mpeg4&#x27;, &#x27;-acodec&#x27;, &#x27;libvo_aacenc&#x27;, &#x27;-b&#x27;, &#x27;10000k&#x27;, &#x27;-pass&#x27;, i, &#x27;-r&#x27;, &#x27;30&#x27;, output_file_path])&#xA;&#xA;        if new_video_720p == 0:&#xA;            # save the new file in the database&#xA;            # video.video_file_hd.name = output_file_name&#xA;            video.save(update_fields=[&#x27;video_file_hd&#x27;])&#xA;            logger.info(&#x27;Video Processing Finished&#x27;)&#xA;            return video&#xA;&#xA;        else:&#xA;            logger.info(&#x27;Proceesing Failed.&#x27;) # Just for now&#xA;&#xA;    except:&#xA;        raise ValidationError(&#x27;Something went wrong&#x27;)&#xA;&#xA;&#xA;@shared_task&#xA;# def task_video_encoding_1080p(video_id, height):&#xA;def task_video_encoding_1080p(video_id):&#xA;    logger.info(&#x27;Video Processing started&#x27;)&#xA;    try:&#xA;        video = Video.objects.get(video_id=video_id)&#xA;        input_file_path = video.video_file.url&#xA;        input_file_name = video.video_file.name&#xA;&#xA;        # get the filename (without extension)&#xA;        filename = os.path.basename(input_file_path)&#xA;&#xA;        # path to the new file, change it according to where you want to put it&#xA;        output_file_name = os.path.join(&#x27;videos&#x27;, &#x27;mp4&#x27;, &#x27;{}.mp4&#x27;.format(filename))&#xA;        output_file_path = os.path.join(settings.MEDIA_ROOT, output_file_name)&#xA;&#xA;        for i in range(1):&#xA;            new_video_1080p = subprocess.call([FFMPEG_PATH, &#x27;-i&#x27;, input_file_path, &#x27;-s&#x27;, &#x27;1920x1080&#x27;, &#x27;-vcodec&#x27;, &#x27;mpeg4&#x27;, &#x27;-acodec&#x27;, &#x27;libvo_aacenc&#x27;, &#x27;-b&#x27;, &#x27;10000k&#x27;, &#x27;-pass&#x27;, i, &#x27;-r&#x27;, &#x27;30&#x27;, output_file_path])&#xA;&#xA;        if new_video_1080p == 0:&#xA;            # save the new file in the database&#xA;            # video.video_file_hd.name = output_file_name&#xA;            video.save(update_fields=[&#x27;video_file_fullhd&#x27;])&#xA;            logger.info(&#x27;Video Processing Finished&#x27;)&#xA;            return video&#xA;        else:&#xA;            logger.info(&#x27;Proceesing Failed.&#x27;) # Just for now&#xA;&#xA;    except:&#xA;        raise ValidationError(&#x27;Something went wrong&#x27;)&#xA;

    &#xA;

    In my first attempt I wasn't triggering the tasks no where, then I've tried to trigger the task from the schema.py file from graphql inside the video_by_id, but there I've got this error :

    &#xA;

    backend-celery-1  | django.core.exceptions.ValidationError: [&#x27;Something went wrong&#x27;]&#xA;backend-celery-1  | [2023-06-18 16:38:52,859: ERROR/ForkPoolWorker-4] Task video.tasks.task_video_encoding_1080p[d33b1a42-5914-467c-ad5c-00565bc8be6f] raised unexpected: ValidationError([&#x27;Something went wrong&#x27;])&#xA;backend-celery-1  | Traceback (most recent call last):&#xA;backend-celery-1  |   File "/usr/src/backend/video/tasks.py", line 81, in task_video_encoding_1080p&#xA;backend-celery-1  |     new_video_1080p = subprocess.call([FFMPEG_PATH, &#x27;-i&#x27;, input_file_path, &#x27;-s&#x27;, &#x27;1920x1080&#x27;, &#x27;-vcodec&#x27;, &#x27;mpeg4&#x27;, &#x27;-acodec&#x27;, &#x27;libvo_aacenc&#x27;, &#x27;-b&#x27;, &#x27;10000k&#x27;, &#x27;-pass&#x27;, i, &#x27;-r&#x27;, &#x27;30&#x27;, output_file_path])&#xA;backend-celery-1  |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^&#xA;backend-celery-1  |   File "/usr/local/lib/python3.11/subprocess.py", line 389, in call&#xA;backend-celery-1  |     with Popen(*popenargs, **kwargs) as p:&#xA;backend-celery-1  |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^&#xA;backend-celery-1  |   File "/usr/local/lib/python3.11/subprocess.py", line 1026, in __init__&#xA;backend-celery-1  |     self._execute_child(args, executable, preexec_fn, close_fds,&#xA;backend-celery-1  |   File "/usr/local/lib/python3.11/subprocess.py", line 1883, in _execute_child&#xA;backend-celery-1  |     self.pid = _fork_exec(&#xA;backend-celery-1  |                ^^^^^^^^^^^&#xA;backend-celery-1  | TypeError: expected str, bytes or os.PathLike object, not int&#xA;backend-celery-1  | &#xA;backend-celery-1  | During handling of the above exception, another exception occurred:&#xA;backend-celery-1  | &#xA;backend-celery-1  | Traceback (most recent call last):&#xA;backend-celery-1  |   File "/usr/local/lib/python3.11/site-packages/celery/app/trace.py", line 477, in trace_task&#xA;backend-celery-1  |     R = retval = fun(*args, **kwargs)&#xA;backend-celery-1  |                  ^^^^^^^^^^^^^^^^^^^^&#xA;backend-celery-1  |   File "/usr/local/lib/python3.11/site-packages/celery/app/trace.py", line 760, in __protected_call__&#xA;backend-celery-1  |     return self.run(*args, **kwargs)&#xA;backend-celery-1  |            ^^^^^^^^^^^^^^^^^^^^^^^^^&#xA;backend-celery-1  |   File "/usr/src/backend/video/tasks.py", line 93, in task_video_encoding_1080p&#xA;backend-celery-1  |     raise ValidationError(&#x27;Something went wrong&#x27;)&#xA;backend-celery-1  | django.core.exceptions.ValidationError: [&#x27;Something went wrong&#x27;]&#xA;

    &#xA;

    If anyone has done this kind of project or something like this please any suggestion or help is much appreciated.

    &#xA;

    Thank you in advance !

    &#xA;

  • FFMpeg video encoding is slow with horrible quality

    4 août 2015, par Muhammad Umar

    I am trying to encode an android video captured from Camera,

    Usually a 3 Second Video is 6mb or let’s say 15 second video is 40 MB.

    I am using ffmpeg to decode, here is the command

               fileToSend = DirectoryUtils.createTemporaryFile(".mp4", AddMoodActivity.this);
               VCamera.initialize(AddMoodActivity.this);
               String ffmpegString = "ffmpeg -i " + picUri.getPath() + " -vf scale=480:-1 -threads 12 -preset ultrafast " + fileToSend.getAbsolutePath();
               UtilityAdapter.FFmpegRun("", ffmpegString);

    Firstly, the quality is horrible .. secondly it takes almost a year to encode.

    How can i optimize, are there any better solutions than this ffmpeg ?