Example #1
0
 def encode(self):
     if self.source:
         media = self.source.media.path
         if not self.media:
             self.media.name = os.path.join(os.path.dirname(self.source.media.name), self.name())
         target = self.media.path
         info = ox.avinfo(media)
         if extract.stream(media, target, self.name(), info):
             self.available = True
         else:
             self.media = None
             self.available = False
         self.save()
     elif self.file.data:
         media = self.file.data.path
         if not self.media:
             self.media.name = self.path(self.name())
         target = self.media.path
         info = ox.avinfo(media)
         if extract.stream(media, target, self.name(), info):
             self.available = True
         else:
             self.media = None
             self.available = False
         self.save()
Example #2
0
 def save(self, *args, **kwargs):
     if self.media and not self.info:
         self.info = ox.avinfo(self.media.path)
         if 'path' in self.info:
             del self.info['path']
     self.oshash = self.info.get('oshash')
     self.duration = self.info.get('duration', 0)
     #wafaa
     '''if 'video' in self.info and self.info['video']:
         if 'display_aspect_ratio' in self.info['video'][0]:
             dar = map(int, self.info['video'][0]['display_aspect_ratio'].split(':'))
             self.aspect_ratio = dar[0] / dar[1]
         else:
             self.aspect_ratio = self.info['video'][0]['width'] / self.info['video'][0]['height']
     else:
         self.aspect_ratio = 128/80    '''
     #wafaa
     if 'image' in self.info and self.info['image']:
         if 'display_aspect_ratio' in self.info['image'][0]:
             dar = map(
                 int,
                 self.info['image'][0]['display_aspect_ratio'].split(':'))
             self.aspect_ratio = dar[0] / dar[1]
         else:
             self.aspect_ratio = self.info['image'][0]['width'] / self.info[
                 'image'][0]['height']
     else:
         self.aspect_ratio = 128 / 80
     super(Stream, self).save(*args, **kwargs)
     if self.available and not self.file.available:
         self.file.save()
Example #3
0
 def encode(self):
     if self.source:
         media = self.source.media.path
         if not self.media:
             self.media.name = os.path.join(
                 os.path.dirname(self.source.media.name), self.name())
         target = self.media.path
         info = ox.avinfo(media)
         ok, error = extract.stream(media, target, self.name(), info)
         if ok:
             self.available = True
         else:
             self.media = None
             self.available = False
             self.error = error
             self.file.failed = True
             self.file.save()
         self.save()
     elif self.file.data:
         media = self.file.data.path
         if not self.media:
             self.media.name = self.path(self.name())
         target = self.media.path
         info = ox.avinfo(media)
         ffmpeg = ox.file.cmd('ffmpeg')
         if ffmpeg == 'ffmpeg':
             ffmpeg = None
         ok, error = extract.stream(media, target, self.name(), info,
                                    ffmpeg)
         if ok:
             self.available = True
         else:
             self.media = None
             self.available = False
             self.error = error
             self.file.failed = True
             self.file.save()
         self.save()
Example #4
0
def avinfo(filename):
    if os.path.getsize(filename):
        info = ox.avinfo(filename)
				#info = imginfo(filename)
        if 'video' in info and info['video'] and 'width' in info['video'][0]:
            if not 'display_aspect_ratio' in info['video'][0]:
                dar = AspectRatio(info['video'][0]['width'], info['video'][0]['height'])
                info['video'][0]['display_aspect_ratio'] = dar.ratio
        del info['path']
        if os.path.splitext(filename)[-1] in ('.srt', '.sub', '.idx', '.rar') and 'error' in info:
            del info['error']
        if 'code' in info and info['code'] == 'badfile':
            del info['code']
        return info
    return {'path': filename, 'size': 0}
Example #5
0
def convertVideo(files, userid, objid):
    """
    converting video into webm format, if video already in webm format ,then pass to create thumbnails
    """
    fileVideoName = str(objid)
    initialFileName = str(objid)
    os.system("mkdir -p "+ "/tmp"+"/"+str(userid)+"/"+fileVideoName+"/")
    fd = open('%s/%s/%s/%s' % (str("/tmp"), str(userid),str(fileVideoName), str(fileVideoName)), 'wb')
    for chunk in files.chunks():
        fd.write(chunk)
    fd.close()
    if files._get_name().endswith('.webm') == False:
        proc = subprocess.Popen(['ffmpeg', '-y', '-i', str("/tmp/"+userid+"/"+fileVideoName+"/"+fileVideoName), str("/tmp/"+userid+"/"+fileVideoName+"/"+initialFileName+".webm")])
        proc.wait()
        files = open("/tmp/"+userid+"/"+fileVideoName+"/"+initialFileName+".webm")
    else : 
        files = open("/tmp/"+userid+"/"+fileVideoName+"/"+fileVideoName)
    filetype = "video"
    oxData = ox.avinfo("/tmp/"+userid+"/"+fileVideoName+"/"+fileVideoName)
    duration = oxData['duration'] # fetching duration of video by python ox
    duration = int(duration)
    secs, mins, hrs = 00, 00, 00
    if duration > 60 :
        secs  = duration % 60
        mins = duration / 60
        if mins > 60 :
            hrs = mins / 60
            mins = mins % 60 
    else:
        secs = duration
    videoDuration = ""
    durationTime = str(str(hrs)+":"+str(mins)+":"+str(secs)) # calculating Time duration of video in hrs,mins,secs

    if duration > 30 :
	videoDuration = "00:00:30"
    else :
    	videoDuration = "00:00:00"    	
    proc = subprocess.Popen(['ffmpeg', '-i', str("/tmp/"+userid+"/"+fileVideoName+"/"+fileVideoName), '-ss', videoDuration, "-s", "170*128", "-vframes", "1", str("/tmp/"+userid+"/"+fileVideoName+"/"+initialFileName+".png")]) # GScreating thumbnail of video using ffmpeg
    proc.wait()
    background = Image.open("/tmp/"+userid+"/"+fileVideoName+"/"+initialFileName+".png")
    fore = Image.open(MEDIA_ROOT+"ndf/images/poster.jpg")
    background.paste(fore, (120, 100))
    draw = ImageDraw.Draw(background)
    draw.text((120, 100), durationTime, (255, 255, 255)) # drawing duration time on thumbnail image
    background.save("/tmp/"+userid+"/"+fileVideoName+"/"+initialFileName+"Time.png")
    thumbnailvideo = open("/tmp/"+userid+"/"+fileVideoName+"/"+initialFileName+"Time.png")
    return files, filetype, thumbnailvideo
Example #6
0
 def save_chunk(self, chunk, chunk_id=-1, done=False):
     if not self.available:
         if not self.data:
             name = 'data.%s' % self.info.get('extension', 'avi')
             self.data.name = self.get_path(name)
             ox.makedirs(os.path.dirname(self.data.path))
             with open(self.data.path, 'w') as f:
                 f.write(chunk.read())
             self.save()
         else:
             with open(self.data.path, 'a') as f:
                 f.write(chunk.read())
         if done:
             self.info.update(ox.avinfo(self.data.path))
             self.parse_info()
             self.save()
         return True
     return False
Example #7
0
 def save(self, *args, **kwargs):
     if self.media and not self.info:
         self.info = ox.avinfo(self.media.path)
         if 'path' in self.info:
             del self.info['path']
     self.oshash = self.info.get('oshash')
     self.duration = self.info.get('duration', 0)
     if 'video' in self.info and self.info['video']:
         if 'display_aspect_ratio' in self.info['video'][0]:
             dar = map(int, self.info['video'][0]['display_aspect_ratio'].split(':'))
             self.aspect_ratio = dar[0] / dar[1]
         else:
             self.aspect_ratio = self.info['video'][0]['width'] / self.info['video'][0]['height']
     else:
         self.aspect_ratio = 128/80
     super(Stream, self).save(*args, **kwargs)
     if self.available and not self.file.available:
         self.file.save()
Example #8
0
 def save_chunk(self, chunk, chunk_id=-1, done=False):
     if not self.available:
         if not self.data:
             name = 'data.%s' % self.info.get('extension', 'avi')
             self.data.name = self.get_path(name)
             ox.makedirs(os.path.dirname(self.data.path))
             with open(self.data.path, 'w') as f:
                 f.write(chunk.read())
             self.save()
         else:
             with open(self.data.path, 'a') as f:
                 f.write(chunk.read())
         if done:
             self.info.update(ox.avinfo(self.data.path))
             self.parse_info()
             self.save()
         return True
     return False
    def loadMetadata(self):
        if not self.file and self.raw_file and os.path.exists(self.raw_file.path):
            self.encoding = True
            self.save()
            return
        os.chmod(self.file.path,0644)
        d = avinfo(self.file.path)
        if 'audio' not in d and 'video' not in d:
            if not self.raw_file and os.path.exists(self.file.path):
                self.raw_file.name = self.file.name + '.upload'
                os.rename(self.file.path, self.raw_file.path)
                self.encoding = True
                self.save()
                return
        #Update DB
        if 'title' in d and self.title:
            del d['title']
        #FIXME:
        for key in ('duration', 'oshash', 'size'):
            if key in d:
                value = d[key]
                if key == 'duration':
                    value = float(value) * 1000   
                setattr(self, key, value)
        if d.get('video'):
            for key in ('width', 'height', 'framerate'):
                if key in d['video'][0]:
                    setattr(self, key, d['video'][0][key])
            self.video_codec = d['video'][0]['codec'].capitalize()
        if d.get('audio'):
            for key in ('channels', 'samplerate'):
                if key in d['audio'][0]:
                    setattr(self, key, d['audio'][0][key])
            self.audio_codec = d['audio'][0]['codec'].capitalize()

        #FIXME: check for to big ogg files here and initiate transcoding
        #base = os.path.dirname(__file__)
        #cmd = '''%s/bin/extract_still.py "%s" "%s" %s''' % (base, self.file.path, self.still.path, self.duration / 2)
        #os.system(cmd)

        self.createTorrent()
        self.encoding = False
        self.save()
Example #10
0
def convertVideo(userid, file_id, filename):
    """
    converting video into webm format, if video already in webm format ,then pass to create thumbnails
    """

    fileobj = node_collection.one({'_id':ObjectId(file_id)})

    objid = fileobj._id
    fileVideoName = str(objid)
    initialFileName = str(objid)

    if hasattr(fileobj, 'fs_file_ids'):
        files =  fileobj.fs.files.get(ObjectId(fileobj.fs_file_ids[0]))
    elif hasattr(fileobj, 'if_file'):
        files = fileobj.get_file(fileobj.if_file['original']['relurl'])

    # -- create tmp directory
    os.system("mkdir -p "+ "/tmp"+"/"+str(userid)+"/"+fileVideoName+"/")
    # -- create tmp file
    fd = open('%s/%s/%s/%s' % (str("/tmp"), str(userid),str(fileVideoName), str(fileVideoName)), 'wb')

    # -- writing uploaded files chunk to tmp file
    for line in files:
        fd.write(line)
    fd.close()
    # -- convert tmp_file tmp_webm file in local disk

    if (hasattr(files, 'name') and (files.name.endswith('.webm') == False)) or \
        (hasattr(files, 'filename') and (files.filename.endswith('.webm') == False)):
        input_filename = str("/tmp/"+str(userid)+"/"+fileVideoName+"/"+fileVideoName)
        output_filename = str("/tmp/"+str(userid)+"/"+fileVideoName+"/"+initialFileName+".webm")
        proc = subprocess.Popen(['ffmpeg', '-y', '-i', input_filename,output_filename])
        proc.wait()
        files = open("/tmp/"+str(userid)+"/"+fileVideoName+"/"+initialFileName+".webm")
    else :
        files = open("/tmp/"+str(userid)+"/"+fileVideoName+"/"+fileVideoName)

    filetype = "video"
    filepath = "/tmp/"+str(userid)+"/"+fileVideoName+"/"+fileVideoName
    # print "filepath: ", filepath
    # print "======== ", os.path.isfile(filepath)
    oxData = ox.avinfo(filepath)
    # print "============ oxData: ", oxData
    duration = oxData['duration'] # fetching duration of video by python ox
    duration = int(duration)
    secs, mins, hrs = 00, 00, 00
    if duration > 60 :
        secs  = duration % 60
        mins = duration / 60
        if mins > 60 :
            hrs = mins / 60
            mins = mins % 60
    else:
        secs = duration
    videoDuration = ""
    durationTime = str(str(hrs)+":"+str(mins)+":"+str(secs)) # calculating Time duration of video in hrs,mins,secs

    if duration > 30 :
        videoDuration = "00:00:30"
    else :
        videoDuration = "00:00:00"
    proc = subprocess.Popen(['ffmpeg', '-i', str("/tmp/"+str(userid)+"/"+fileVideoName+"/"+fileVideoName), '-ss', videoDuration, "-s", "170*128", "-vframes", "1", str("/tmp/"+str(userid)+"/"+fileVideoName+"/"+initialFileName+".png")]) # GScreating thumbnail of video using ffmpeg
    proc.wait()

    background = Image.open("/tmp/"+str(userid)+"/"+fileVideoName+"/"+initialFileName+".png")
    fore = Image.open("gnowsys_ndf/ndf/static/ndf/images/poster.jpg")
    background.paste(fore, (120, 100))
    draw = ImageDraw.Draw(background)
    draw.text((120, 100), durationTime, (255, 255, 255)) # drawing duration time on thumbnail image
    background.save("/tmp/"+str(userid)+"/"+fileVideoName+"/"+initialFileName+"Time.png")
    thumbnailvideo = open("/tmp/"+str(userid)+"/"+fileVideoName+"/"+initialFileName+"Time.png")

    webmfiles = files
    '''storing thumbnail of video with duration in saved object'''

    # th_gridfs_id = fileobj.fs.files.put(thumbnailvideo.read(), filename=filename+"-thumbnail", content_type="image/png")

    if hasattr(fileobj, 'fs_file_ids'):
        th_gridfs_id = fileobj.fs.files.put(thumbnailvideo.read(), filename=filename+"-thumbnail", content_type="image/png")
        node_fs_file_ids = fileobj.fs_file_ids

        if len(node_fs_file_ids) == 1:
            node_fs_file_ids.append(ObjectId(th_gridfs_id))
        elif len(node_fs_file_ids) > 1:
            node_fs_file_ids[1] = ObjectId(th_gridfs_id)

        # print "node_fs_file_ids: ", node_fs_file_ids

        node_collection.collection.update(
                                            {'_id': ObjectId(fileobj._id)},
                                            {'$set': {'fs_file_ids': node_fs_file_ids}}
                                        )
        # node_collection.find_and_modify({'_id':fileobj._id},{'$push':{'fs_file_ids':th_gridfs_id}})

        # print "fileobj.fs_file_ids: ", fileobj.fs_file_ids

    elif hasattr(fileobj, 'if_file'):
        thumbnail_filehive_obj = filehive_collection.collection.Filehive()
        thumbnail_file = thumbnailvideo

        mime_type = 'image/png'
        file_name = unicode( filename + '-thumbnail' )
        thumbnail_file_extension = '.png'

        thumbnail_filehive_id_url_dict = thumbnail_filehive_obj.save_file_in_filehive(
            file_blob=thumbnail_file,
            file_name=file_name,
            first_uploader=userid,
            first_parent=fileobj._id,
            mime_type=mime_type,
            file_extension=thumbnail_file_extension,
            if_image_size_name='thumbnail'
            )

        # print "==== ", thumbnail_filehive_id_url_dict

        node_collection.collection.update(
                                            {'_id': ObjectId(fileobj._id)},
                                            {'$set': {'if_file.thumbnail': thumbnail_filehive_id_url_dict}}
                                        )

    if filename.endswith('.webm') == False:

        if hasattr(fileobj, 'fs_file_ids'):
            vid_gridfs_id = fileobj.fs.files.put(webmfiles.read(), filename=filename+".webm", content_type=filetype)

            fileobj.reload()
            # print "fileobj.fs_file_ids: ", fileobj.fs_file_ids
            node_fs_file_ids = fileobj.fs_file_ids

            if len(node_fs_file_ids) == 2:
                node_fs_file_ids.append(ObjectId(vid_gridfs_id))
            elif len(node_fs_file_ids) > 2:
                node_fs_file_ids[2] = ObjectId(vid_gridfs_id)

            # print "node_fs_file_ids: ", node_fs_file_ids

            node_collection.collection.update(
                                                {'_id': ObjectId(fileobj._id)},
                                                {'$set': {'fs_file_ids': node_fs_file_ids}}
                                            )

            # --saving webm video id into file object
            # node_collection.find_and_modify({'_id':fileobj._id},{'$push':{'fs_file_ids':vid_gridfs_id}})

        elif hasattr(fileobj, 'if_file'):
            webm_filehive_obj = filehive_collection.collection.Filehive()
            fileobj.reload()
            midsize_file = webmfiles

            mime_type = webm_filehive_obj.get_file_mimetype(midsize_file)
            file_name = unicode( filename + '.webm' )
            mid_file_extension = '.webm'

            mid_filehive_id_url_dict = webm_filehive_obj.save_file_in_filehive(
                file_blob=midsize_file,
                file_name=file_name,
                first_uploader=userid,
                first_parent=fileobj._id,
                mime_type=mime_type,
                file_extension=mid_file_extension,
                if_image_size_name='mid'
                )

            # print "==== ",  mid_filehive_id_url_dict

            node_collection.collection.update(
                                                {'_id': ObjectId(fileobj._id)},
                                                {'$set': {'if_file.mid': mid_filehive_id_url_dict}}
                                            )