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
;
46 #include "filehandler.h"
51 FileTracker
*FileTracker
::instance
= NULL
;
53 FileTracker
::FileTracker( ) : mode( CAPTURE_MOVIE_APPEND
)
55 cerr
<< ">> Constructing File Capture tracker" << endl
;
58 FileTracker
::~FileTracker( )
60 cerr
<< ">> Destroying File Capture tracker" << endl
;
63 FileTracker
&FileTracker
::GetInstance( )
65 if ( instance
== NULL
)
66 instance
= new FileTracker();
71 void FileTracker
::SetMode( FileCaptureMode mode
)
76 FileCaptureMode FileTracker
::GetMode( )
81 char *FileTracker
::Get( int index
)
86 void FileTracker
::Add( const char *file
)
88 if ( this->mode
!= CAPTURE_IGNORE
)
90 cerr
<< ">>>> Registering " << file
<< " with the tracker" << endl
;
91 list
.push_back( strdup( file
) );
95 unsigned int FileTracker
::Size( )
100 void FileTracker
::Clear( )
104 free( list
[ Size() - 1 ] );
107 this->mode
= CAPTURE_MOVIE_APPEND
;
110 FileHandler
::FileHandler() : done( false ), autoSplit( false ), maxFrameCount( 999999 ),
111 framesWritten( 0 ), filename( "" )
117 FileHandler
::~FileHandler()
123 bool FileHandler
::GetAutoSplit() const
129 bool FileHandler
::GetTimeStamp() const
135 string FileHandler
::GetBaseName() const
141 string FileHandler
::GetExtension() const
147 int FileHandler
::GetMaxFrameCount() const
149 return maxFrameCount
;
152 off_t FileHandler
::GetMaxFileSize() const
157 string FileHandler
::GetFilename() const
163 void FileHandler
::SetAutoSplit( bool flag
)
169 void FileHandler
::SetTimeStamp( bool flag
)
175 void FileHandler
::SetBaseName( const string
& s
)
181 void FileHandler
::SetMaxFrameCount( int count
)
183 assert( count
>= 0 );
184 maxFrameCount
= count
;
188 void FileHandler
::SetEveryNthFrame( int every
)
190 assert ( every
> 0 );
192 everyNthFrame
= every
;
196 void FileHandler
::SetMaxFileSize( off_t size
)
198 assert ( size
>= 0 );
204 void FileHandler
::SetSampleFrame( const Frame
& sample
)
210 bool FileHandler
::Done()
216 bool FileHandler
::WriteFrame( const Frame
& frame
)
218 static TimeCode prevTimeCode
;
221 /* If the user wants autosplit, start a new file if a
222 new recording is detected. */
223 prevTimeCode
.sec
= -1;
224 frame
.GetTimeCode( timeCode
);
225 int time_diff
= timeCode
.sec
- prevTimeCode
.sec
;
226 bool discontinuity
= prevTimeCode
.sec
!= -1 && ( time_diff
> 1 || ( time_diff
< 0 && time_diff
> -59 ) );
227 if ( FileIsOpen() && GetAutoSplit() == true && ( frame
.IsNewRecording() || discontinuity
) )
232 if ( FileIsOpen() == false )
236 static int counter
= 0;
238 if ( GetTimeStamp() == true )
240 ostringstream sb
, sb2
;
244 if ( ! frame
.GetRecordingDate( date
) )
248 gettimeofday( &tv
, &tz
);
249 localtime_r( static_cast< const time_t * >( &tv
.tv_sec
), &date
);
252 << setw( 4 ) << date
.tm_year
+ 1900 << '.'
253 << setw( 2 ) << date
.tm_mon
+ 1 << '.'
254 << setw( 2 ) << date
.tm_mday
<< '_'
255 << setw( 2 ) << date
.tm_hour
<< '-'
256 << setw( 2 ) << date
.tm_min
<< '-'
257 << setw( 2 ) << date
.tm_sec
;
259 sb2
<< GetBaseName() << recDate
<< GetExtension();
260 filename
= sb2
.str();
261 cerr
<< ">>> Trying " << filename
<< endl
;
269 sb
<< GetBaseName() << setfill( '0' ) << setw( 3 ) << ++ counter
<< GetExtension();
271 cerr
<< ">>> Trying " << filename
<< endl
;
273 while ( stat( filename
.c_str(), &stats
) == 0 );
276 SetSampleFrame( frame
);
277 if ( Create( filename
) == false )
279 cerr
<< ">>> Error creating file!" << endl
;
288 if ( framesToSkip
== 0 )
290 if ( 0 > Write( frame
) )
292 cerr
<< ">>> Error writing frame!" << endl
;
295 framesToSkip
= everyNthFrame
;
300 /* If the frame count is exceeded, close the current file.
301 If the autosplit flag is set, a new file will be created in the next iteration.
302 If the flag is not set, we are done. */
304 if ( ( GetMaxFrameCount() > 0 ) &&
305 ( framesWritten
>= GetMaxFrameCount() ) )
308 done
= !GetAutoSplit();
311 /* If the file size could be exceeded by another frame, close the current file.
312 If the autosplit flag is set, a new file will be created on the next iteration.
313 If the flag is not set, we are done. */
314 /* not exact, but should be good enough to prevent going over. */
318 frame
.GetAudioInfo( info
);
319 if ( ( GetFileSize() > 0 ) && ( GetMaxFileSize() > 0 ) &&
320 ( GetFileSize() + frame
.GetFrameSize() + info
.samples
* 4 + 12 )
321 >= GetMaxFileSize() )
322 { // 12 = sizeof chunk metadata
324 done
= !GetAutoSplit();
327 prevTimeCode
.sec
= timeCode
.sec
;
332 RawHandler
::RawHandler() : fd( -1 )
338 RawHandler
::~RawHandler()
344 bool RawHandler
::FileIsOpen()
350 bool RawHandler
::Create( const string
& filename
)
352 fd
= open( filename
.c_str(), O_CREAT
| O_TRUNC
| O_RDWR
| O_NONBLOCK
, 0644 );
355 FileTracker
::GetInstance().Add( filename
.c_str() );
356 this->filename
= filename
;
363 int RawHandler
::Write( const Frame
& frame
)
365 int result
= write( fd
, frame
.data
, frame
.GetFrameSize() );
370 int RawHandler
::Close()
381 off_t RawHandler
::GetFileSize()
383 struct stat file_status
;
384 fstat( fd
, &file_status
);
385 return file_status
.st_size
;
388 int RawHandler
::GetTotalFrames()
390 return GetFileSize() / ( 480 * numBlocks
);
394 bool RawHandler
::Open( const char *s
)
396 unsigned char data
[ 4 ];
398 fd
= open( s
, O_RDONLY
| O_NONBLOCK
);
401 if ( read( fd
, data
, 4 ) < 0 )
403 lseek( fd
, 0, SEEK_SET
);
404 numBlocks
= ( ( data
[ 3 ] & 0x80 ) == 0 ) ?
250 : 300;
410 int RawHandler
::GetFrame( uint8_t *data
, int frameNum
)
413 int size
= 480 * numBlocks
;
416 off_t offset
= ( ( off_t
) frameNum
* ( off_t
) size
);
417 fail_if( lseek( fd
, offset
, SEEK_SET
) == ( off_t
) - 1 );
418 if ( read( fd
, data
, size
) > 0 )
425 /***************************************************************************/
428 AVIHandler
::AVIHandler( int format
) : avi( NULL
), aviFormat( format
), isOpenDML( false ),
429 fccHandler( make_fourcc( "dvsd" ) ), channels( 2 ), isFullyInitialized( false ),
433 for ( int c
= 0; c
< 4; c
++ )
434 audioChannels
[ c
] = NULL
;
438 AVIHandler
::~AVIHandler()
440 if ( audioBuffer
!= NULL
)
445 for ( int c
= 0; c
< 4; c
++ )
447 if ( audioChannels
[ c
] != NULL
)
449 delete audioChannels
[ c
];
450 audioChannels
[ c
] = NULL
;
458 void AVIHandler
::SetSampleFrame( const Frame
& sample
)
461 sample
.GetAudioInfo( audioInfo
);
462 sample
.GetVideoInfo( videoInfo
);
464 sample
.GetAAUXPack( 0x50, pack
);
465 dvinfo
.dwDVAAuxSrc
= *( DWORD
* ) ( pack
.data
+ 1 );
466 sample
.GetAAUXPack( 0x51, pack
);
467 dvinfo
.dwDVAAuxCtl
= *( DWORD
* ) ( pack
.data
+ 1 );
469 sample
.GetAAUXPack( 0x52, pack
);
470 dvinfo
.dwDVAAuxSrc1
= *( DWORD
* ) ( pack
.data
+ 1 );
471 sample
.GetAAUXPack( 0x53, pack
);
472 dvinfo
.dwDVAAuxCtl1
= *( DWORD
* ) ( pack
.data
+ 1 );
474 sample
.GetVAUXPack( 0x60, pack
);
475 dvinfo
.dwDVVAuxSrc
= *( DWORD
* ) ( pack
.data
+ 1 );
476 sample
.GetVAUXPack( 0x61, pack
);
477 dvinfo
.dwDVVAuxCtl
= *( DWORD
* ) ( pack
.data
+ 1 );
481 if ( sample
.decoder
->std
== e_dv_std_smpte_314m
)
482 fccHandler
= make_fourcc( "dv25" );
487 bool AVIHandler
::FileIsOpen()
493 bool AVIHandler
::Create( const string
& filename
)
495 assert( avi
== NULL
);
501 fail_null( avi
= new AVI1File
);
502 if ( avi
->Create( filename
.c_str() ) == false )
504 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency, AVI_LARGE_INDEX );
508 fail_null( avi
= new AVI2File
);
509 if ( avi
->Create( filename
.c_str() ) == false )
511 //if ( GetOpenDML() )
512 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency,
513 //( AVI_SMALL_INDEX | AVI_LARGE_INDEX ) );
515 //avi->Init( videoInfo.isPAL ? AVI_PAL : AVI_NTSC, audioInfo.frequency,
516 //( AVI_SMALL_INDEX ) );
520 assert( aviFormat
== AVI_DV1_FORMAT
|| aviFormat
== AVI_DV2_FORMAT
);
523 avi
->setDVINFO( dvinfo
);
524 avi
->setFccHandler( make_fourcc( "iavs" ), fccHandler
);
525 avi
->setFccHandler( make_fourcc( "vids" ), fccHandler
);
526 this->filename
= filename
;
527 FileTracker
::GetInstance().Add( filename
.c_str() );
528 return ( avi
!= NULL
);
532 int AVIHandler
::Write( const Frame
& frame
)
534 assert( avi
!= NULL
);
537 return avi
->WriteFrame( frame
) ?
0 : -1;
546 int AVIHandler
::Close()
554 if ( audioBuffer
!= NULL
)
559 for ( int c
= 0; c
< 4; c
++ )
561 if ( audioChannels
[ c
] != NULL
)
563 delete audioChannels
[ c
];
564 audioChannels
[ c
] = NULL
;
567 isFullyInitialized
= false;
571 off_t AVIHandler
::GetFileSize()
573 return avi
->GetFileSize();
576 int AVIHandler
::GetTotalFrames()
578 return avi
->GetTotalFrames();
582 bool AVIHandler
::Open( const char *s
)
584 assert( avi
== NULL
);
585 fail_null( avi
= new AVI1File
);
586 if ( avi
->Open( s
) )
590 avi
->verifyStreamFormat( make_fourcc( "dvsd" ) ) ||
591 avi
->verifyStreamFormat( make_fourcc( "DVSD" ) ) ||
592 avi
->verifyStreamFormat( make_fourcc( "dvcs" ) ) ||
593 avi
->verifyStreamFormat( make_fourcc( "DVCS" ) ) ||
594 avi
->verifyStreamFormat( make_fourcc( "dvcp" ) ) ||
595 avi
->verifyStreamFormat( make_fourcc( "DVCP" ) ) ||
596 avi
->verifyStreamFormat( make_fourcc( "CDVC" ) ) ||
597 avi
->verifyStreamFormat( make_fourcc( "cdvc" ) ) ||
598 avi
->verifyStreamFormat( make_fourcc( "DV25" ) ) ||
599 avi
->verifyStreamFormat( make_fourcc( "dv25" ) ) ) )
602 if ( avi
->verifyStream( make_fourcc( "auds" ) ) )
603 aviFormat
= AVI_DV2_FORMAT
;
605 aviFormat
= AVI_DV1_FORMAT
;
606 isOpenDML
= avi
->isOpenDML();
615 int AVIHandler
::GetFrame( uint8_t *data
, int frameNum
)
617 int result
= avi
->GetDVFrame( data
, frameNum
);
621 /* get the audio from the audio stream, if available */
622 if ( aviFormat
== AVI_DV2_FORMAT
)
626 if ( ! isFullyInitialized
&&
627 avi
->getStreamFormat( ( void* ) &wav
, make_fourcc( "auds" ) ) )
629 if ( channels
> 0 && channels
< 5 )
631 // Allocate interleaved audio buffer
632 audioBuffer
= new int16_t[ 2 * DV_AUDIO_MAX_SAMPLES
* channels
];
634 // Allocate non-interleaved audio buffers
635 for ( int c
= 0; c
< channels
; c
++ )
636 audioChannels
[ c
] = new int16_t[ 2 * DV_AUDIO_MAX_SAMPLES
];
638 // Get the audio parameters from AVI for subsequent calls to method
639 audioInfo
.channels
= wav
.nChannels
;
640 audioInfo
.frequency
= wav
.nSamplesPerSec
;
642 // Skip initialization on subsequent calls to method
643 isFullyInitialized
= true;
644 cerr
<< ">>> using audio from separate AVI audio stream" << endl
;
648 // Get the frame from AVI
649 int n
= avi
->getFrame( audioBuffer
, frameNum
, make_fourcc( "01wb" ) );
652 // Temporary pointer to audio scratch buffer
653 int16_t * s
= audioBuffer
;
655 // Determine samples in this frame
656 audioInfo
.samples
= n
/ audioInfo
.channels
/ sizeof( int16_t );
658 // Convert interleaved audio into non-interleaved
659 for ( int n
= 0; n
< audioInfo
.samples
; ++n
)
660 for ( int i
= 0; i
< audioInfo
.channels
; i
++ )
661 audioChannels
[ i
][ n
] = *s
++;
663 // Write interleaved audio into frame
664 frame
.EncodeAudio( audioInfo
, audioChannels
);
668 // Parse important metadata in DV bitstream
669 frame
.ExtractHeader();
676 void AVIHandler
::SetOpenDML( bool flag
)
682 bool AVIHandler
::GetOpenDML() const
688 /***************************************************************************/
690 #ifdef HAVE_LIBQUICKTIME
693 #define DV_AUDIO_MAX_SAMPLES 1944
696 QtHandler
::QtHandler() : fd( NULL
)
703 QtHandler
::~QtHandler()
708 void QtHandler
::Init()
715 samplesPerBuffer
= 0;
718 audioChannelBuffer
= NULL
;
719 isFullyInitialized
= false;
723 bool QtHandler
::FileIsOpen()
729 bool QtHandler
::Create( const string
& filename
)
733 if ( open( filename
.c_str(), O_CREAT
| O_TRUNC
| O_RDWR
| O_NONBLOCK
, 0644 ) != -1 )
735 fd
= quicktime_open( const_cast<char*>( filename
.c_str() ), 0, 1 );
737 FileTracker
::GetInstance().Add( filename
.c_str() );
741 this->filename
= filename
;
745 void QtHandler
::AllocateAudioBuffers()
747 if ( channels
> 0 && channels
< 5 )
749 audioBufferSize
= DV_AUDIO_MAX_SAMPLES
* 2;
750 audioBuffer
= new int16_t[ audioBufferSize
* channels
];
752 audioChannelBuffer
= new short int * [ channels
];
753 for ( int c
= 0; c
< channels
; c
++ )
754 audioChannelBuffer
[ c
] = new short int[ audioBufferSize
];
755 isFullyInitialized
= true;
759 inline void QtHandler
::DeinterlaceStereo16( void* pInput
, int iBytes
,
760 void* pLOutput
, void* pROutput
)
762 short int * piSampleInput
= ( short int* ) pInput
;
763 short int* piSampleLOutput
= ( short int* ) pLOutput
;
764 short int* piSampleROutput
= ( short int* ) pROutput
;
766 while ( ( char* ) piSampleInput
< ( ( char* ) pInput
+ iBytes
) )
768 *piSampleLOutput
++ = *piSampleInput
++;
769 *piSampleROutput
++ = *piSampleInput
++;
774 int QtHandler
::Write( const Frame
& frame
)
776 if ( ! isFullyInitialized
)
780 if ( frame
.GetAudioInfo( audio
) )
783 quicktime_set_audio( fd
, channels
, audio
.frequency
, 16, QUICKTIME_TWOS
);
790 quicktime_set_video( fd
, 1, 720, frame
.IsPAL() ?
576 : 480,
791 frame
.GetFrameRate(), QUICKTIME_DV
);
792 AllocateAudioBuffers();
795 int result
= quicktime_write_frame( fd
, const_cast<unsigned char*>( frame
.data
),
796 frame
.GetFrameSize(), 0 );
801 if ( frame
.GetAudioInfo( audio
) && ( unsigned int ) audio
.samples
< audioBufferSize
)
803 long bytesRead
= frame
.ExtractAudio( audioBuffer
);
805 DeinterlaceStereo16( audioBuffer
, bytesRead
,
806 audioChannelBuffer
[ 0 ],
807 audioChannelBuffer
[ 1 ] );
809 quicktime_encode_audio( fd
, audioChannelBuffer
, NULL
, audio
.samples
);
816 int QtHandler
::Close()
820 quicktime_close( fd
);
823 if ( audioBuffer
!= NULL
)
828 if ( audioChannelBuffer
!= NULL
)
830 for ( int c
= 0; c
< channels
; c
++ )
831 delete audioChannelBuffer
[ c
];
832 delete audioChannelBuffer
;
833 audioChannelBuffer
= NULL
;
839 off_t QtHandler
::GetFileSize()
841 struct stat file_status
;
842 fstat( fileno( fd
->stream
), &file_status
);
843 return file_status
.st_size
;
847 int QtHandler
::GetTotalFrames()
849 return ( int ) quicktime_video_length( fd
, 0 );
853 bool QtHandler
::Open( const char *s
)
857 fd
= quicktime_open( ( char * ) s
, 1, 0 );
860 fprintf( stderr
, "Error opening: %s\n", s
);
864 if ( quicktime_has_video( fd
) <= 0 )
866 fprintf( stderr
, "There must be at least one video track in the input file (%s).\n",
871 char * fcc
= quicktime_video_compressor( fd
, 0 );
872 if ( strncmp( fcc
, QUICKTIME_DV
, 4 ) != 0 &&
873 strncmp( fcc
, QUICKTIME_DV_AVID
, 4 ) != 0 &&
874 strncmp( fcc
, QUICKTIME_DV_AVID_A
, 4 ) != 0 )
879 if ( quicktime_has_audio( fd
) )
880 channels
= quicktime_track_channels( fd
, 0 );
885 int QtHandler
::GetFrame( uint8_t *data
, int frameNum
)
887 assert( fd
!= NULL
);
889 quicktime_set_video_position( fd
, frameNum
, 0 );
890 quicktime_read_frame( fd
, data
, 0 );
893 if ( quicktime_has_audio( fd
) )
895 if ( ! isFullyInitialized
)
896 AllocateAudioBuffers();
898 int frequency
= quicktime_sample_rate( fd
, 0 );
899 int samples
= ( int )( frequency
/ quicktime_frame_rate( fd
, 0 ) );
900 for ( int i
= 0; i
< channels
; i
++ )
902 quicktime_set_audio_position( fd
, ( int64_t )( frameNum
* samples
), 0 );
903 quicktime_decode_audio( fd
, audioChannelBuffer
[ i
], NULL
, (long) samples
, i
);
905 dv_encoder_t
*encoder
= dv_encoder_new( 0, 0, 0 );
906 encoder
->samples_this_frame
= samples
;
907 dv_encode_full_audio( encoder
, audioChannelBuffer
, channels
, frequency
, data
);
908 dv_encoder_free( encoder
);