@@ -204,6 +204,57 @@ int update_recording_metadata(uint64_t id, time_t end_time,
204204 return 0 ;
205205}
206206
207+ /**
208+ * Correct the start_time of an existing recording in the database.
209+ *
210+ * Used after flushing the pre-event circular buffer into a detection recording
211+ * so that the stored start_time matches the actual first packet timestamp
212+ * rather than the time mp4_writer_create() was called.
213+ */
214+ int update_recording_start_time (uint64_t id , time_t start_time ) {
215+ int rc ;
216+ sqlite3_stmt * stmt ;
217+
218+ sqlite3 * db = get_db_handle ();
219+ pthread_mutex_t * db_mutex = get_db_mutex ();
220+
221+ if (!db ) {
222+ log_error ("Database not initialized" );
223+ return -1 ;
224+ }
225+
226+ pthread_mutex_lock (db_mutex );
227+
228+ const char * sql = "UPDATE recordings SET start_time = ? WHERE id = ?;" ;
229+
230+ rc = sqlite3_prepare_v2 (db , sql , -1 , & stmt , NULL );
231+ if (rc != SQLITE_OK ) {
232+ log_error ("Failed to prepare update_recording_start_time statement: %s" ,
233+ sqlite3_errmsg (db ));
234+ pthread_mutex_unlock (db_mutex );
235+ return -1 ;
236+ }
237+
238+ sqlite3_bind_int64 (stmt , 1 , (sqlite3_int64 )start_time );
239+ sqlite3_bind_int64 (stmt , 2 , (sqlite3_int64 )id );
240+
241+ rc = sqlite3_step (stmt );
242+ if (rc != SQLITE_DONE ) {
243+ log_error ("Failed to update recording start_time (id=%lu): %s" ,
244+ (unsigned long )id , sqlite3_errmsg (db ));
245+ sqlite3_finalize (stmt );
246+ pthread_mutex_unlock (db_mutex );
247+ return -1 ;
248+ }
249+
250+ sqlite3_finalize (stmt );
251+ pthread_mutex_unlock (db_mutex );
252+
253+ log_debug ("Corrected start_time for recording ID %lu to %ld" ,
254+ (unsigned long )id , (long )start_time );
255+ return 0 ;
256+ }
257+
207258// Get recording metadata by ID
208259int get_recording_metadata_by_id (uint64_t id , recording_metadata_t * metadata ) {
209260 int rc ;
0 commit comments