public static int getDuration ( File flvFile ) { int duration = 0 ; RandomAccessFile flv = null ; try { flv = new RandomAccessFile ( flvFile , "r" ) ; long flvLength = Math . max ( flvFile . length ( ) , flv . length ( ) ) ; log . debug ( "File length: {}" , flvLength ) ; if ( flvLength > 13 ) { flv . seek ( flvLength - 4 ) ; int lastTagSize = flv . readInt ( ) ; log . debug ( "Last tag size: {}" , lastTagSize ) ; if ( lastTagSize > 0 && ( lastTagSize < flvLength ) ) { // jump right to where tag timestamp would be flv . seek ( flvLength - lastTagSize ) ; // grab timestamp as a regular int duration = flv . readInt ( ) ; // adjust value to match extended timestamp duration = ( duration >>> 8 ) | ( ( duration & 0x000000ff ) << 24 ) ; } else { // attempt to read the metadata flv . seek ( 13 ) ; byte tagType = flv . readByte ( ) ; if ( tagType == ITag . TYPE_METADATA ) { ByteBuffer buf = ByteBuffer . allocate ( 3 ) ; flv . getChannel ( ) . read ( buf ) ; int bodySize = IOUtils . readMediumInt ( buf ) ; log . debug ( "Metadata body size: {}" , bodySize ) ; flv . skipBytes ( 4 ) ; // timestamp flv . skipBytes ( 3 ) ; // stream id buf . clear ( ) ; buf = ByteBuffer . allocate ( bodySize ) ; flv . getChannel ( ) . read ( buf ) ; // construct the meta IoBuffer ioBuf = IoBuffer . wrap ( buf ) ; Input input = new Input ( ioBuf ) ; String metaType = Deserializer . deserialize ( input , String . class ) ; log . debug ( "Metadata type: {}" , metaType ) ; Map < String , ? > meta = Deserializer . deserialize ( input , Map . class ) ; Object tmp = meta . get ( "duration" ) ; if ( tmp != null ) { if ( tmp instanceof Double ) { duration = ( ( Double ) tmp ) . intValue ( ) ; } else { duration = Integer . valueOf ( ( String ) tmp ) ; } } input = null ; meta . clear ( ) ; meta = null ; ioBuf . clear ( ) ; ioBuf . free ( ) ; ioBuf = null ; } } } } catch ( IOException e ) { log . warn ( "Exception getting file duration" , e ) ; } finally { try { if ( flv != null ) { flv . close ( ) ; } } catch ( IOException e ) { } flv = null ; } return duration ; }
Returns the last tag s timestamp as the files duration .