Of course you could send video-Data in JSON, but since JSON is essentially a String-Format with several reserved Characters you will have to encode the video-data. You could use any scheme you like - but BASE64 is a widely accepted Standard so I would use it.
Just create a JSON-String object and fill it with the BASE-64 encoded Video Data.
But beware of Buffer-Overflows!!! Because many JSON-Implementations will usually not expect giant Data-Elements in JSON it may be advisable to break the Data-Stream into several smaller Chunks and deliver them one at a time... Of course you could also just stream the JSON-Data itself, but as far as I know most JSON Stacks operate serially, since you can only parse a valid JSON-String if it is complete.
So the best thing performance wise (if you REALLY WANT to pack the video Data into JSON, which is clearly not what JSON was ever intended for, and there should be better solutions for almost all setups) should be to BASE64 Encode the Video in a Stream, so you can read Chunks of it into Memory, pack them into JSON-Strings and send these to the Server, which can use these Chunks to stream the Video to a file or play it, or reconstruct it in memory...
@BSON was mentioned before - it could be advisable to use it, since the JSON-Data will be compressed. But it doesn't change the fact you have to encode your Video-Data in an unfavorable format, which will bloat up the transmitted data and will cost its fair share of performance on BOTH ENDS!
But I can imagine Scenarios where using JSON for video transmission could be advisable. If you have a high number of small videos (small jingles, or video fragments, which the user can select and collate) then a solid easy to handle data structure to administrate these videos could be well worth the extra transfer cost...
|
Sending binary data in JSON from PHP is very simple:
$data = file_get_contents($filename);
echo json_encode(array('filecontent' => $data));
At least in theory this would work. The reason why it does not work in practice is that $data is limited in size (must fit into the memory limit), and that JSON is not meant to transfer megabytes of data.
The encoding is inefficient. Either you use the bytes natively, then you will experience escape sequences for any non-printable character, making these bytes getting six times as big (the unicode escape sequence uses a backslash, the letter "u" and four hex numbers). Or you use base64 encoding, which will blow up EVERY byte by about 33%. Not counting the overhead for the most basic JSON wrapping.
Offering a native stream of bytes with an appropriate header seems to be the better idea. You could directly feed that stream into the video codec for replay, without having to parse JSON, decode base64 and reassemble everything back into a video data stream.
|
Here is the info according to the PHP official documentation. Hopefully it will work for the video file.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(serverURL);
MultipartEntity postEntity = new MultipartEntity();
File file = new File("file path to be put here");
postEntity.addPart("fileupload", new FileBody(file, "video/mp4"));
postEntity.addPart("loginKey", new StringBody(""+loginKey));
postEntity.addPart("message", new StringBody(message));
postEntity.addPart("token", new StringBody(token));
post.setEntity(postEntity);
response = client.execute(post);
|
try this it works for you.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);//
FileBody filebodyVideo = new FileBody(file);
StringBody title = new StringBody("Filename: " + filename);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("videoFile", filebodyVideo);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute( httppost );
|
You can encode any binary file into base64 and then output a JSON string like this:
<?php
$fgc = file_get_contents('yourfile.gif'); //can be any binary
$bindata = base64_encode($fgc);
$arr = array('name'=>'yourfile.gif','mime'=>'image/gif','data'=>$bindata);
echo json_encode($arr);
?>
<?php
if(isset($_GET['name']))
{
$video_name = $_GET['name'];
$path = "/path/to/videos/folder/$video_name"; //ex: video.mp4
$size=filesize($path);
$fm=@fopen($path,'rb');
if(!$fm) {
// You can also redirect here
header ("HTTP/1.0 404 Not Found");
die();
}
$begin=0;
$end=$size;
if(isset($_SERVER['HTTP_RANGE'])) {
if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
$begin=intval($matches[0]);
if(!empty($matches[1])) {
$end=intval($matches[1]);
}
}
}
if($begin>0||$end<$size)
header('HTTP/1.0 206 Partial Content');
else
header('HTTP/1.0 200 OK');
header("Content-Type: video/mp4");
header('Accept-Ranges: bytes');
header('Content-Length:'.($end-$begin));
header("Content-Disposition: inline;");
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');
$cur=$begin;
fseek($fm,$begin,0);
while(!feof($fm)&&$cur<$end&&(connection_status()==0))
{ print fread($fm,min(1024*16,$end-$cur));
$cur+=1024*16;
usleep(1000);
}
die();
}else{
echo "Please provide a Video name (name=)";
}
?>
ava Code (Download and Save video to SDCARD):
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
public class VideoSaveSDCARD extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProgressBack PB = new ProgressBack();
PB.execute("");
}
class ProgressBack extends AsyncTask<String,String,String> {
ProgressDialog PD;
@Override
protected void onPreExecute() {
PD= ProgressDialog.show(LoginPage.this,null, "Please Wait ...", true);
PD.setCancelable(true);
}
@Override
protected void doInBackground(String... arg0) {
DownloadFile("http://yourserver/video.php?name=video.mp4","video.mp4");
}
protected void onPostExecute(Boolean result) {
PD.dismiss();
}
}
public void DownloadFile(String fileURL, String fileName) {
try {
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File RootFile = new File(RootDir);
RootFile.mkdir();
// File root = Environment.getExternalStorageDirectory();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(RootFile,
fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Error....", e.toString());
}
}
}
No comments:
Post a Comment