2 * filehandler.cc -- saving DV data into different file formats
3 * Copyright (C) 2000 Arne Schirmacher <arne@schirmacher.de>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software Foundation,
17 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 #include <framework/mlt_frame.h>
33 using std
::ostringstream
;
51 #include "filehandler.h"
56 FileTracker
*FileTracker
::instance
= NULL
;
58 FileTracker
::FileTracker( ) : mode( CAPTURE_MOVIE_APPEND
)
60 cerr
<< ">> Constructing File Capture tracker" << endl
;
63 FileTracker
::~FileTracker( )
65 cerr
<< ">> Destroying File Capture tracker" << endl
;
68 FileTracker
&FileTracker
::GetInstance( )
70 if ( instance
== NULL
)
71 instance
= new FileTracker();
76 void FileTracker
::SetMode( FileCaptureMode mode
)
81 FileCaptureMode FileTracker
::GetMode( )
86 char *FileTracker
::Get( int index
)
91 void FileTracker
::Add( const char *file
)
93 if ( this->mode
!= CAPTURE_IGNORE
)
95 cerr
<< ">>>> Registering " << file
<< " with the tracker" << endl
;
96 list
.push_back( strdup( file
) );
100 unsigned int FileTracker
::Size( )
105 void FileTracker
::Clear( )
109 free( list
[ Size() - 1 ] );
112 this->mode
= CAPTURE_MOVIE_APPEND
;
115 FileHandler
::FileHandler() : done( false ), autoSplit( false ), maxFrameCount( 999999 ),
116 framesWritten( 0 ), filename( "" )
122 FileHandler
::~FileHandler()
128 bool FileHandler
::GetAutoSplit() const
134 bool FileHandler
::GetTimeStamp() const
140 string FileHandler
::GetBaseName() const
146 string FileHandler
::GetExtension() const
152 int FileHandler
::GetMaxFrameCount() const
154 return maxFrameCount
;
157 off_t FileHandler
::GetMaxFileSize() const
162 string FileHandler
::GetFilename() const
168 void FileHandler
::SetAutoSplit( bool flag
)
174 void FileHandler
::SetTimeStamp( bool flag
)
180 void FileHandler
::SetBaseName( const string
& s
)
186 void FileHandler
::SetMaxFrameCount( int count
)
188 assert( count
>= 0 );
189 maxFrameCount
= count
;
193 void FileHandler
::SetEveryNthFrame( int every
)
195 assert ( every
> 0 );
197 everyNthFrame
= every
;
201 void FileHandler
::SetMaxFileSize( off_t size
)
203 assert ( size
>= 0 );
209 void FileHandler
::SetSampleFrame( const Frame
& sample
)
215 bool FileHandler
::Done()
221 bool FileHandler
::WriteFrame( const Frame
& frame
)
223 static TimeCode prevTimeCode
;
226 /* If the user wants autosplit, start a new file if a
227 new recording is detected. */
228 prevTimeCode
.sec
= -1;
229 frame
.GetTimeCode( timeCode
);
230 int time_diff
= timeCode
.sec
- prevTimeCode
.sec
;
231 bool discontinuity
= prevTimeCode
.sec
!= -1 && ( time_diff
> 1 || ( time_diff
< 0 && time_diff
> -59 ) );
232 if ( FileIsOpen() && GetAutoSplit() == true && ( frame
.IsNewRecording() || discontinuity
) )
237 if ( FileIsOpen() == false )
241 static int counter
= 0;
243 if ( GetTimeStamp() == true )
245 ostringstream sb
, sb2
;
249 if ( ! frame
.GetRecordingDate( date
) )
253 gettimeofday( &tv
, &tz
);
254 localtime_r( static_cast< const time_t * >( &tv
.tv_sec
), &date
);
257 << setw( 4 ) << date
.tm_year
+ 1900 << '.'
258 << setw( 2 ) << date
.tm_mon
+ 1 << '.'
259 << setw( 2 ) << date
.tm_mday
<< '_'
260 << setw( 2 ) << date
.tm_hour
<< '-'
261 << setw( 2 ) << date
.tm_min
<< '-'
262 << setw( 2 ) << date
.tm_sec
;
264 sb2
<< GetBaseName() << recDate
<< GetExtension();
265 filename
= sb2
.str();
266 cerr
<< ">>> Trying " << filename
<< endl
;
274 sb
<< GetBaseName() << setfill( '0' ) << setw( 3 ) << ++ counter
<< GetExtension();
276 cerr
<< ">>> Trying " << filename
<< endl
;
278 while ( stat( filename
.c_str(), &stats
) == 0 );
281 SetSampleFrame( frame
);
282 if ( Create( filename
) == false )
284 cerr
<< ">>> Error creating file!" << endl
;
293 if ( framesToSkip
== 0 )
295 if ( 0 > Write( frame
) )
297 cerr
<< ">>> Error writing frame!" << endl
;
300 framesToSkip
= everyNthFrame
;
305 /* If the frame count is exceeded, close the current file.
306 If the autosplit flag is set, a new file will be created in the next iteration.
307 If the flag is not set, we are done. */
309 if ( ( GetMaxFrameCount() > 0 ) &&
310 ( framesWritten
>= GetMaxFrameCount() ) )
313 done
= !GetAutoSplit();
316 /* If the file size could be exceeded by another frame, close the current file.
317 If the autosplit flag is set, a new file will be created on the next iteration.
318 If the flag is not set, we are done. */
319 /* not exact, but should be good enough to prevent going over. */
323 frame
.GetAudioInfo( info
);
324 if ( ( GetFileSize() > 0 ) && ( GetMaxFileSize() > 0 ) &&
325 ( GetFileSize() + frame
.GetFrameSize() + info
.samples
* 4 + 12 )
326 >= GetMaxFileSize() )
327 { // 12 = sizeof chunk metadata
329 done
= !GetAutoSplit();
332 prevTimeCode
.sec
= timeCode
.sec
;
337 RawHandler
::RawHandler() : fd( -1 )
343 RawHandler
::~RawHandler()
349 bool RawHandler
::FileIsOpen()
355 bool RawHandler
::Create( const string
& filename
)
357 fd
= open( filename
.c_str(), O_CREAT
| O_TRUNC
| O_RDWR
| O_NONBLOCK
, 0644 );
360 FileTracker
::GetInstance().Add( filename
.c_str() );
361 this->filename
= filename
;
368 int RawHandler
::Write( const Frame
& frame
)
370 int result
= write( fd
, frame
.data
, frame
.GetFrameSize() );
375 int RawHandler
::Close()
386 off_t RawHandler
::GetFileSize()
388 struct stat file_status
;
389 fstat( fd
, &file_status
);
390 return file_status
.st_size
;
393 int RawHandler
::GetTotalFrames()
395 return GetFileSize() / ( 480 * numBlocks
);
399 bool RawHandler
::Open( const char *s
)
401 unsigned char data
[ 4 ];
403 fd
= open( s
, O_RDONLY
| O_NONBLOCK
);
406 if ( read( fd
, data
, 4 ) < 0 )
408 lseek( fd
, 0, SEEK_SET
);
409 numBlocks
= ( ( data
[ 3 ] & 0x80 ) == 0 ) ?
250 : 300;
415 int RawHandler
::GetFrame( uint8_t *data
, int frameNum
)
418 int size
= 480 * numBlocks
;
421 off_t offset
= ( ( off_t
) frameNum
* ( off_t
) size
);
422 fail_if( lseek( fd
, offset
, SEEK_SET
) == ( off_t
) - 1 );
423 if ( read( fd
, data
, size
) > 0 )
430 /***************************************************************************/
433 AVIHandler
::AVIHandler( int format
) : avi( NULL
), aviFormat( format
), isOpenDML( false ),
434 fccHandler( make_fourcc( "dvsd" ) ), channels( 2 ), isFullyInitialized( false ),
438 for ( int c
= 0; c
< 4; c
++ )
439 audioChannels
[ c
] = NULL
;
443 AVIHandler
::~AVIHandler()
445 if ( audioBuffer
!= NULL
)
450 for ( int c
= 0; c
< 4; c
++ )
452 if ( audioChannels
[ c
] != NULL
)
454 delete audioChannels
[ c
];
455 audioChannels
[ c
] = NULL
;
463 void AVIHandler
::SetSampleFrame( const Frame
& sample
)
466 sample
.GetAudioInfo( audioInfo
);
467 sample
.GetVideoInfo( videoInfo
);
469 sample
.GetAAUXPack( 0x50, pack
);
470 dvinfo
.dwDVAAuxSrc
= *( DWORD
* ) ( pack
.data
+ 1 );
471 sample
.GetAAUXPack( 0x51, pack
);
472 dvinfo
.dwDVAAuxCtl
= *( DWORD
* ) ( pack
.data
+ 1 );
474 sample
.GetAAUXPack( 0x52, pack
);
475 dvinfo
.dwDVAAuxSrc1
= *( DWORD
* ) ( pack
.data
+ 1 );
476 sample
.GetAAUXPack( 0x53, pack
);
477 dvinfo
.dwDVAAuxCtl1
= *( DWORD
* ) ( pack
.data
+ 1 );
479 sample
.GetVAUXPack( 0x60, pack
);
480 dvinfo
.dwDVVAuxSrc
= *( DWORD
* ) ( pack
.data
+ 1 );
481 sample
.GetVAUXPack( 0x61, pack
);
482 dvinfo
.dwDVVAuxCtl
= *( DWORD
* ) ( pack
.data
+ 1 );
486 if ( sample
.decoder
->std
== e_dv_std_smpte_314m
)
487 fccHandler
= make_fourcc( "dv25" );
492 bool AVIHandler
::FileIsOpen()
498 bool AVIHandler
::Create( const string
& filename
)
500 assert( avi
== NULL
);
506 fail_null( avi
= new AVI1File
);
507 if ( avi
->Create( filename
.c_str() ) == false )
509 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency, AVI_LARGE_INDEX );
513 fail_null( avi
= new AVI2File
);
514 if ( avi
->Create( filename
.c_str() ) == false )
516 //if ( GetOpenDML() )
517 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency,
518 //( AVI_SMALL_INDEX | AVI_LARGE_INDEX ) );
520 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency,
521 //( AVI_SMALL_INDEX ) );
525 assert( aviFormat
== AVI_DV1_FORMAT
|| aviFormat
== AVI_DV2_FORMAT
);
528 avi
->setDVINFO( dvinfo
);
529 avi
->setFccHandler( make_fourcc( "iavs" ), fccHandler
);
530 avi
->setFccHandler( make_fourcc( "vids" ), fccHandler
);
531 this->filename
= filename
;
532 FileTracker
::GetInstance().Add( filename
.c_str() );
533 return ( avi
!= NULL
);
537 int AVIHandler
::Write( const Frame
& frame
)
539 assert( avi
!= NULL
);
542 return avi
->WriteFrame( frame
) ?
0 : -1;
551 int AVIHandler
::Close()
559 if ( audioBuffer
!= NULL
)
564 for ( int c
= 0; c
< 4; c
++ )
566 if ( audioChannels
[ c
] != NULL
)
568 delete audioChannels
[ c
];
569 audioChannels
[ c
] = NULL
;
572 isFullyInitialized
= false;
576 off_t AVIHandler
::GetFileSize()
578 return avi
->GetFileSize();
581 int AVIHandler
::GetTotalFrames()
583 return avi
->GetTotalFrames();
587 bool AVIHandler
::Open( const char *s
)
589 assert( avi
== NULL
);
590 fail_null( avi
= new AVI1File
);
591 if ( avi
->Open( s
) )
595 avi
->verifyStreamFormat( make_fourcc( "dvsd" ) ) ||
596 avi
->verifyStreamFormat( make_fourcc( "DVSD" ) ) ||
597 avi
->verifyStreamFormat( make_fourcc( "dvcs" ) ) ||
598 avi
->verifyStreamFormat( make_fourcc( "DVCS" ) ) ||
599 avi
->verifyStreamFormat( make_fourcc( "dvcp" ) ) ||
600 avi
->verifyStreamFormat( make_fourcc( "DVCP" ) ) ||
601 avi
->verifyStreamFormat( make_fourcc( "CDVC" ) ) ||
602 avi
->verifyStreamFormat( make_fourcc( "cdvc" ) ) ||
603 avi
->verifyStreamFormat( make_fourcc( "DV25" ) ) ||
604 avi
->verifyStreamFormat( make_fourcc( "dv25" ) ) ) )
607 if ( avi
->verifyStream( make_fourcc( "auds" ) ) )
608 aviFormat
= AVI_DV2_FORMAT
;
610 aviFormat
= AVI_DV1_FORMAT
;
611 isOpenDML
= avi
->isOpenDML();
620 int AVIHandler
::GetFrame( uint8_t *data
, int frameNum
)
622 int result
= avi
->GetDVFrame( data
, frameNum
);
626 /* get the audio from the audio stream, if available */
627 if ( aviFormat
== AVI_DV2_FORMAT
)
631 if ( ! isFullyInitialized
&&
632 avi
->getStreamFormat( ( void* ) &wav
, make_fourcc( "auds" ) ) )
634 if ( channels
> 0 && channels
< 5 )
636 // Allocate interleaved audio buffer
637 audioBuffer
= new int16_t[ 2 * DV_AUDIO_MAX_SAMPLES
* channels
];
639 // Allocate non-interleaved audio buffers
640 for ( int c
= 0; c
< channels
; c
++ )
641 audioChannels
[ c
] = new int16_t[ 2 * DV_AUDIO_MAX_SAMPLES
];
643 // Get the audio parameters from AVI for subsequent calls to method
644 audioInfo
.channels
= wav
.nChannels
;
645 audioInfo
.frequency
= wav
.nSamplesPerSec
;
647 // Skip initialization on subsequent calls to method
648 isFullyInitialized
= true;
649 cerr
<< ">>> using audio from separate AVI audio stream" << endl
;
653 // Get the frame from AVI
654 int n
= avi
->getFrame( audioBuffer
, frameNum
, make_fourcc( "01wb" ) );
657 // Temporary pointer to audio scratch buffer
658 int16_t * s
= audioBuffer
;
660 // Determine samples in this frame
661 audioInfo
.samples
= n
/ audioInfo
.channels
/ sizeof( int16_t );
663 // Convert interleaved audio into non-interleaved
664 for ( int n
= 0; n
< audioInfo
.samples
; ++n
)
665 for ( int i
= 0; i
< audioInfo
.channels
; i
++ )
666 audioChannels
[ i
][ n
] = *s
++;
668 // Write interleaved audio into frame
669 frame
.EncodeAudio( audioInfo
, audioChannels
);
673 // Parse important metadata in DV bitstream
674 frame
.ExtractHeader();
681 void AVIHandler
::SetOpenDML( bool flag
)
687 bool AVIHandler
::GetOpenDML() const
693 /***************************************************************************/
695 #ifdef HAVE_LIBQUICKTIME
698 #define DV_AUDIO_MAX_SAMPLES 1944
701 // Missing fourcc's in libquicktime (allows compilation)
702 #ifndef QUICKTIME_DV_AVID
703 #define QUICKTIME_DV_AVID "AVdv"
706 #ifndef QUICKTIME_DV_AVID_A
707 #define QUICKTIME_DV_AVID_A "dvcp"
710 #ifndef QUICKTIME_DVCPRO
711 #define QUICKTIME_DVCPRO "dvpp"
714 QtHandler
::QtHandler() : fd( NULL
)
721 QtHandler
::~QtHandler()
726 void QtHandler
::Init()
733 samplesPerBuffer
= 0;
736 audioChannelBuffer
= NULL
;
737 isFullyInitialized
= false;
741 bool QtHandler
::FileIsOpen()
747 bool QtHandler
::Create( const string
& filename
)
751 if ( open( filename
.c_str(), O_CREAT
| O_TRUNC
| O_RDWR
| O_NONBLOCK
, 0644 ) != -1 )
753 fd
= quicktime_open( const_cast<char*>( filename
.c_str() ), 0, 1 );
755 FileTracker
::GetInstance().Add( filename
.c_str() );
759 this->filename
= filename
;
763 void QtHandler
::AllocateAudioBuffers()
765 if ( channels
> 0 && channels
< 5 )
767 audioBufferSize
= DV_AUDIO_MAX_SAMPLES
* 2;
768 audioBuffer
= new int16_t[ audioBufferSize
* channels
];
770 audioChannelBuffer
= new short int * [ channels
];
771 for ( int c
= 0; c
< channels
; c
++ )
772 audioChannelBuffer
[ c
] = new short int[ audioBufferSize
];
773 isFullyInitialized
= true;
777 inline void QtHandler
::DeinterlaceStereo16( void* pInput
, int iBytes
,
778 void* pLOutput
, void* pROutput
)
780 short int * piSampleInput
= ( short int* ) pInput
;
781 short int* piSampleLOutput
= ( short int* ) pLOutput
;
782 short int* piSampleROutput
= ( short int* ) pROutput
;
784 while ( ( char* ) piSampleInput
< ( ( char* ) pInput
+ iBytes
) )
786 *piSampleLOutput
++ = *piSampleInput
++;
787 *piSampleROutput
++ = *piSampleInput
++;
792 int QtHandler
::Write( const Frame
& frame
)
794 if ( ! isFullyInitialized
)
798 if ( frame
.GetAudioInfo( audio
) )
801 quicktime_set_audio( fd
, channels
, audio
.frequency
, 16, QUICKTIME_TWOS
);
808 quicktime_set_video( fd
, 1, 720, frame
.IsPAL() ?
576 : 480,
809 frame
.GetFrameRate(), QUICKTIME_DV
);
810 AllocateAudioBuffers();
813 int result
= quicktime_write_frame( fd
, const_cast<unsigned char*>( frame
.data
),
814 frame
.GetFrameSize(), 0 );
819 if ( frame
.GetAudioInfo( audio
) && ( unsigned int ) audio
.samples
< audioBufferSize
)
821 long bytesRead
= frame
.ExtractAudio( audioBuffer
);
823 DeinterlaceStereo16( audioBuffer
, bytesRead
,
824 audioChannelBuffer
[ 0 ],
825 audioChannelBuffer
[ 1 ] );
827 quicktime_encode_audio( fd
, audioChannelBuffer
, NULL
, audio
.samples
);
834 int QtHandler
::Close()
838 quicktime_close( fd
);
841 if ( audioBuffer
!= NULL
)
846 if ( audioChannelBuffer
!= NULL
)
848 for ( int c
= 0; c
< channels
; c
++ )
849 delete audioChannelBuffer
[ c
];
850 delete audioChannelBuffer
;
851 audioChannelBuffer
= NULL
;
857 off_t QtHandler
::GetFileSize()
859 struct stat file_status
;
860 stat( filename
.c_str(), &file_status
);
861 return file_status
.st_size
;
865 int QtHandler
::GetTotalFrames()
867 return ( int ) quicktime_video_length( fd
, 0 );
871 bool QtHandler
::Open( const char *s
)
875 fd
= quicktime_open( ( char * ) s
, 1, 0 );
878 fprintf( stderr
, "Error opening: %s\n", s
);
882 if ( quicktime_has_video( fd
) <= 0 )
884 fprintf( stderr
, "There must be at least one video track in the input file (%s).\n",
889 char * fcc
= quicktime_video_compressor( fd
, 0 );
890 if ( strncmp( fcc
, QUICKTIME_DV
, 4 ) != 0 &&
891 strncmp( fcc
, QUICKTIME_DV_AVID
, 4 ) != 0 &&
892 strncmp( fcc
, QUICKTIME_DV_AVID_A
, 4 ) != 0 &&
893 strncmp( fcc
, QUICKTIME_DVCPRO
, 4 ) != 0 )
898 if ( quicktime_has_audio( fd
) )
899 channels
= quicktime_track_channels( fd
, 0 );
904 int QtHandler
::GetFrame( uint8_t *data
, int frameNum
)
906 assert( fd
!= NULL
);
908 quicktime_set_video_position( fd
, frameNum
, 0 );
909 quicktime_read_frame( fd
, data
, 0 );
912 if ( quicktime_has_audio( fd
) )
914 if ( ! isFullyInitialized
)
915 AllocateAudioBuffers();
917 // Fetch the frequency of the audio track and calc number of samples needed
918 int frequency
= quicktime_sample_rate( fd
, 0 );
919 float fps
= ( data
[ 3 ] & 0x80 ) ?
25.0f
: 29.97f
;
920 int samples
= mlt_sample_calculator( fps
, frequency
, frameNum
);
921 int64_t seek
= mlt_sample_calculator_to_now( fps
, frequency
, frameNum
);
923 // Obtain a dv encoder and initialise it with minimal info
924 dv_encoder_t
*encoder
= dv_encoder_new( 0, 0, 0 );
925 encoder
->isPAL
= ( data
[ 3 ] & 0x80 );
926 encoder
->samples_this_frame
= samples
;
928 // Seek to the calculated position and decode
929 quicktime_set_audio_position( fd
, seek
, 0 );
930 lqt_decode_audio( fd
, audioChannelBuffer
, NULL
, (long) samples
);
932 // Encode the audio on the frame and done
933 dv_encode_full_audio( encoder
, audioChannelBuffer
, channels
, frequency
, data
);
934 dv_encoder_free( encoder
);