
Recherche avancée
Médias (2)
-
Granite de l’Aber Ildut
9 septembre 2011, par
Mis à jour : Septembre 2011
Langue : français
Type : Texte
-
Géodiversité
9 septembre 2011, par ,
Mis à jour : Août 2018
Langue : français
Type : Texte
Autres articles (44)
-
Publier sur MédiaSpip
13 juin 2013Puis-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 -
La file d’attente de SPIPmotion
28 novembre 2010, parUne file d’attente stockée dans la base de donnée
Lors de son installation, SPIPmotion crée une nouvelle table dans la base de donnée intitulée spip_spipmotion_attentes.
Cette nouvelle table est constituée des champs suivants : id_spipmotion_attente, l’identifiant numérique unique de la tâche à traiter ; id_document, l’identifiant numérique du document original à encoder ; id_objet l’identifiant unique de l’objet auquel le document encodé devra être attaché automatiquement ; objet, le type d’objet auquel (...) -
Organiser par catégorie
17 mai 2013, parDans MédiaSPIP, une rubrique a 2 noms : catégorie et rubrique.
Les différents documents stockés dans MédiaSPIP peuvent être rangés dans différentes catégories. On peut créer une catégorie en cliquant sur "publier une catégorie" dans le menu publier en haut à droite ( après authentification ). Une catégorie peut être rangée dans une autre catégorie aussi ce qui fait qu’on peut construire une arborescence de catégories.
Lors de la publication prochaine d’un document, la nouvelle catégorie créée sera proposée (...)
Sur d’autres sites (6163)
-
MOV to ACVHD conversion via Spring Boot and FFmpeg leads to file system error
31 décembre 2024, par epicUsernameI am experiencing an issue on a personal project that seeks to convert HEIC to JPG files and MOV files to AVCHD format. The HEIC to JPG conversion works, but the MOV to AVCHD does not, which is where my problems lie.


The intent is to do this with Spring Boot and FFmpeg, using a simple interface done in WindowBuilder.


The relevant bits are the pom file :


<dependencies>
 
 
 <dependency>
 <groupid>jmagick</groupid>
 <artifactid>jmagick</artifactid>
 <version>6.6.9</version>
 </dependency>

 
 <dependency>
 <groupid>net.java.dev.jna</groupid>
 <artifactid>jna</artifactid>
 <version>5.7.0</version> 
 </dependency>
 <dependency>
 <groupid>net.java.dev.jna</groupid>
 <artifactid>jna-platform</artifactid>
 <version>5.7.0</version>
 </dependency>
 
 


 <dependency>
 <groupid>org.bytedeco</groupid>
 <artifactid>ffmpeg</artifactid>
 <version>7.1-1.5.11</version>
 </dependency>
 <dependency>
 <groupid>org.bytedeco</groupid>
 <artifactid>javacv</artifactid>
 <version>1.5.11</version>
 </dependency>
 <dependency>
 <groupid>org.bytedeco</groupid>
 <artifactid>ffmpeg-platform</artifactid>
 <version>7.1-1.5.11</version>
 </dependency>
 
 <dependency>
 <groupid>org.bytedeco</groupid>
 <artifactid>javacpp</artifactid>
 <version>1.5.11</version>
 </dependency>
 </dependencies>




and the main file with the event handling for the application, based on the interface :


package home.multimeida.mmconverter;

imports...

public class MMConverterInterface extends JFrame {

 public static void main(String[] args) {
 
 
 try {
 System.setProperty("jna.library.path", "absolute/path/to/gstreamer/bin");
 // Gst.init("GStreamer Test");
 System.out.println("GStreamer initialized successfully.");
 } catch (Exception e) {
 e.printStackTrace();
 System.out.println("Failed to initialize GStreamer.");
 }
 EventQueue.invokeLater(new Runnable() {
 public void run() {
 try {
 MMConverterInterface frame = new MMConverterInterface();
 frame.setVisible(true);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }

 /**
 * Create the frame.
 */
 public MMConverterInterface() {
 
 // convert button
 
 btnConvert.addActionListener(e -> {
 
 try {
 
 if (sourceFileLabel.getText().equals("No file chosen...") || destinationFolderLabel.getText().equals("No folder selected...")) {
 JOptionPane.showMessageDialog(null, "Please select both an input file and a save location.", "Validation Error", JOptionPane.WARNING_MESSAGE);
 return;
 }
 
 File sourceFile = new File(sourceFileLabel.getText());
 File destinationFile;
 
 if (rdbtnNewRadioButton.isSelected()) {
 
 System.out.println("Converting HEIC to JPG...");
 
 String outputFileName = sourceFile.getName().replaceFirst("[.][^.]+$", ".jpg");
 
 // Call your conversion logic here
 
 destinationFile = new File(destinationFolderLabel.getText(), outputFileName);
 
 convertHeicToJpg(sourceFile, destinationFile);
 
 } else if (rdbtnNewRadioButton_1.isSelected()) {
 
 if (sourceFileLabel.getText().equals("No file chosen...") || destinationFolderLabel.getText().equals("No folder selected...")) {
 JOptionPane.showMessageDialog(null, "Please select both an input file and a save location.", "Validation Error", JOptionPane.WARNING_MESSAGE);
 return;
 }
 
 // Validate source file
 if (!sourceFile.exists() || !sourceFile.canRead()) {
 JOptionPane.showMessageDialog(null, "Source file does not exist or is not readable.", "File Error", JOptionPane.ERROR_MESSAGE);
 return;
 }
 
 // Validate destination folder
 String destinationPath = destinationFolderLabel.getText();
 if (destinationPath == null || destinationPath.isEmpty() || !(new File(destinationPath).isDirectory())) {
 JOptionPane.showMessageDialog(null, "Invalid destination folder.", "File Error", JOptionPane.ERROR_MESSAGE);
 return;
 }
 
 System.out.println("Converting MOV to AVCHD...");
 
 String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());

 // Extract the file name without the extension
 String baseName = sourceFile.getName().replaceFirst("[.][^.]+$", "");

 // Sanitize the base name (replace invalid characters with '_')
 baseName = baseName.replaceAll("[^a-zA-Z0-9-_]", "_");
 
 String sanitizedFileName = baseName + "_" + currentDate;
 sanitizedFileName = sanitizedFileName.replaceAll("[^a-zA-Z0-9._-]", "_"); // Allow alphanumeric, '-', '_', and '.'

 destinationFile = new File(destinationPath, sanitizedFileName);
 
 
 /*
 // Ensure the destination file is writable
 if (!destinationFile.canWrite()) {
 JOptionPane.showMessageDialog(null, "Output file is not writable.", "File Error", JOptionPane.ERROR_MESSAGE);
 return;
 }
 */
 

 convertMovToAvchd(sourceFile, destinationFile);
 
 } else {
 
 JOptionPane.showMessageDialog(null, "Please select a conversion type.");
 
 }
 
 } catch (Exception ex) {
 
 JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage(), "Conversion Error", JOptionPane.ERROR_MESSAGE);
 ex.printStackTrace();
 }
 
 
 });
 
 // cancel button:
 
 btnCancel.addActionListener(e -> {
 System.out.println("Operation canceled.");
 System.exit(0); // Close the application
 });

 }
 
 public void convertMovToAvchd(File sourceFile, File destinationFile) {
 avutil.av_log_set_level(avutil.AV_LOG_DEBUG);
 
 

 AVFormatContext inputFormatContext = null;
 AVFormatContext outputFormatContext = new AVFormatContext(null);
 AVCodecContext inputCodecContext = null;
 AVCodecContext outputCodecContext = null;

 try {
 // Validate input file
 if (!sourceFile.exists() || !sourceFile.canRead()) {
 System.out.println("Source file does not exist or is not readable: " + sourceFile.getAbsolutePath());
 return;
 }
 
 // Validate output file path using the validateFileCreation method
 if (!validateFileCreation(destinationFile)) {
 return; // Exit if destination file validation fails
 }

 // Validate output file path
 if (destinationFile.getParentFile() == null || !destinationFile.getParentFile().exists()) {
 System.out.println("Output directory does not exist: " + destinationFile.getParentFile());
 return;
 }
 if (!destinationFile.getParentFile().canWrite()) {
 System.out.println("Output directory is not writable: " + destinationFile.getParentFile());
 return;
 }

 // Open input file
 inputFormatContext = avformat.avformat_alloc_context();
 if (avformat.avformat_open_input(inputFormatContext, sourceFile.getAbsolutePath(), null, null) < 0) {
 System.out.println("Failed to open input file: " + sourceFile.getAbsolutePath());
 return;
 }

 // Find stream information
 if (avformat.avformat_find_stream_info(inputFormatContext, (PointerPointer) null) < 0) {
 System.out.println("Failed to retrieve input stream information.");
 return;
 }

 // Find video stream
 int videoStreamIndex = avformat.av_find_best_stream(inputFormatContext, avutil.AVMEDIA_TYPE_VIDEO, -1, -1, (AVCodec) null, 0);
 if (videoStreamIndex < 0) {
 System.out.println("Failed to find video stream in input file.");
 return;
 }

 // Initialize input codec context
 inputCodecContext = avcodec.avcodec_alloc_context3(null);
 avcodec.avcodec_parameters_to_context(inputCodecContext, inputFormatContext.streams(videoStreamIndex).codecpar());

 AVCodec decoder = avcodec.avcodec_find_decoder(inputCodecContext.codec_id());
 if (decoder == null || avcodec.avcodec_open2(inputCodecContext, decoder, (PointerPointer) null) < 0) {
 System.out.println("Failed to open video decoder.");
 return;
 }

 // Allocate output format context
 if (avformat.avformat_alloc_output_context2(outputFormatContext, null, "mpegts", destinationFile.getAbsolutePath()) < 0) {
 System.out.println("Failed to allocate output format context.");
 return;
 }

 // Initialize output codec
 AVCodec encoder = avcodec.avcodec_find_encoder_by_name("mpeg2video");
 if (encoder == null) {
 System.out.println("Failed to find MPEG2 video encoder.");
 return;
 }

 outputCodecContext = avcodec.avcodec_alloc_context3(encoder);
 if (outputCodecContext == null) {
 System.out.println("Failed to allocate output codec context.");
 return;
 }
 
 if ((outputFormatContext.oformat().flags() & avformat.AVFMT_GLOBALHEADER) != 0) {
 outputCodecContext.flags(outputCodecContext.flags() | avcodec.AV_CODEC_FLAG_GLOBAL_HEADER);
 }


 //outputCodecContext.codec_id(avcodec.AV_CODEC_ID_MPEG2VIDEO);
 outputCodecContext.codec_id(encoder.id());
 outputCodecContext.codec_type(avutil.AVMEDIA_TYPE_VIDEO);
 outputCodecContext.width(1920);
 outputCodecContext.height(1080);
 outputCodecContext.pix_fmt(avutil.AV_PIX_FMT_YUV420P);
 outputCodecContext.time_base(avutil.av_make_q(1, 25));
 outputCodecContext.bit_rate(4000000);
 outputCodecContext.gop_size(12);

 if ((outputFormatContext.oformat().flags() & avformat.AVFMT_GLOBALHEADER) != 0) {
 outputCodecContext.flags(outputCodecContext.flags() | avcodec.AV_CODEC_FLAG_GLOBAL_HEADER);
 }

 
 
 if (avcodec.avcodec_open2(outputCodecContext, encoder, (PointerPointer) null) < 0) {
 System.out.println("Failed to open video encoder.");
 return;
 }

 // Create output stream
 AVStream videoStream = avformat.avformat_new_stream(outputFormatContext, encoder);
 if (videoStream == null) {
 System.out.println("Failed to create video stream.");
 return;
 }

 avcodec.avcodec_parameters_from_context(videoStream.codecpar(), outputCodecContext);
 
 System.out.println("Destination file path before trying to open the file is: " + destinationFile);

 if ((outputFormatContext.oformat().flags() & avformat.AVFMT_NOFILE) == 0) {
 // Ensure the output path has the correct extension
 String outputPath = destinationFile.getAbsolutePath().replace("\\", "/") + ".avchd";
 System.out.println("Normalized output path: " + outputPath);

 // Try opening the output file
 int ret = avformat.avio_open(outputFormatContext.pb(), outputPath, avformat.AVIO_FLAG_WRITE);
 if (ret < 0) {
 BytePointer errorBuffer = new BytePointer(avutil.AV_ERROR_MAX_STRING_SIZE);
 avutil.av_strerror(ret, errorBuffer, errorBuffer.capacity());
 System.out.println("Failed to open output file: " + errorBuffer.getString());
 return;
 }
 }


 // Write header
 if (avformat.avformat_write_header(outputFormatContext, (PointerPointer) null) < 0) {
 System.out.println("Failed to write header to output file.");
 return;
 }


 // Packet processing loop
 AVPacket packet = new AVPacket();
 while (avformat.av_read_frame(inputFormatContext, packet) >= 0) {
 if (packet.stream_index() == videoStreamIndex) {
 if (avcodec.avcodec_send_packet(inputCodecContext, packet) >= 0) {
 AVFrame frame = avutil.av_frame_alloc();
 while (avcodec.avcodec_receive_frame(inputCodecContext, frame) >= 0) {
 if (avcodec.avcodec_send_frame(outputCodecContext, frame) >= 0) {
 AVPacket encodedPacket = new AVPacket();
 while (avcodec.avcodec_receive_packet(outputCodecContext, encodedPacket) >= 0) {
 encodedPacket.stream_index(videoStream.index());
 avformat.av_interleaved_write_frame(outputFormatContext, encodedPacket);
 avcodec.av_packet_unref(encodedPacket);
 }
 }
 avutil.av_frame_unref(frame);
 }
 avutil.av_frame_free(frame);
 }
 }
 avcodec.av_packet_unref(packet);
 }

 // Write trailer
 avformat.av_write_trailer(outputFormatContext);
 System.out.println("Conversion completed successfully.");
 
 if (avcodec.avcodec_send_frame(outputCodecContext, null) >= 0) {
 AVPacket encodedPacket = new AVPacket();
 while (avcodec.avcodec_receive_packet(outputCodecContext, encodedPacket) >= 0) {
 encodedPacket.stream_index(videoStream.index());
 avformat.av_interleaved_write_frame(outputFormatContext, encodedPacket);
 avcodec.av_packet_unref(encodedPacket);
 }
 }

 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 // Cleanup
 avcodec.avcodec_free_context(inputCodecContext);
 avcodec.avcodec_free_context(outputCodecContext);
 avformat.avformat_close_input(inputFormatContext);

 if (outputFormatContext != null && outputFormatContext.pb() != null) {
 avformat.avio_closep(outputFormatContext.pb());
 }
 avformat.avformat_free_context(outputFormatContext);
 }
 }
 
 private boolean validateFileCreation(File destinationFile) {
 // Check if the parent directory exists and is writable
 File parentDir = destinationFile.getParentFile();
 if (parentDir == null || !parentDir.exists()) {
 System.out.println("Parent directory does not exist: " + parentDir);
 return false;
 }
 if (!parentDir.canWrite()) {
 System.out.println("Cannot write to parent directory: " + parentDir);
 return false;
 }

 // Check if the file exists and is writable
 if (destinationFile.exists()) {
 if (!destinationFile.canWrite()) {
 System.out.println("Destination file is not writable: " + destinationFile);
 return false;
 }
 } else {
 // If the file doesn't exist, try to create it to verify writability
 try {
 if (!destinationFile.createNewFile()) {
 System.out.println("Unable to create destination file: " + destinationFile);
 return false;
 }
 // Delete the file after successful creation to avoid residual files
 destinationFile.delete();
 } catch (IOException e) {
 System.out.println("File creation failed: " + e.getMessage());
 return false;
 }
 }

 return true;
 }
 
}





A few caveats :


- 

-
I did explore FFmpeg and GStreamer for this project. GStreamer was inconclusive, with available version for it that were too old for use with my current state of STS4.27 and Java 17, even if this version of Java is under long-term support...


-
I've used AI to tell me about the options and suggest ways to build this thing, since multimedia handling is very far away from my skillset. I don't have a good conceptual grasp of video formats and how they transfrom from one to another.








The issue, as I have identified it, occurs at these lines :


// Ensure the destination file is writable
 if (!destinationFile.canWrite()) {
 JOptionPane.showMessageDialog(null, "Output file is not writable.", "File Error", JOptionPane.ERROR_MESSAGE);
 return;
 }



^^ And this, while temporarily commented out for testing, it meant to compensate for an issue that occurs here in the conversion function :


if ((outputFormatContext.oformat().flags() & avformat.AVFMT_NOFILE) == 0) {
 // Ensure the output path has the correct extension
 String outputPath = destinationFile.getAbsolutePath().replace("\\", "/") + ".avchd";
 System.out.println("Normalized output path: " + outputPath);

 // Try opening the output file
 int ret = avformat.avio_open(outputFormatContext.pb(), outputPath, avformat.AVIO_FLAG_WRITE);
 if (ret < 0) {
 BytePointer errorBuffer = new BytePointer(avutil.AV_ERROR_MAX_STRING_SIZE);
 avutil.av_strerror(ret, errorBuffer, errorBuffer.capacity());
 System.out.println("Failed to open output file: " + errorBuffer.getString());
 return;
 }
 }



The idea here is that the avio_open() function requires the use of the a valid file path that it can open to be able to write it.


Padadoxically, the file conversion seems to work, but the project crashes with a fatal error in the console :


Selected file: E:\TestConveresions\sample_960x540.mov
Save location: E:\TestConveresions
Converting MOV to AVCHD...
Destination file path before trying to open the file is: E:\TestConveresions\sample_960x540_20241231
Normalized output path: E:/TestConveresions/sample_960x540_20241231.avchd
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffcffb0868b, pid=11020, tid=14436
#
# JRE version: OpenJDK Runtime Environment Temurin-21.0.5+11 (21.0.5+11) (build 21.0.5+11-LTS)
# Java VM: OpenJDK 64-Bit Server VM Temurin-21.0.5+11 (21.0.5+11-LTS, mixed mode, emulated-client, sharing, tiered, compressed oops, compressed class ptrs, g1 gc, windows-amd64)
# Problematic frame:
# C 0x00007ffcffb0868b
#
# No core dump will be written. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# E:\STS4 Workspace\MMConverter\hs_err_pid11020.log
[80.882s][warning][os] Loading hsdis library failed
#
# If you would like to submit a bug report, please visit:
# https://github.com/adoptium/adoptium-support/issues
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
[AVFormatContext @ 000002528adcea40] Opening 'E:\TestConveresions\sample_960x540.mov' for reading
[file @ 000002528ae51c40] Setting default whitelist 'file,crypto,data'
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] Format mov,mp4,m4a,3gp,3g2,mj2 probed with size=2048 and score=100
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] ISO: File Type Major Brand: qt 
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] Unknown dref type 0x206c7275 size 12
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] Processing st: 0, edit list 0 - media time: 2002, duration: 400410
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] Offset DTS by 2002 to make first pts zero.
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] Setting codecpar->delay to 2 for stream st: 0
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] Before avformat_find_stream_info() pos: 1320742 bytes read:38225 seeks:1 nb_streams:1
[h264 @ 000002528ae62780] nal_unit_type: 7(SPS), nal_ref_idc: 3
[h264 @ 000002528ae62780] Decoding VUI
[h264 @ 000002528ae62780] nal_unit_type: 8(PPS), nal_ref_idc: 3
[h264 @ 000002528ae62780] nal_unit_type: 7(SPS), nal_ref_idc: 3
[h264 @ 000002528ae62780] Decoding VUI
[h264 @ 000002528ae62780] nal_unit_type: 8(PPS), nal_ref_idc: 3
[h264 @ 000002528ae62780] nal_unit_type: 6(SEI), nal_ref_idc: 0
[h264 @ 000002528ae62780] nal_unit_type: 5(IDR), nal_ref_idc: 3
[h264 @ 000002528ae62780] Format yuv420p chosen by get_format().
[h264 @ 000002528ae62780] Reinit context to 960x544, pix_fmt: yuv420p
[h264 @ 000002528ae62780] no picture 
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] All info found
[mov,mp4,m4a,3gp,3g2,mj2 @ 000002528adcea40] After avformat_find_stream_info() pos: 51943 bytes read:90132 seeks:2 frames:1
[h264 @ 000002528ae62780] nal_unit_type: 7(SPS), nal_ref_idc: 3
[h264 @ 000002528ae62780] Decoding VUI
[h264 @ 000002528ae62780] nal_unit_type: 8(PPS), nal_ref_idc: 3
[mpeg2video @ 000002528ae8e700] intra_quant_bias = 96 inter_quant_bias = 0




If I refer to the error log, I get this. It is partial, as I'm not sure SO will take all of it (quite long), but still might have enough to be relevant :


Host: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz, 8 cores, 31G, Windows 11 , 64 bit Build 26100 (10.0.26100.2454)


--------------- T H R E A D ---------------

Current thread (0x00000252d030b340): JavaThread "AWT-EventQueue-0" [_thread_in_native, id=14436, stack(0x000000a4e2b00000,0x000000a4e2c00000) (1024K)]

Stack: [0x000000a4e2b00000,0x000000a4e2c00000], sp=0x000000a4e2bfdf30, free space=1015k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C 0x00007ffcffb0868b

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j org.bytedeco.ffmpeg.global.avformat.avio_open(Lorg/bytedeco/ffmpeg/avformat/AVIOContext;Ljava/lang/String;I)I+0
j home.multimeida.mmconverter.MMConverterInterface.convertMovToAvchd(Ljava/io/File;Ljava/io/File;)V+1120
j home.multimeida.mmconverter.MMConverterInterface.lambda$2(Ljavax/swing/JRadioButton;Ljavax/swing/JRadioButton;Ljava/awt/event/ActionEvent;)V+347
j home.multimeida.mmconverter.MMConverterInterface$$Lambda+0x000002528c0c7778.actionPerformed(Ljava/awt/event/ActionEvent;)V+13
j javax.swing.AbstractButton.fireActionPerformed(Ljava/awt/event/ActionEvent;)V+84 java.desktop@21.0.5
j javax.swing.AbstractButton$Handler.actionPerformed(Ljava/awt/event/ActionEvent;)V+5 java.desktop@21.0.5
j javax.swing.DefaultButtonModel.fireActionPerformed(Ljava/awt/event/ActionEvent;)V+34 java.desktop@21.0.5
j javax.swing.DefaultButtonModel.setPressed(Z)V+117 java.desktop@21.0.5
j javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Ljava/awt/event/MouseEvent;)V+35 java.desktop@21.0.5
j java.awt.Component.processMouseEvent(Ljava/awt/event/MouseEvent;)V+64 java.desktop@21.0.5
j javax.swing.JComponent.processMouseEvent(Ljava/awt/event/MouseEvent;)V+23 java.desktop@21.0.5
J 2581 c1 java.awt.Component.processEvent(Ljava/awt/AWTEvent;)V java.desktop@21.0.5 (220 bytes) @ 0x00000252fa62719c [0x00000252fa627020+0x000000000000017c]
J 2580 c1 java.awt.Container.processEvent(Ljava/awt/AWTEvent;)V java.desktop@21.0.5 (22 bytes) @ 0x00000252fa627d9c [0x00000252fa627cc0+0x00000000000000dc]
J 2406 c1 java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@21.0.5 (785 bytes) @ 0x00000252fa670f14 [0x00000252fa670040+0x0000000000000ed4]
J 2325 c1 java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@21.0.5 (129 bytes) @ 0x00000252fa64e93c [0x00000252fa64e8a0+0x000000000000009c]
J 2608 c1 java.awt.LightweightDispatcher.retargetMouseEvent(Ljava/awt/Component;ILjava/awt/event/MouseEvent;)V java.desktop@21.0.5 (372 bytes) @ 0x00000252fa61c364 [0x00000252fa61b9e0+0x0000000000000984]
J 2578 c1 java.awt.LightweightDispatcher.processMouseEvent(Ljava/awt/event/MouseEvent;)Z java.desktop@21.0.5 (268 bytes) @ 0x00000252fa628a54 [0x00000252fa6284c0+0x0000000000000594]
J 2474 c1 java.awt.LightweightDispatcher.dispatchEvent(Ljava/awt/AWTEvent;)Z java.desktop@21.0.5 (73 bytes) @ 0x00000252fa699bbc [0x00000252fa699a60+0x000000000000015c]
J 2325 c1 java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@21.0.5 (129 bytes) @ 0x00000252fa64e914 [0x00000252fa64e8a0+0x0000000000000074]
J 2473 c1 java.awt.Window.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@21.0.5 (23 bytes) @ 0x00000252fa699654 [0x00000252fa6994e0+0x0000000000000174]
J 1838 c1 java.awt.EventQueue.dispatchEventImpl(Ljava/awt/AWTEvent;Ljava/lang/Object;)V java.desktop@21.0.5 (139 bytes) @ 0x00000252fa3bec64 [0x00000252fa3beb20+0x0000000000000144]
J 1837 c1 java.awt.EventQueue$4.run()Ljava/lang/Void; java.desktop@21.0.5 (60 bytes) @ 0x00000252fa3c0504 [0x00000252fa3c0460+0x00000000000000a4]
J 1836 c1 java.awt.EventQueue$4.run()Ljava/lang/Object; java.desktop@21.0.5 (5 bytes) @ 0x00000252fa3c0a04 [0x00000252fa3c09c0+0x0000000000000044]
J 1778 c1 java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;Ljava/security/AccessControlContext;)Ljava/lang/Object; java.base@21.0.5 (22 bytes) @ 0x00000252fa4601d4 [0x00000252fa45ffa0+0x0000000000000234]
J 1832 c1 java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V java.desktop@21.0.5 (80 bytes) @ 0x00000252fa44f14c [0x00000252fa44eae0+0x000000000000066c]
J 1846 c1 java.awt.EventDispatchThread.pumpOneEventForFilters(I)V java.desktop@21.0.5 (106 bytes) @ 0x00000252fa3ba544 [0x00000252fa3ba2e0+0x0000000000000264]
j java.awt.EventDispatchThread.pumpEventsForFilter(ILjava/awt/Conditional;Ljava/awt/EventFilter;)V+35 java.desktop@21.0.5
j java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+11 java.desktop@21.0.5
j java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4 java.desktop@21.0.5
j java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3 java.desktop@21.0.5
j java.awt.EventDispatchThread.run()V+9 java.desktop@21.0.5
v ~StubRoutines::call_stub 0x00000252fa08100d

siginfo: EXCEPTION_ACCESS_VIOLATION (0xc0000005), writing address 0x0000000000000000




If anyone has a perspective on this, it'd be appreciated.


The catch 22 in this project is that pre-creating the file is not a good idea, since avio_open has a purpose in-built method for that (I tried). Error checking everything about Java's File class in terms of setting pathways and creating and deleting files is not problematic. Likewise, permissions are all fine (Full Control in source and target folders) ; I've tested default C drive folders, which have restritions, to a separate volume and removable media, to no effect. Likewise, FFmpeg requires a forward slash, "/" in file paths, whereas Java does the backslash, generally. That's been handled with the replace method in the above conditioning, also to no effect.


The basic contradiction in the project seems to be that the error tries open a file that does not exist, with a valid source and destination file, and if I try to create a placeholder file wiht an acvhd extension at the event handling for the Convert button, it still errors out ; meanwhile, FFmpeg allegedly handles the file creation at its core, but requires a valid path to be passed ; I've tried with and without a filename, with and without an extension. I'm not able to resovle it.


The excessive error handling conditions are in an effort to isolate the problem, which I think I've done.


There also seems to be a compatibility between mpegts and acvhd, which is why I also had that format specified in the conversion function, without result.


I also have the idea to be able to do this without having to install any libraries locally or having to set path variables, which is an aspect that both GStreamer and FFmpeg have.


Nearest suggestion I've found is this : integrate ffmpeg with spring boot


AI remains hopeless for resolving this issue.


-
-
How to set output file while using subprocess.Popen and hide cmd window at the same time ?
2 mars 2021, par NandeI made a simple app that can convert video files using FFMpeg. I used Kivy for UI. I used
os.system()
to execute ffmpeg commands but while using this method, there is always a cmd window popping up. Therefore i am trying to usesubprocess.Popen()
to execute ffmpeg commands but i also want to save ffmpeg output to a text file.

I tried this but it didn't work :


subprocess.Popen(f"ffmpeg -i {path} -acodec {acodec} {output} > output.txt 2>&1", creationflags = 0x08000000, stdout="output.txt")



FFMpeg converts the video but there is no output.txt file. This code works with
os.system()


How can i hide cmd window while saving output to a text file ?


My full python code :


import os
from signal import SIGINT
import psutil
from time import sleep
from threading import Thread
from kivy.config import Config
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'width', '400')
Config.set('graphics', 'height', '330')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty

Window.clearcolor = (1, 1, 1, 1)

desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') + "\\"


def cmd(command):
 os.system(command)


def getpid(prcs):
 for proc in psutil.process_iter():
 try:
 pinf = proc.as_dict(attrs=["pid", "name"])
 if prcs.lower() in pinf["name"].lower():
 return pinf["pid"]
 except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
 return False
 return False


# noinspection PyGlobalUndefined
def progress(app, path):
 app.root.prgrss_bar.value = 0
 app.root.prgrss_lbl.text = "Progress: %0"

 if not os.getcwd().endswith("ffmpeg"):
 os.chdir("ffmpeg")

 inputpath = app.root.label.text
 if inputpath.startswith("Choose"):
 return
 audio = app.root.audio.state
 video = app.root.video.state
 both = app.root.both.state

 global line1
 global line2

 if video == "down" or both == "down":
 command = f"ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 {inputpath} > output2.txt 2>&1"
 os.system(command)
 ffprobe = open("output2.txt", "r")
 frames = int(ffprobe.read())

 control = True
 while control:
 sleep(0.5)

 with open(path, "r") as f:
 for last_line in f:
 pass
 line1 = last_line
 sleep(0.5)

 with open(path, "r") as f:
 for last_line in f:
 pass
 line2 = last_line
 if line1 == line2:
 app.root.prgrss_bar.value = 100
 app.root.prgrss_lbl.text = "Progress: Finished"
 control = False
 else:
 try:
 current_frame = int(line2.split("=")[1].split()[0])
 percentage = int(current_frame / frames * 100)
 text = f"Progress: %{percentage}"
 app.root.prgrss_lbl.text = text
 app.root.prgrss_bar.value = percentage
 if percentage == 100:
 control = False
 except ValueError or TypeError:
 pass

 elif audio == "down":
 command = f"ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {app.root.label.text} > output2.txt 2>&1"
 os.system(command)
 ffprobe = open("output2.txt", "r")
 duration = round(float(ffprobe.read()), 2)
 control = True
 while control:
 sleep(0.5)
 with open(path, "r") as f:
 for last_line in f:
 pass
 line1 = last_line
 sleep(0.5)

 with open(path, "r") as f:
 for last_line in f:
 pass
 line2 = last_line
 if line1 == line2:
 app.root.prgrss_bar.value = 100
 app.root.prgrss_lbl.text = "Progress: Finished"
 control = False
 else:
 try:
 current = line2.split("=")[2].split()[0].split(":")
 seconds = round((int(current[0]) * 3600) + (int(current[1]) * 60) + float(current[2]), 2)
 percentage = int(seconds / duration * 100)
 text = f"Progress: %{percentage}"
 app.root.prgrss_lbl.text = text
 app.root.prgrss_bar.value = percentage
 if percentage == 100:
 control = False
 except ValueError or TypeError:
 pass


class Window(Widget):

 @staticmethod
 def popup_open():
 popup = FolderPopup()
 popup.open()

 @staticmethod
 def exists_open():
 popup = Exists()
 popup.open()

 @staticmethod
 def choose_open():
 popup = ChooseFormat()
 popup.open()

 @staticmethod
 def path_popup():
 popup = ChoosePath()
 popup.open()

 @staticmethod
 def unsupported_audio():
 popup = UnsupportedAudio()
 popup.open()

 @staticmethod
 def no_video_format():
 popup = NoVideoFormat()
 popup.open()

 @staticmethod
 def no_process():
 popup = NoFFMPEGProcess()
 popup.open()

 def start(self, app):
 path = app.root.label.text
 if path.startswith("Choose"):
 self.path_popup()
 return

 outname = app.root.outname.text
 video_f = app.root.spinner.text
 audio_f = app.root.spinner2.text
 video = app.root.video.state
 audio = app.root.audio.state
 both = app.root.both.state

 audio_supported = {"MP4": ["AAC", "MP3", "Opus"],
 "MKV": ["AAC", "MP3", "Opus"],
 "MOV": ["AAC", "MP3"],
 "AVI": ["AAC", "MP3"],
 "WMV": ["AAC", "MP3"]}

 audio_ce = {"AAC": ["aac", ".m4a"],
 "MP3": ["libmp3lame", ".mp3"],
 "Opus": ["libopus", ".opus"],
 "WAV": ["pcm_u8", ".wav"],
 "Choose": ["Choose", "Choose"]}

 if not os.getcwd().endswith("ffmpeg"):
 os.chdir("ffmpeg")

 video_ext = video_f.lower()
 acodec = audio_ce[audio_f][0]
 audio_ext = audio_ce[audio_f][1]
 command = ""

 if (video == "normal" and audio == "normal" and both == "normal") or (
 video_f == "Choose" and audio_f == "Choose"):
 self.choose_open()
 return
 elif video == "down":
 if video_f == "Choose":
 self.no_video_format()
 return
 output = f"{desktop}{outname}.{video_ext}"
 if not os.path.exists(output):
 command += f"ffmpeg -i {path} -an {output} > output.txt 2>&1"
 else:
 self.exists_open()
 return
 elif audio == "down":
 output = f"{desktop}{outname}{audio_ext}"
 if not os.path.exists(output):
 command += f"ffmpeg -i {path} -vn -acodec {acodec} {output} > output.txt 2>&1"
 else:
 self.exists_open()
 return
 elif both == "down":
 if video_f == "Choose":
 self.no_video_format()
 return
 elif audio_f == "Choose":
 output = f"{desktop}{outname}.{video_ext}"
 if not os.path.exists(output):
 command += f"ffmpeg -i {path} {output} > output.txt 2>&1"
 else:
 self.exists_open()
 return
 else:
 if audio_f not in audio_supported[video_f]:
 self.unsupported_audio()
 return
 else:
 output = f"{desktop}{outname}.{video_ext}"
 if not os.path.exists(output):
 command += f"ffmpeg -i {path} -acodec {acodec} {output} > output.txt 2>&1"
 else:
 self.exists_open()
 return

 thrd = Thread(target=cmd, args=(command,))
 thrd.start()
 print("Thread started.")

 def stop(self):
 pid = getpid("ffmpeg")
 if not pid:
 self.no_process()
 else:
 os.kill(pid, SIGINT)

 def test_open(self, app):
 if not os.getcwd().endswith("ffmpeg"):
 os.chdir("ffmpeg")

 video = app.root.label.text
 if video.startswith("Choose"):
 return self.path_popup()

 command = f"ffplay {video}"
 os.system(command)

 @staticmethod
 def check_progress(app):
 path = os.getcwd() + r"\output.txt"
 chkprgrss = Thread(target=progress, args=(app, path,))
 chkprgrss.start()


class FolderPopup(Popup):
 dosya = ObjectProperty(None)
 desktop = desktop

 @staticmethod
 def no_path_submit():
 popup = NoPathSubmit()
 popup.open()

 def buton(self, app):

 try:
 app.root.label.text = self.dosya.selection[0]
 self.dismiss()
 except:
 self.no_path_submit()


class Exists(Popup):
 def buton(self):
 self.dismiss()


class ChooseFormat(Popup):
 def buton(self):
 self.dismiss()


class ChoosePath(Popup):
 def buton(self):
 self.dismiss()


class UnsupportedAudio(Popup):
 def buton(self):
 self.dismiss()


class NoVideoFormat(Popup):
 def buton(self):
 self.dismiss()


class NoPathSubmit(Popup):
 def buton(self):
 self.dismiss()


class NoFFMPEGProcess(Popup):
 def buton(self):
 self.dismiss()


class GUI(App):
 def build(self):
 return Window()


if __name__ == "__main__":
 GUI().run()



-
How to join AAC files with AVCONV CONCAT using an input txt file ?
26 mars 2015, par user27284I have a number of AAC files and want to concatenate them into one AAC file. When I do this with AVCONV at the command line and I am specific with the file names, it works. When I try to do this with a text file that holds a list of files, it fails. What led me here is the FFMPEG tutorial page at Concatenating media files. I get a variety of results depending on what I try and I cannot find any info on what I am doing wrong with the syntax.
My file list (list.txt in the same directory)...
file 'sr_program_2015_03_23_05_44_01.aac'
file 'sr_program_2015_03_23_07_44_58.aac'When I follow the example at the page I mentioned above, I get an error. I included both the use of ffmpeg AND avconv but the results are the same.
ffmpeg...
ffmpeg -f concat -i list.txt -c copy output
ffmpeg version 0.8.17-6:0.8.17-1, Copyright (c) 2000-2014 the Libav developers
built on Mar 15 2015 17:00:31 with gcc 4.7.2
The ffmpeg program is only provided for script compatibility and will be removed
in a future release. It has been deprecated in the Libav project to allow for
incompatible command line syntax improvements in its replacement called avconv
(see Changelog for details). Please use avconv instead.
Unknown input format: 'concat'avconv...
avconv -f concat -i list.txt -c copy output
avconv version 0.8.17-6:0.8.17-1, Copyright (c) 2000-2014 the Libav developers
built on Mar 15 2015 17:00:31 with gcc 4.7.2
Unknown input format: 'concat'When I remove the "-f" and use the filenames directly, it works. I have no idea why. The resulting file also plays as expected.
avconv -i concat:sr_program_2015_03_23_05_44_01.aac\|sr_program_2015_03_23_07_44_58.aac -c copy output.aac
avconv version 0.8.17-6:0.8.17-1, Copyright (c) 2000-2014 the Libav developers
built on Mar 15 2015 17:00:31 with gcc 4.7.2
[aac @ 0xcb6cc0] channel element 3.5 is not allocated
[aac @ 0xcb4b20] max_analyze_duration reached
[aac @ 0xcb4b20] Estimating duration from bitrate, this may be inaccurate
Input #0, aac, from 'concat:sr_program_2015_03_23_05_44_01.aac|sr_program_2015_03_23_07_44_58.aac':
Duration: 01:58:34.29, bitrate: 65 kb/s
Stream #0.0: Audio: aac, 44100 Hz, stereo, s16, 65 kb/s
Output #0, adts, to 'output.aac':
Metadata:
encoder : Lavf53.21.1
Stream #0.0: Audio: aac, 44100 Hz, stereo, 65 kb/s
Stream mapping:
Stream #0:0 -> #0:0 (copy)
Press ctrl-c to stop encoding
size= 57148kB time=7315.03 bitrate= 64.0kbits/s
video:0kB audio:57148kB global headers:0kB muxing overhead 0.000000%Noticing that the working approach does not use the ’-f’ option, I tried that again with my first attempt and got a completely different error.
avconv concat -i list.txt -c copy output.aac
avconv version 0.8.17-6:0.8.17-1, Copyright (c) 2000-2014 the Libav developers
built on Mar 15 2015 17:00:31 with gcc 4.7.2
Unable to find a suitable output format for 'concat'The reason I want to process these ’broken stream’ aac files from a file list in a file is because I want to create the list from a script/code and then process it as part of a daily automated process. When the streams have broken, there are numerous files with the same date. When all goes well, there is only one file. It happens every other week or so. I want to automate the fix that I usually do manually. I have already accomplished creating the target file list, ironically, from examples on the same page mentioned above when I became stuck with this odd behavior.
I also want to know what it is I am doing wrong. I see the example I used first everywhere. I have tried this on two different machines running debian but different architectures (arm and x86) and received the same results.
Also, to make sure I had the latest ffmeg, I compiled it on each system using this page... Compile FFmpeg on Ubuntu, Debian, or Mint
Thank you for your time.