Xugller illegalArgumentExeception - converters

I'm try to convert a movie (.mp4) in audio (.mp3) with Xuggler. I use porcessing on OS X.
IMediaReader reader = ToolFactory.makeReader("/Users/nouv/Desktop/video1.mp4");
IMediaWriter writer = ToolFactory.makeWriter("/Users/nouv/Desktop/audioOutput.mp3", reader);
int sampleRate = 22050;
int channels = 1;
writer.addAudioStream(0, 0, ICodec.ID.CODEC_ID_MP3, channels, sampleRate);
reader.addListener(writer);
try {
while (reader.readPacket() == null)
;
} finally {}
I have this error : IllegalArgumentException : stream[0] is not video
Exception in thread "Animation Thread" java.lang.IllegalArgumentException: stream[0] is not video
at com.xuggle.mediatool.MediaWriter.encodeVideo(MediaWriter.java:754)
at com.xuggle.mediatool.MediaWriter.encodeVideo(MediaWriter.java:783)
at com.xuggle.mediatool.MediaWriter.onVideoPicture(MediaWriter.java:1434)
at com.xuggle.mediatool.AMediaToolMixin.onVideoPicture(AMediaToolMixin.java:166)
at com.xuggle.mediatool.MediaReader.dispatchVideoPicture(MediaReader.java:610)
at com.xuggle.mediatool.MediaReader.decodeVideo(MediaReader.java:519)
at com.xuggle.mediatool.MediaReader.readPacket(MediaReader.java:475)
at xuggle.setup(xuggle.java:135)
at processing.core.PApplet.handleDraw(PApplet.java:2117)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:193)
at processing.core.PApplet.run(PApplet.java:2020)
at java.lang.Thread.run(Thread.java:680)
I tried with .mp4 , .mov and .flv movie and I have the same error.

IContainer container = IContainer.make();
int result = container.open(inputFilename, IContainer.Type.READ, null);
// check if the operation was successful
if (result<0)
throw new RuntimeException("Failed to open media file");
int numStreams = container.getNumStreams();
int audioStreamId = -1;
IContainer writer = IContainer.make();
writer.open(outputFilename, IContainer.Type.WRITE, IContainerFormat.make());
for (int i=0; i<numStreams; i++) {
IStream stream = container.getStream(i);
IStreamCoder coder = stream.getStreamCoder();
IStreamCoder audioCoder = IStreamCoder.make(IStreamCoder.Direction.ENCODING, coder);
if( coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO){
coder.open(IMetaData.make(), IMetaData.make());
audioStreamId = i;
ICodec inputCodec = ICodec.findDecodingCodec(ICodec.ID.CODEC_ID_MP3);
if (inputCodec == null)
throw new IllegalArgumentException("could not find input codec id");
if (audioStreamId == -1)
throw new RuntimeException("could not find audio stream in container: "+inputFilename);
writer.addNewStream(audioCoder);
if(writer.writeHeader() == 0)
{
IPacket packet = IPacket.make();
while(container.readNextPacket(packet) >= 0){
if(packet.getStreamIndex() == audioStreamId)
{
if(coder.isOpen()){
writer.writePacket(packet);
} else {throw new RuntimeException("Could not open Coder"); }
}
}
}else {throw new RuntimeException("Header not Written for writer container.");}
}
coder.close(); audioCoder.close();
}
writer.writeTrailer();
writer.close();
hope this helps... :)

Related

Using AUGraph in Xamarin.Mac

I'm trying to get the following example working in a Xamarin.Mac project.
It's an AUGraph that connects a mixer to the default output. The mixer has one input which is a render callback that generates a sine wav.
var graph = new AUGraph();
var output = graph.AddNode(AudioComponentDescription.CreateOutput(AudioTypeOutput.Default));
var mixer = graph.AddNode(AudioComponentDescription.CreateMixer(AudioTypeMixer.MultiChannel));
if (graph.TryOpen() != 0)
{
throw new Exception();
}
var mixNode = graph.GetNodeInfo(mixer);
// configure mixer
if (mixNode.SetElementCount(AudioUnitScopeType.Input, 1) != AudioUnitStatus.OK)
{
throw new Exception();
}
if (mixNode.SetRenderCallback(HandleRenderDelegate, AudioUnitScopeType.Global, 0) != AudioUnitStatus.OK)
{
throw new Exception();
}
var outNode = graph.GetNodeInfo(output);
// define stream description
var desc = new AudioStreamBasicDescription();
desc.BitsPerChannel = 32;
desc.BytesPerFrame = 4;
desc.BytesPerPacket = 4;
desc.Format = AudioFormatType.LinearPCM;
desc.FormatFlags = AudioStreamBasicDescription.AudioFormatFlagsAudioUnitNativeFloat;
desc.FramesPerPacket = 1;
desc.ChannelsPerFrame = 2;
desc.SampleRate = 44100;
// set mixer input format
if (mixNode.SetFormat(desc, AudioUnitScopeType.Input, 0) != AudioUnitStatus.OK)
{
throw new Exception();
}
// connect mixer's output to the output
if (graph.ConnnectNodeInput(mixer, 0, output, 0) != AUGraphError.OK)
{
throw new Exception();
}
// set format of mixer's output
desc = mixNode.GetAudioFormat(AudioUnitScopeType.Output);
desc.SampleRate = 44100;
if (outNode.SetFormat(desc, AudioUnitScopeType.Input,0) != AudioUnitStatus.OK)
{
throw new Exception();
}
if (mixNode.SetFormat(desc, AudioUnitScopeType.Output) != AudioUnitStatus.OK)
{
throw new Exception();
}
if (graph.Initialize() != AUGraphError.OK)
{
throw new Exception();
}
if (graph.Start() != AUGraphError.OK)
{
throw new Exception();
}
The callback:
int sample = 0;
unsafe AudioUnitStatus HandleRenderDelegate(AudioUnitRenderActionFlags actionFlags, AudioTimeStamp timeStamp, uint busNumber, uint numberFrames, AudioBuffers data)
{
var left = (float*)data[0].Data;
var right = (float*)data[1].Data;
for (var i = 0; i < numberFrames; i++)
{
float sampleValue = (float)Math.Sin(sample * 2 * Math.PI * 440 / 44100);
left[i] = right[i] = sampleValue;
sample++;
}
return AudioUnitStatus.OK;
}
The callback is running and the buffer is being filled but no sound is generated. The example works in iOS with AudioTypeOutput.Remote being used in place of AudioTypeOutput.Default but for some reason macOS is not playing the sound. Any ideas?
The output volume of the mixer had to be set manually because it defaults to 0.

"Parameter is not valid" error when extracting images using iTextSharp from a PDF containing JPXDecode filter

I am trying to extract images from a PDF using the following code. It works well for some filters like DCTDecode , but is not working for JPXDEcode ."Parameter not valid " error occurs at the point image.GetDrawingImage() is called.
using System.Drawing.Imaging;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
...
PdfReader pdf = new PdfReader(currfilename);
PdfReaderContentParser parser = new PdfReaderContentParser(pdf);
ImageRender listener = new ImageRender();
for (int i = 1; i <= pdf.NumberOfPages; i++)
{
try
{
parser.ProcessContent(i, listener);//calls RenderImage() at this point
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public void RenderImage(ImageRenderInfo renderInfo)
{
PdfImageObject image = renderInfo.GetImage();
PdfName filter = image.Get(PdfName.FILTER) as PdfName;
if (renderInfo.GetRef() != null && image != null)
{
using (System.Drawing.Image dotnetImg = image.GetDrawingImage())//exception occurs at this point
{
if (dotnetImg != null)
{
ImageNames.Add(string.Format("{0}.tiff", renderInfo.GetRef().Number));
using (MemoryStream ms = new MemoryStream())
{
dotnetImg.Save(ms, ImageFormat.Tiff);
Images.Add(ms.ToArray());
}
}
}
}
}
I tried these links for a solution
Extract images using iTextSharp
Extract Image from a particular page in PDF
and was able to extract the raw image bytes using PdfReader.GetStreamBytesRaw() function but "Parameter not valid "exception always occurs at the point where System.Drawing.Image.FromStream(memory stream) is called.
I also checked this link "Parameter is not valid" exception from System.Drawing.Image.FromStream() method , but could not find anything helpful.
Please help
The JPXDecode filter corresponds to JPEG 2000 compression, which is not supported by .net framework. This other question in SO may help: JPEG 2000 support in C#.NET
Using FreeImage.dll solved the problem. The code is as follows
using FreeImageAPI;
using System.Drawing.Imaging;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
...
imagecount = 0;
PdfReader pdf = new PdfReader(currfilename);
PdfReaderContentParser parser = new PdfReaderContentParser(pdf);
ImageRender listener = new ImageRender();
for (int i = 1; i <= pdf.NumberOfPages; i++)
{
try
{
parser.ProcessContent(i, listener);//calls RenderImage() at this point
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
if (listener.Images.Count > 0)
{
for (int j = 0; (j < listener.Images.Count); ++j)
{
string imgpath = Environment.CurrentDirectory.ToString() + "\\Image" + imagecount + ".bmp";
// create a memory stream
MemoryStream imageStream = new MemoryStream(listener.Images[j]);
// create a FIBITMAP from that stream
FIBITMAP dib = FreeImage.LoadFromStream(imageStream);
if (dib.IsNull) continue;
//turn it into a normal Bitmap
Bitmap bitmap = FreeImage.GetBitmap(dib);
bitmap.Save(imgpath);
//unload the FIBITMAP
FreeImage.UnloadEx(ref dib);
bitmap.Dispose();
System.Drawing.Image img = System.Drawing.Image.FromFile(imgpath);
}
public void RenderImage(ImageRenderInfo renderInfo)
{
PdfImageObject image = renderInfo.GetImage();
if (renderInfo.GetRef() != null && image != null)
{
byte[] tempImage = image.GetImageAsBytes();
ImageNames.Add(string.Format("0}.bmp",renderInfo.GetRef().Number));
Images.Add(tempImage);
}
}
I followed the instructions given here to add FreeImage .Net to solution

To Extract .7zip file using SharpCompress library in windows phone but getting exception

IArchive archive = null;
IReader reader = null;
archive = SevenZipArchive.Open(fileStream, Options.LookForHeader);
reader = archive.ExtractAllEntries();
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Stream _redaer = new MemoryStream();
reader.WriteEntryTo(_redaer);
fileName = reader.Entry.FilePath;
int index = fileName.LastIndexOf("/");
string file = fileName.Substring(index + 1, (fileName.Length - (index + 1)));
using (binaryReader = new BinaryReader(_redaer, encoding))
{
long fileLength = _redaer.Length;
MemoryStream ms = new MemoryStream();
_redaer.Position = 0;
_redaer.CopyTo(ms);
byte[] buteArray = ms.ToArray();
SaveToIsoStore(fileName, buteArray);
}
}
}
This code gives exception of type SharpCompress.Common.InvalidFormatException,Please provide the solution in wp7.

j2me midlet chinese character display message garbled

My J2ME midlet could retrieves message in Chinese character from a PHP server but it's garbled. The server basically returns the response string and by detecting the first 2 characters. AA = good, anything else indicates error of which the message is to be passed to the calling function for display
InputStream is = null;
StringBuffer sb = null;
String str = "";
HttpConnection http = null;
DataOutputStream dos = null;
try
{
URL = login.getURL();
URL += ctlFunction + "/" + uriStr;
URL = EncodeURL(URL);
//System.out.println(URL);
if(!ctlFunction.equals("login"))
{
msg += "&user=" + login.getUsername();
msg += "&token=" + login.getToken();
}
msg += "&lang=" + System.getProperty("microedition.locale");
// establish the connection
http = (HttpConnection) Connector.open(URL);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Content-length", ""+EncodeURL(msg).getBytes().length);
dos = http.openDataOutputStream();
byte[] request_body = EncodeURL(msg).getBytes();
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// server response
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
is = http.openDataInputStream();
int length = (int) http.getLength();
if (length != -1)
{
// Read data in one chunk
byte serverData[] = new byte[length];
is.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
}
else
{
networkError();
}
}
catch (Exception e)
{
System.err.println("Error3: " + e.toString());
networkError(e.toString());
}
finally
{
if (is != null)
is.close();
if (!str.equals(""))
post = str;
else
networkError();
if (http != null)
http.close();
}
if (post != null)
{
String fate = post.substring(0, 2);
if(fate.equals("AA"))
{
if(ctlFunction.equals("login"))
{
String rawPost = post.substring(2);
Vector v = new Vector();
int index = 0;
//find the first occurrence of the SPLITTER
int endIndex = rawPost.indexOf(SPLITTER, index);
String item = "";
//extract the items until the end of the last SPLITTER found in the rawPost string
while(endIndex != -1)
{
item = rawPost.substring(index, endIndex);
index = endIndex + 1;
endIndex = rawPost.indexOf(SPLITTER, index);
v.addElement(item);
}
//extract the rest of the rawPost (the text item)
item = rawPost.substring(index);
v.addElement(item);
String[] ret = new String[v.size()];
v.copyInto(ret);
login.setToken(ret[0]);
login.setToday(ret[1]);
login.setNextDrawDay(ret[2]);
}
midlet.returnResults(post.substring(2), getCurrentDisplay(), ctlFunction);
}
else
{
String errmessage = post.substring(2);
System.out.println(post);
midlet.showInfo(post, getCurrentDisplay());
}
}
else
{
networkError();
}
On the PHP server, I have set the header to UTF-8 encoding
<?php header("Content-Type:text/plain; charset=utf-8"); ?>
What could possibly be wrong?
I found that this user has the same problem and it's been answered
Reading UTF8 strings from a server through http using MIDP. Kudos to the answer.
I basically edited my MIDP code from
// is = http.openDataInputStream();
// int length = (int) http.getLength();
// if (length != -1)
// {
// // Read data in one chunk
// byte serverData[] = new byte[length];
// is.read(serverData);
// str = new String(serverData);
// }
// else // Length not available...
// {
// ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
// int ch;
// while ((ch = is.read()) != -1)
// bStrm.write(ch);
//
// str = new String(bStrm.toByteArray());
// bStrm.close();
// }
to
Reader r = new InputStreamReader(http.openInputStream(), "UTF-8");
int ch;
while((ch = r.read()) != -1)
str = str + (char)ch;
just wondering though why does reading bytes messes up the UTF-8 characters?

i want to play music from webSite with the Mediaelement ," media.setSource()"

i get the stream from webSite ,then put it in isolatedStorage into IsolatedstorageStream ,
but it don't work ,no error no sound , what's wrong ????
HttpWebResponse reponse = request.EndGetResponse(result) as HttpWebResponse;
if (reponse.StatusCode == HttpStatusCode.OK)
{
Stream stream=reponse.GetResponseStream();
SaveMusic(stream, "music");
ReadMusic("music");
Deployment.Current.Dispatcher.BeginInvoke(
() =>
{
me.AutoPlay = true;
me.Volume = 100;
me.SetSource(songStream);
me.Play();
});
}
ok thanks keyboardP for your help ;here is my code
protected void SaveMusic(Stream stream,string name)
{
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!fileStorage.DirectoryExists("Source/Music"))
{
fileStorage.CreateDirectory("Source/Music");
}
using (IsolatedStorageFileStream fileStream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("Source\\Music\\" + name + ".mp3", FileMode.Create))
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Flush();
}
}
protected void ReadMusic(string name)
{
using (IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
songStream = null;
songStream = new IsolatedStorageFileStream("Source\\Music\\" + name + ".mp3", FileMode.Open, fileStorage);
}
}
Assuming your saving and reading code is correct, your stream's position might be at the end. Try adding
songStream.Position = 0;
before SetSource(songStream);
Try using this to save the file:
using (var fileStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
var buffer = new byte[1024];
using (var myIsStream = fileStorage.OpenFile("Source\\Music\\" + name + ".mp3", FileMode.CreateNew))
{
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, 1024)) > 0)
myIsStream.Write(buffer, 0, bytesRead);
}
}

Resources