Insert 360° metadata to mp4 file in java - java

I'm trying to add 360° metadata to a mp4 file with this library : https://github.com/copiousfreetime/mp4parser
after have check the code, i had created this :
public void injectSphericalMetaV2(TrackBox trackBox) throws IOException {
String sphericalVideoGlobalMetadata = "<rdf:SphericalVideo xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"xmlns:GSpherical=\"http://ns.google.com/videos/1.0/spherical/\"><GSpherical:Spherical>true</GSpherical:Spherical><GSpherical:Stitched>true</GSpherical:Stitched><GSpherical:StitchingSoftware>GIROPTIC 360 CAM</GSpherical:StitchingSoftware><GSpherical:ProjectionType>equirectangular</GSpherical:ProjectionType></rdf:SphericalVideo>";
String UUID_ID = "FFCC8263-F855-4A93-8814-587A02521FDD";
UserBox sphericalAtom = new UserBox(UUID_ID.getBytes());
sphericalAtom.setData(sphericalVideoGlobalMetadata.getBytes());
trackBox.addBox(sphericalAtom);
}
and i execute it here :
protected TrackBox createTrackBox(Track track, Movie movie, Map<Track, int[]> chunks) {
TrackBox trackBox = new TrackBox();
TrackHeaderBox tkhd = new TrackHeaderBox();
tkhd.setEnabled(true);
tkhd.setInMovie(true);
tkhd.setMatrix(track.getTrackMetaData().getMatrix());
tkhd.setAlternateGroup(track.getTrackMetaData().getGroup());
tkhd.setCreationTime(track.getTrackMetaData().getCreationTime());
if (track.getEdits() == null || track.getEdits().isEmpty()) {
tkhd.setDuration(track.getDuration() * getTimescale(movie) / track.getTrackMetaData().getTimescale());
} else {
long d = 0;
for (Edit edit : track.getEdits()) {
d += (long) edit.getSegmentDuration();
}
tkhd.setDuration(d * track.getTrackMetaData().getTimescale());
}
tkhd.setHeight(track.getTrackMetaData().getHeight());
tkhd.setWidth(track.getTrackMetaData().getWidth());
tkhd.setLayer(track.getTrackMetaData().getLayer());
tkhd.setModificationTime(new Date());
tkhd.setTrackId(track.getTrackMetaData().getTrackId());
tkhd.setVolume(track.getTrackMetaData().getVolume());
trackBox.addBox(tkhd);
trackBox.addBox(createEdts(track, movie));
MediaBox mdia = new MediaBox();
trackBox.addBox(mdia);
MediaHeaderBox mdhd = new MediaHeaderBox();
mdhd.setCreationTime(track.getTrackMetaData().getCreationTime());
mdhd.setDuration(track.getDuration());
mdhd.setTimescale(track.getTrackMetaData().getTimescale());
mdhd.setLanguage(track.getTrackMetaData().getLanguage());
mdia.addBox(mdhd);
HandlerBox hdlr = new HandlerBox();
mdia.addBox(hdlr);
hdlr.setHandlerType(track.getHandler());
MediaInformationBox minf = new MediaInformationBox();
if (track.getHandler().equals("vide")) {
try {
injectSphericalMetaV2(trackBox);
} catch (IOException e) {
e.printStackTrace();
}
minf.addBox(new VideoMediaHeaderBox());
} else if (track.getHandler().equals("soun")) {
minf.addBox(new SoundMediaHeaderBox());
} else if (track.getHandler().equals("text")) {
minf.addBox(new NullMediaHeaderBox());
} else if (track.getHandler().equals("subt")) {
minf.addBox(new SubtitleMediaHeaderBox());
} else if (track.getHandler().equals("hint")) {
minf.addBox(new HintMediaHeaderBox());
} else if (track.getHandler().equals("sbtl")) {
minf.addBox(new NullMediaHeaderBox());
}
// dinf: all these three boxes tell us is that the actual
// data is in the current file and not somewhere external
DataInformationBox dinf = new DataInformationBox();
DataReferenceBox dref = new DataReferenceBox();
dinf.addBox(dref);
DataEntryUrlBox url = new DataEntryUrlBox();
url.setFlags(1);
dref.addBox(url);
minf.addBox(dinf);
Box stbl = createStbl(track, movie, chunks);
minf.addBox(stbl);
mdia.addBox(minf);
LOG.logDebug("done with trak for track_" + track.getTrackMetaData().getTrackId());
return trackBox;
}
these 2 methods are in my MP4BuilderV2 and i call it here a TrimActivity like this :
Container out = new DefaultMp4BuilderV2().build(movie);
MovieHeaderBox mvhd = Path.getPath(out, "moov/mvhd");
mvhd.setMatrix(Matrix.ROTATE_180);
if (!dst.exists()) {
dst.createNewFile();
} else {
dst.delete();
dst.createNewFile();
}
FileOutputStream fos = new FileOutputStream(dst);
WritableByteChannel fc = fos.getChannel();
try {
out.writeContainer(fc);
}catch (Exception e) {
Log.e("erreur", e.toString());
}finally {
fc.close();
fos.close();
file.close();
}
file.close();
But in the last try/catch i get this error : java.nio.BufferOverflowException
If someone has the solution thanks in advance

I was with the same problem as you, searching for a solution I found a meta tag insertion implementation that worked for me, maybe it helps you.

Related

Flatbuffer writing in binary file in android give only single response

I am new at flatbuffer. I had created a schema file from outside the project and adding the user(Monster as in Flatbuffer document) inside the binary via java code in android. everything works fine. but the time of reading binary file data it only gives me the user length 1. I had added 3 people but it's give me the length of monsters is 1 at the time of reading. can anyone help to figure this out. Here is the code->
this is the full code ->
enter code here
builder = new FlatBufferBuilder(1024);
public void addNewData(String emailOffset, String nameOffset,String
contactNoOffset, String DOJOffset, String departmentOffset,
String empIdOffset, float[] embeddingOffset)
{
int storeembedd = SingleJson.createEmbeddingVector(builder,
embeddingOffset);
int hereEmailOffset = builder.createString(emailOffset);
int hereNameOffset = builder.createString(nameOffset);
int hereContactOffset = builder.createString(contactNoOffset);
int hereDOJOffset = builder.createString(DOJOffset);
int hereDepartmentOffset=builder.createString(departmentOffset);
int hereImpIdOffset = builder.createString(empIdOffset);
int test = SingleJson.createSingleJson(builder, hereEmailOffset,
hereNameOffset, hereContactOffset
, hereDOJOffset, hereDepartmentOffset, hereImpIdOffset,
storeembedd);
int [] offsetOfMonster = new int[1];
offsetOfMonster[0] = test;
int temp = Monsters.createMonstersVector(builder,
offsetOfMonster);
Monsters.startMonsters(builder);
Monsters.addMonsters(builder, temp);
int orc = Monsters.endMonsters(builder);
builder.finish(orc);
byte[] buf1 = builder.sizedByteArray();
openAndAppenedInBinary(buf1);
}
private void openAndAppenedInBinary(byte[] buf1) {
FileOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(newFile());
byte[] buffer = new byte[inputStream.available()];
if (inputStream.available() == 0) {
output = new FileOutputStream(newFile(), true);
output.write(buf1);
} else {
while (inputStream.read(buffer) != -1) {
output = new FileOutputStream(newFile(), true);
output.write(buffer);
output.write(buf1);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String newFile() {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getPackageName()
+ "/binFile");
if (!file.exists()) {
if (!file.mkdir()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
Path dir = Paths.get(file.getAbsolutePath());
Files.createDirectory(dir);
} catch (IOException e) {
Path parentDir = Paths.get(file.getParent());
if (!Files.exists(parentDir)) {
try {
Files.createDirectories(parentDir);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
File binFile = new File(file, "renamed.bin");
try {
FileWriter writer = new FileWriter(binFile);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
return binFile.getAbsolutePath();
}
here is my reading code of flatbiffer->
new FlatParsingForPerticularId().execute(readRawResource(R.raw.renamed));//renamed is my bin file
private class FlatParsingForPerticularId extends AsyncTask {
#Override
protected String doInBackground(Object... params) {
byte[] buffer = (byte[]) params[0];
long startTime = System.currentTimeMillis();
ByteBuffer bb = ByteBuffer.wrap(buffer);
Monsters monsterList = Monsters.getRootAsMonsters(bb);
int length = monsterList.monstersLength();
SingleJson monster = null;
for (int i = 0; i < length; i++) {//here I m getting length 1 intead of 3
monster = monsterList.monsters(i);
if (i == outputval[0]) {
outputval[0] = (int) monster.EmpNo();
break;
}
}
long endTime = System.currentTimeMillis() - startTime;
String textToShow = "Elements: " + monsterList.monstersLength() + ": load time: " + endTime + "ms";
String[] monsterArr = monster.Name().split(" ");
return monsterArr[0];
}

Thrown IllegalArgumentException when using java.nio

Trying to download file by url. For that using java.nio library. The code above work perfect for sdk 24 and above but getting IllegalArgumentException for android sdk 23 and below. I'm getting the error when trying transfer the data. Dear Friends can you please clarify which is the problem.
private void downloadFile(final String itemUrl) {
new Thread(new Runnable() {
#Override
public void run() {
ReadableByteChannel readableByteChannel = null;
FileOutputStream fOutStream = null;
String root =
getApplicationContext().getApplicationInfo().dataDir;
File myDir = new File(root + "/downloadedSongs");
if (!myDir.exists()) {
myDir.mkdirs();
}
File file = new File(myDir, itemTitle);
if (file.exists()) {
file.delete();
}
try {
URL url = new URL(itemUrl);
readableByteChannel =
Channels.newChannel(url.openStream());
fOutStream = new FileOutputStream(file);
fOutStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
} catch (IOException e) {
orderAction = Enums.OrderAction.Delete;
} catch (IllegalArgumentException e) {
orderAction = Enums.OrderAction.Delete;
Crashlytics.logException(e);
} finally {
try {
if (fOutStream != null) {
fOutStream.close();
}
if (readableByteChannel != null) {
readableByteChannel.close();
}
} catch (IOException ioExObj) {
orderAction = Enums.OrderAction.Delete;
}
closeNotification(orderAction);
}
}
}).start();
}
Fatal Exception: java.lang.IllegalArgumentException: position=0 count=9223372036854775807 at java.nio.FileChannelImpl.transferFrom(FileChannelImpl.java:370) at am.itsoft.youtomp3.services.DnlService$1.run(DnlService.java:169) at java.lang.Thread.run(Thread.java:818)
The reason is in this argument: Long.MAX_VALUE
Right code:
FileChannel destChannel = fOutStream.getChannel();
long blockSize;
if (Build.VERSION.SDK_INT > 23) {
long blockSize = Long.MAX_VALUE;
} else {
long blockSize = 8*1024;
}
long position = 0;
long loaded;
while ((loaded = destChannel.transferFrom(readableByteChannel, position, blockSize)) > 0) {
position += loaded;
}

use array output in other class

Good day!
I have a method which returns me an array of report names
System.out.println(bc[i].getDefaultName().getValue()
i want to use array output in other class, how i need to linked method outpud in my array in other class?
Method is:
public class ReoprtSearch {
public void executeTasks() {
PropEnum props[] = new PropEnum[] { PropEnum.searchPath, PropEnum.defaultName};
BaseClass bc[] = null;
String searchPath = "//report";
//searchPath for folder - //folder, report - //report, folder and report - //folder | //report
try {
SearchPathMultipleObject spMulti = new SearchPathMultipleObject(searchPath);
bc = cmService.query(spMulti, props, new Sort[] {}, new QueryOptions());
} catch (Exception e) {
e.printStackTrace();
return;
}
if (bc != null) {
for (int i = 0; i < bc.length; i++) {
System.out.println(bc[i].getDefaultName().getValue();
}
}
}
}
array in what i want put the array looks like:
String [] folders =
my trying like:
ReoprtSearch search = new ReoprtSearch();
String [] folders = {search.executeTasks()};
Returns me an error: cannot convert from void to string
Give me an explanations to understand how i can related to method output from other class.
Thanks
The problem is that your executeTasks method doesn't actually return anything (which is why it's void), and just prints to stdout. Instead of printing, add the names to an array and then return it. Something like this:
public class ReoprtSearch {
public String[] executeTasks() {
PropEnum props[] = new PropEnum[] { PropEnum.searchPath, PropEnum.defaultName};
BaseClass bc[] = null;
String searchPath = "//report";
//searchPath for folder - //folder, report - //report, folder and report - //folder | //report
try {
SearchPathMultipleObject spMulti = new SearchPathMultipleObject(searchPath);
bc = cmService.query(spMulti, props, new Sort[] {}, new QueryOptions());
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (bc != null) {
String results[] = new String[bc.length];
for (int i = 0; i < bc.length; i++) {
results[i] = bc[i].getDefaultName().getValue();
}
return results;
}
return null;
}
}

OrientDB slow when browsing cluster

Well what i am trying to achieve is to save pairs of words in a sentence and if the word is already there , i am trying to save a list of words against one.
To save the pairing as there could many millions as my data set file is very large , i opted for orientdb. I dont know if i am approaching it correctly but orientdb is very slow. After 8 hours of running it has only made pairs for 12000 sentences.
As far as i have checked the major slowdown was in browsing cluster.
Attached is my code, please if ant one can give any pointers over my approach.
public static void main(String[] args) {
// TODO Auto-generated method stub
Main m = new Main();
m.openDatabase();
m.readFile("train_v2.txt");
m.closeDatabase();
}
}
class Main {
ODatabaseDocumentTx db;
Map<String, Object> index;
List<Object> list = null;
String pairing[];
ODocument doc;
Main() {
}
public void closeDatabase() {
if (!db.isClosed()) {
db.close();
}
}
void openDatabase() {
db = new ODatabaseDocumentTx("local:/databases/model").open("admin",
"admin");
doc = new ODocument("final");
}
public void readFile(String filename) {
InputStream ins = null; // raw byte-stream
Reader r = null; // cooked reader
int i = 1;
BufferedReader br = null; // buffered for readLine()
try {
String s;
ins = new FileInputStream(filename);
r = new InputStreamReader(ins, "UTF-8"); // leave charset out
// for
// default
br = new BufferedReader(r);
while ((s = br.readLine()) != null) {
System.out.println("" + i);
createTermPair(s.replaceAll("[^\\w ]", "").trim());
i++;
}
} catch (Exception e) {
System.err.println(e.getMessage()); // handle exception
} finally {
closeDatabase();
if (br != null) {
try {
br.close();
} catch (Throwable t) { /* ensure close happens */
}
}
if (r != null) {
try {
r.close();
} catch (Throwable t) { /* ensure close happens */
}
}
if (ins != null) {
try {
ins.close();
} catch (Throwable t) { /* ensure close happens */
}
}
}
}
private void createTermPair(String phrase) {
phrase = phrase + " .";
String[] word = phrase.split(" ");
for (int i = 0; i < word.length - 1; i++) {
if (!word[i].trim().equalsIgnoreCase("")
&& !word[i + 1].trim().equalsIgnoreCase("")) {
String wordFirst = word[i].toLowerCase().trim();
String wordSecond = word[i + 1].toLowerCase().trim();
String pair = wordFirst + " " + wordSecond;
checkForPairAndWrite(pair);
}
}
}
private void checkForPairAndWrite(String pair) {
try {
pairing = pair.trim().split(" ");
if (!pairing[1].equalsIgnoreCase(" ")) {
index = new HashMap<String, Object>();
for (ODocument docr : db.browseCluster("final")) {
list = docr.field(pairing[0]);
}
if (list == null) {
list = new ArrayList<>();
}
list.add("" + pairing[1]);
if (list.size() >= 1)
index.put(pairing[0], list);
doc.fields(index);
doc.save();
}// for (int i = 0; i < list.size(); i++) {
// System.out.println("" + list.get(i));
// }
} catch (Exception e) {
}
return;
}
}

Extracting files in .iso using jSevenZip

I'm trying to extract the files in an .iso file I have. There are no errors and the console prints out all the files inside. However, none of the files get extracted. Any help is greatly appreciated!
I was able to find this link but I can't seem to integrate it in to my project.
Link to code example
class DownloadWorker extends SwingWorker<String, Object> {
private String flocation;
private JLabel out;
public DownloadWorker(String location, JLabel fout)
{
this.flocation = location;
this.out = fout;
}
#Override
public String doInBackground() {
//download here
out.setText("Beginning download. This may take a few minutes.");
try {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(flocation);
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.iso";
String LOCAL_FILE = (flocation + "\\ProfessorPhys\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists())
System.out.println("Directory created!");
}
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(localfile +"\\ProfessorPhys.iso\\", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
return "done";
}
#Override
protected void done() {
//done
out.setText(out.getText() + "\n Operation Done");
}
}
Code I'm trying to implement:
public class ExtractorUtil {
private static Logger logger = Logger.getLogger(ExtractorUtil.class.getCanonicalName());
public static void extract(File file, String extractPath) throws Exception {
ISevenZipInArchive inArchive = null;
RandomAccessFile randomAccessFile = null;
randomAccessFile = new RandomAccessFile(file, "r");
inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
inArchive.extract(null, false, new MyExtractCallback(inArchive, extractPath));
if (inArchive != null) {
inArchive.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
public static class MyExtractCallback implements IArchiveExtractCallback {
private final ISevenZipInArchive inArchive;
private final String extractPath;
public MyExtractCallback(ISevenZipInArchive inArchive, String extractPath) {
this.inArchive = inArchive;
this.extractPath = extractPath;
}
#Override
public ISequentialOutStream getStream(final int index, ExtractAskMode extractAskMode) throws SevenZipException {
return new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
String filePath = inArchive.getStringProperty(index, PropID.PATH);
FileOutputStream fos = null;
try {
File dir = new File(extractPath);
File path = new File(extractPath + filePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (!path.exists()) {
path.createNewFile();
}
fos = new FileOutputStream(path, true);
fos.write(data);
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
}
}
return data.length;
}
};
}

Categories

Resources