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.
29 using std
::ostringstream
;
41 #include "filehandler.h"
46 FileTracker
*FileTracker
::instance
= NULL
;
48 FileTracker
::FileTracker( ) : mode( CAPTURE_MOVIE_APPEND
)
50 cerr
<< ">> Constructing File Capture tracker" << endl
;
53 FileTracker
::~FileTracker( )
55 cerr
<< ">> Destroying File Capture tracker" << endl
;
58 FileTracker
&FileTracker
::GetInstance( )
60 if ( instance
== NULL
)
61 instance
= new FileTracker();
66 void FileTracker
::SetMode( FileCaptureMode mode
)
71 FileCaptureMode FileTracker
::GetMode( )
76 char *FileTracker
::Get( int index
)
81 void FileTracker
::Add( const char *file
)
83 if ( this->mode
!= CAPTURE_IGNORE
)
85 cerr
<< ">>>> Registering " << file
<< " with the tracker" << endl
;
86 list
.push_back( strdup( file
) );
90 unsigned int FileTracker
::Size( )
95 void FileTracker
::Clear( )
99 free( list
[ Size() - 1 ] );
102 this->mode
= CAPTURE_MOVIE_APPEND
;
105 FileHandler
::FileHandler() : done( false ), autoSplit( false ), maxFrameCount( 999999 ),
106 framesWritten( 0 ), filename( "" )
112 FileHandler
::~FileHandler()
118 bool FileHandler
::GetAutoSplit() const
124 bool FileHandler
::GetTimeStamp() const
130 string FileHandler
::GetBaseName() const
136 string FileHandler
::GetExtension() const
142 int FileHandler
::GetMaxFrameCount() const
144 return maxFrameCount
;
147 off_t FileHandler
::GetMaxFileSize() const
152 string FileHandler
::GetFilename() const
158 void FileHandler
::SetAutoSplit( bool flag
)
164 void FileHandler
::SetTimeStamp( bool flag
)
170 void FileHandler
::SetBaseName( const string
& s
)
176 void FileHandler
::SetMaxFrameCount( int count
)
178 assert( count
>= 0 );
179 maxFrameCount
= count
;
183 void FileHandler
::SetEveryNthFrame( int every
)
185 assert ( every
> 0 );
187 everyNthFrame
= every
;
191 void FileHandler
::SetMaxFileSize( off_t size
)
193 assert ( size
>= 0 );
199 void FileHandler
::SetSampleFrame( const Frame
& sample
)
205 bool FileHandler
::Done()
211 bool FileHandler
::WriteFrame( const Frame
& frame
)
213 static TimeCode prevTimeCode
;
216 /* If the user wants autosplit, start a new file if a
217 new recording is detected. */
218 prevTimeCode
.sec
= -1;
219 frame
.GetTimeCode( timeCode
);
220 int time_diff
= timeCode
.sec
- prevTimeCode
.sec
;
221 bool discontinuity
= prevTimeCode
.sec
!= -1 && ( time_diff
> 1 || ( time_diff
< 0 && time_diff
> -59 ) );
222 if ( FileIsOpen() && GetAutoSplit() == true && ( frame
.IsNewRecording() || discontinuity
) )
227 if ( FileIsOpen() == false )
231 static int counter
= 0;
233 if ( GetTimeStamp() == true )
235 ostringstream sb
, sb2
;
239 if ( ! frame
.GetRecordingDate( date
) )
243 gettimeofday( &tv
, &tz
);
244 localtime_r( static_cast< const time_t * >( &tv
.tv_sec
), &date
);
247 << setw( 4 ) << date
.tm_year
+ 1900 << '.'
248 << setw( 2 ) << date
.tm_mon
+ 1 << '.'
249 << setw( 2 ) << date
.tm_mday
<< '_'
250 << setw( 2 ) << date
.tm_hour
<< '-'
251 << setw( 2 ) << date
.tm_min
<< '-'
252 << setw( 2 ) << date
.tm_sec
;
254 sb2
<< GetBaseName() << recDate
<< GetExtension();
255 filename
= sb2
.str();
256 cerr
<< ">>> Trying " << filename
<< endl
;
264 sb
<< GetBaseName() << setfill( '0' ) << setw( 3 ) << ++ counter
<< GetExtension();
266 cerr
<< ">>> Trying " << filename
<< endl
;
268 while ( stat( filename
.c_str(), &stats
) == 0 );
271 SetSampleFrame( frame
);
272 if ( Create( filename
) == false )
274 cerr
<< ">>> Error creating file!" << endl
;
283 if ( framesToSkip
== 0 )
285 if ( 0 > Write( frame
) )
287 cerr
<< ">>> Error writing frame!" << endl
;
290 framesToSkip
= everyNthFrame
;
295 /* If the frame count is exceeded, close the current file.
296 If the autosplit flag is set, a new file will be created in the next iteration.
297 If the flag is not set, we are done. */
299 if ( ( GetMaxFrameCount() > 0 ) &&
300 ( framesWritten
>= GetMaxFrameCount() ) )
303 done
= !GetAutoSplit();
306 /* If the file size could be exceeded by another frame, close the current file.
307 If the autosplit flag is set, a new file will be created on the next iteration.
308 If the flag is not set, we are done. */
309 /* not exact, but should be good enough to prevent going over. */
313 frame
.GetAudioInfo( info
);
314 if ( ( GetFileSize() > 0 ) && ( GetMaxFileSize() > 0 ) &&
315 ( GetFileSize() + frame
.GetFrameSize() + info
.samples
* 4 + 12 )
316 >= GetMaxFileSize() )
317 { // 12 = sizeof chunk metadata
319 done
= !GetAutoSplit();
322 prevTimeCode
.sec
= timeCode
.sec
;
327 RawHandler
::RawHandler() : fd( -1 )
333 RawHandler
::~RawHandler()
339 bool RawHandler
::FileIsOpen()
345 bool RawHandler
::Create( const string
& filename
)
347 fd
= open( filename
.c_str(), O_CREAT
| O_TRUNC
| O_RDWR
| O_NONBLOCK
, 0644 );
350 FileTracker
::GetInstance().Add( filename
.c_str() );
351 this->filename
= filename
;
358 int RawHandler
::Write( const Frame
& frame
)
360 int result
= write( fd
, frame
.data
, frame
.GetFrameSize() );
365 int RawHandler
::Close()
376 off_t RawHandler
::GetFileSize()
378 struct stat file_status
;
379 fstat( fd
, &file_status
);
380 return file_status
.st_size
;
383 int RawHandler
::GetTotalFrames()
385 return GetFileSize() / ( 480 * numBlocks
);
389 bool RawHandler
::Open( const char *s
)
391 unsigned char data
[ 4 ];
393 fd
= open( s
, O_RDONLY
| O_NONBLOCK
);
396 if ( read( fd
, data
, 4 ) < 0 )
398 lseek( fd
, 0, SEEK_SET
);
399 numBlocks
= ( ( data
[ 3 ] & 0x80 ) == 0 ) ?
250 : 300;
405 int RawHandler
::GetFrame( uint8_t *data
, int frameNum
)
408 int size
= 480 * numBlocks
;
411 off_t offset
= ( ( off_t
) frameNum
* ( off_t
) size
);
412 fail_if( lseek( fd
, offset
, SEEK_SET
) == ( off_t
) - 1 );
413 if ( read( fd
, data
, size
) > 0 )
420 /***************************************************************************/
423 AVIHandler
::AVIHandler( int format
) : avi( NULL
), aviFormat( format
), isOpenDML( false ),
424 fccHandler( make_fourcc( "dvsd" ) ), channels( 2 ), isFullyInitialized( false ),
428 for ( int c
= 0; c
< 4; c
++ )
429 audioChannels
[ c
] = NULL
;
433 AVIHandler
::~AVIHandler()
435 if ( audioBuffer
!= NULL
)
440 for ( int c
= 0; c
< 4; c
++ )
442 if ( audioChannels
[ c
] != NULL
)
444 delete audioChannels
[ c
];
445 audioChannels
[ c
] = NULL
;
453 void AVIHandler
::SetSampleFrame( const Frame
& sample
)
456 sample
.GetAudioInfo( audioInfo
);
457 sample
.GetVideoInfo( videoInfo
);
459 sample
.GetAAUXPack( 0x50, pack
);
460 dvinfo
.dwDVAAuxSrc
= *( DWORD
* ) ( pack
.data
+ 1 );
461 sample
.GetAAUXPack( 0x51, pack
);
462 dvinfo
.dwDVAAuxCtl
= *( DWORD
* ) ( pack
.data
+ 1 );
464 sample
.GetAAUXPack( 0x52, pack
);
465 dvinfo
.dwDVAAuxSrc1
= *( DWORD
* ) ( pack
.data
+ 1 );
466 sample
.GetAAUXPack( 0x53, pack
);
467 dvinfo
.dwDVAAuxCtl1
= *( DWORD
* ) ( pack
.data
+ 1 );
469 sample
.GetVAUXPack( 0x60, pack
);
470 dvinfo
.dwDVVAuxSrc
= *( DWORD
* ) ( pack
.data
+ 1 );
471 sample
.GetVAUXPack( 0x61, pack
);
472 dvinfo
.dwDVVAuxCtl
= *( DWORD
* ) ( pack
.data
+ 1 );
476 if ( sample
.decoder
->std
== e_dv_std_smpte_314m
)
477 fccHandler
= make_fourcc( "dv25" );
482 bool AVIHandler
::FileIsOpen()
488 bool AVIHandler
::Create( const string
& filename
)
490 assert( avi
== NULL
);
496 fail_null( avi
= new AVI1File
);
497 if ( avi
->Create( filename
.c_str() ) == false )
499 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency, AVI_LARGE_INDEX );
503 fail_null( avi
= new AVI2File
);
504 if ( avi
->Create( filename
.c_str() ) == false )
506 //if ( GetOpenDML() )
507 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency,
508 //( AVI_SMALL_INDEX | AVI_LARGE_INDEX ) );
510 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency,
511 //( AVI_SMALL_INDEX ) );
515 assert( aviFormat
== AVI_DV1_FORMAT
|| aviFormat
== AVI_DV2_FORMAT
);
518 avi
->setDVINFO( dvinfo
);
519 avi
->setFccHandler( make_fourcc( "iavs" ), fccHandler
);
520 avi
->setFccHandler( make_fourcc( "vids" ), fccHandler
);
521 this->filename
= filename
;
522 FileTracker
::GetInstance().Add( filename
.c_str() );
523 return ( avi
!= NULL
);
527 int AVIHandler
::Write( const Frame
& frame
)
529 assert( avi
!= NULL
);
532 return avi
->WriteFrame( frame
) ?
0 : -1;
541 int AVIHandler
::Close()
549 if ( audioBuffer
!= NULL
)
554 for ( int c
= 0; c
< 4; c
++ )
556 if ( audioChannels
[ c
] != NULL
)
558 delete audioChannels
[ c
];
559 audioChannels
[ c
] = NULL
;
562 isFullyInitialized
= false;
566 off_t AVIHandler
::GetFileSize()
568 return avi
->GetFileSize();
571 int AVIHandler
::GetTotalFrames()
573 return avi
->GetTotalFrames();
577 bool AVIHandler
::Open( const char *s
)
579 assert( avi
== NULL
);
580 fail_null( avi
= new AVI1File
);
581 if ( avi
->Open( s
) )
585 avi
->verifyStreamFormat( make_fourcc( "dvsd" ) ) ||
586 avi
->verifyStreamFormat( make_fourcc( "DVSD" ) ) ||
587 avi
->verifyStreamFormat( make_fourcc( "dvcs" ) ) ||
588 avi
->verifyStreamFormat( make_fourcc( "DVCS" ) ) ||
589 avi
->verifyStreamFormat( make_fourcc( "dvcp" ) ) ||
590 avi
->verifyStreamFormat( make_fourcc( "DVCP" ) ) ||
591 avi
->verifyStreamFormat( make_fourcc( "CDVC" ) ) ||
592 avi
->verifyStreamFormat( make_fourcc( "cdvc" ) ) ||
593 avi
->verifyStreamFormat( make_fourcc( "DV25" ) ) ||
594 avi
->verifyStreamFormat( make_fourcc( "dv25" ) ) ) )
597 if ( avi
->verifyStream( make_fourcc( "auds" ) ) )
598 aviFormat
= AVI_DV2_FORMAT
;
600 aviFormat
= AVI_DV1_FORMAT
;
601 isOpenDML
= avi
->isOpenDML();
610 int AVIHandler
::GetFrame( uint8_t *data
, int frameNum
)
612 int result
= avi
->GetDVFrame( data
, frameNum
);
616 /* get the audio from the audio stream, if available */
617 if ( aviFormat
== AVI_DV2_FORMAT
)
621 if ( ! isFullyInitialized
&&
622 avi
->getStreamFormat( ( void* ) &wav
, make_fourcc( "auds" ) ) )
624 if ( channels
> 0 && channels
< 5 )
626 // Allocate interleaved audio buffer
627 audioBuffer
= new int16_t[ 2 * DV_AUDIO_MAX_SAMPLES
* channels
];
629 // Allocate non-interleaved audio buffers
630 for ( int c
= 0; c
< channels
; c
++ )
631 audioChannels
[ c
] = new int16_t[ 2 * DV_AUDIO_MAX_SAMPLES
];
633 // Get the audio parameters from AVI for subsequent calls to method
634 audioInfo
.channels
= wav
.nChannels
;
635 audioInfo
.frequency
= wav
.nSamplesPerSec
;
637 // Skip initialization on subsequent calls to method
638 isFullyInitialized
= true;
639 cerr
<< ">>> using audio from separate AVI audio stream" << endl
;
643 // Get the frame from AVI
644 int n
= avi
->getFrame( audioBuffer
, frameNum
, make_fourcc( "01wb" ) );
647 // Temporary pointer to audio scratch buffer
648 int16_t * s
= audioBuffer
;
650 // Determine samples in this frame
651 audioInfo
.samples
= n
/ audioInfo
.channels
/ sizeof( int16_t );
653 // Convert interleaved audio into non-interleaved
654 for ( int n
= 0; n
< audioInfo
.samples
; ++n
)
655 for ( int i
= 0; i
< audioInfo
.channels
; i
++ )
656 audioChannels
[ i
][ n
] = *s
++;
658 // Write interleaved audio into frame
659 frame
.EncodeAudio( audioInfo
, audioChannels
);
663 // Parse important metadata in DV bitstream
664 frame
.ExtractHeader();
671 void AVIHandler
::SetOpenDML( bool flag
)
677 bool AVIHandler
::GetOpenDML() const
683 /***************************************************************************/
685 #ifdef HAVE_LIBQUICKTIME
688 #define DV_AUDIO_MAX_SAMPLES 1944
691 QtHandler
::QtHandler() : fd( NULL
)
698 QtHandler
::~QtHandler()
703 void QtHandler
::Init()
710 samplesPerBuffer
= 0;
713 audioChannelBuffer
= NULL
;
714 isFullyInitialized
= false;
718 bool QtHandler
::FileIsOpen()
724 bool QtHandler
::Create( const string
& filename
)
728 if ( open( filename
.c_str(), O_CREAT
| O_TRUNC
| O_RDWR
| O_NONBLOCK
, 0644 ) != -1 )
730 fd
= quicktime_open( const_cast<char*>( filename
.c_str() ), 0, 1 );
732 FileTracker
::GetInstance().Add( filename
.c_str() );
736 this->filename
= filename
;
740 void QtHandler
::AllocateAudioBuffers()
742 if ( channels
> 0 && channels
< 5 )
744 audioBufferSize
= DV_AUDIO_MAX_SAMPLES
* 2;
745 audioBuffer
= new int16_t[ audioBufferSize
* channels
];
747 audioChannelBuffer
= new short int * [ channels
];
748 for ( int c
= 0; c
< channels
; c
++ )
749 audioChannelBuffer
[ c
] = new short int[ audioBufferSize
];
750 isFullyInitialized
= true;
754 inline void QtHandler
::DeinterlaceStereo16( void* pInput
, int iBytes
,
755 void* pLOutput
, void* pROutput
)
757 short int * piSampleInput
= ( short int* ) pInput
;
758 short int* piSampleLOutput
= ( short int* ) pLOutput
;
759 short int* piSampleROutput
= ( short int* ) pROutput
;
761 while ( ( char* ) piSampleInput
< ( ( char* ) pInput
+ iBytes
) )
763 *piSampleLOutput
++ = *piSampleInput
++;
764 *piSampleROutput
++ = *piSampleInput
++;
769 int QtHandler
::Write( const Frame
& frame
)
771 if ( ! isFullyInitialized
)
775 if ( frame
.GetAudioInfo( audio
) )
778 quicktime_set_audio( fd
, channels
, audio
.frequency
, 16, QUICKTIME_TWOS
);
785 quicktime_set_video( fd
, 1, 720, frame
.IsPAL() ?
576 : 480,
786 frame
.GetFrameRate(), QUICKTIME_DV
);
787 AllocateAudioBuffers();
790 int result
= quicktime_write_frame( fd
, const_cast<unsigned char*>( frame
.data
),
791 frame
.GetFrameSize(), 0 );
796 if ( frame
.GetAudioInfo( audio
) && ( unsigned int ) audio
.samples
< audioBufferSize
)
798 long bytesRead
= frame
.ExtractAudio( audioBuffer
);
800 DeinterlaceStereo16( audioBuffer
, bytesRead
,
801 audioChannelBuffer
[ 0 ],
802 audioChannelBuffer
[ 1 ] );
804 quicktime_encode_audio( fd
, audioChannelBuffer
, NULL
, audio
.samples
);
811 int QtHandler
::Close()
815 quicktime_close( fd
);
818 if ( audioBuffer
!= NULL
)
823 if ( audioChannelBuffer
!= NULL
)
825 for ( int c
= 0; c
< channels
; c
++ )
826 delete audioChannelBuffer
[ c
];
827 delete audioChannelBuffer
;
828 audioChannelBuffer
= NULL
;
834 off_t QtHandler
::GetFileSize()
836 struct stat file_status
;
837 fstat( fileno( fd
->stream
), &file_status
);
838 return file_status
.st_size
;
842 int QtHandler
::GetTotalFrames()
844 return ( int ) quicktime_video_length( fd
, 0 );
848 bool QtHandler
::Open( const char *s
)
852 fd
= quicktime_open( ( char * ) s
, 1, 0 );
855 fprintf( stderr
, "Error opening: %s\n", s
);
859 if ( quicktime_has_video( fd
) <= 0 )
861 fprintf( stderr
, "There must be at least one video track in the input file (%s).\n",
866 char * fcc
= quicktime_video_compressor( fd
, 0 );
867 if ( strncmp( fcc
, QUICKTIME_DV
, 4 ) != 0 &&
868 strncmp( fcc
, QUICKTIME_DV_AVID
, 4 ) != 0 &&
869 strncmp( fcc
, QUICKTIME_DV_AVID_A
, 4 ) != 0 )
874 if ( quicktime_has_audio( fd
) )
875 channels
= quicktime_track_channels( fd
, 0 );
880 int QtHandler
::GetFrame( uint8_t *data
, int frameNum
)
882 assert( fd
!= NULL
);
884 quicktime_set_video_position( fd
, frameNum
, 0 );
885 quicktime_read_frame( fd
, data
, 0 );
888 if ( quicktime_has_audio( fd
) )
893 if ( ! isFullyInitialized
)
895 cerr
<< ">>> using audio from separarate Quicktime audio track" << endl
;
896 AllocateAudioBuffers();
899 info
.channels
= channels
;
900 info
.frequency
= quicktime_sample_rate( fd
, 0 );
901 samples
= info
.frequency
/ quicktime_frame_rate( fd
, 0 );
902 info
.samples
= (int) samples
;
903 for ( int i
= 0; i
< channels
; i
++ )
905 quicktime_set_audio_position( fd
, ( int64_t )( frameNum
* samples
), 0 );
906 quicktime_decode_audio( fd
, audioChannelBuffer
[ i
], NULL
, (long) samples
, i
);
908 frame
.EncodeAudio( info
, audioChannelBuffer
);
910 frame
.ExtractHeader();