From 983cf78761afff85dd85804719e50227e409275d Mon Sep 17 00:00:00 2001
From: rogerdpack <rogerpack2005@gmail.com>
Date: Wed, 24 Jun 2015 04:18:38 -0600
Subject: [PATCH] windows: respond to logoff and ctrl+break messages

Signed-off-by: rogerdpack <rogerpack2005@gmail.com>
---
 configure |  2 ++
 ffmpeg.c  | 33 ++++++++++++++++++++++++++++++++-
 2 files changed, 34 insertions(+), 1 deletion(-)

diff --git a/configure b/configure
index 0620936..2dc6df8 100755
--- a/configure
+++ b/configure
@@ -1787,6 +1787,7 @@ SYSTEM_FUNCS="
     pthread_cancel
     sched_getaffinity
     SetConsoleTextAttribute
+    SetConsoleCtrlHandler
     setmode
     setrlimit
     Sleep
@@ -4987,6 +4988,7 @@ check_func_headers windows.h GetSystemTimeAsFileTime
 check_func_headers windows.h MapViewOfFile
 check_func_headers windows.h PeekNamedPipe
 check_func_headers windows.h SetConsoleTextAttribute
+check_func_headers windows.h SetConsoleCtrlHandler
 check_func_headers windows.h Sleep
 check_func_headers windows.h VirtualAlloc
 check_struct windows.h "CONDITION_VARIABLE" Ptr
diff --git a/ffmpeg.c b/ffmpeg.c
index f502998..720e105 100644
--- a/ffmpeg.c
+++ b/ffmpeg.c
@@ -22,7 +22,6 @@
  * @file
  * multimedia converter based on the FFmpeg libraries
  */
-
 #include "config.h"
 #include <ctype.h>
 #include <string.h>
@@ -79,6 +78,10 @@
 #include <windows.h>
 #include <psapi.h>
 #endif
+#ifdef HAVE_SETCONSOLECTRLHANDLER
+#include <windows.h>
+#endif
+
 
 #if HAVE_SYS_SELECT_H
 #include <sys/select.h>
@@ -325,6 +328,31 @@ sigterm_handler(int sig)
         exit(123);
 }
 
+#ifdef HAVE_SETCONSOLECTRLHANDLER
+static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
+{
+    av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %d\n", fdwCtrlType);
+
+    switch (fdwCtrlType)
+    {
+    case CTRL_C_EVENT:
+    case CTRL_BREAK_EVENT:
+        sigterm_handler(SIGINT);
+        return TRUE;
+
+    case CTRL_CLOSE_EVENT:
+    case CTRL_LOGOFF_EVENT:
+    case CTRL_SHUTDOWN_EVENT:
+        sigterm_handler(SIGTERM);
+        return TRUE;
+
+    default:
+        av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %d\n", fdwCtrlType);
+        return FALSE;
+    }
+}
+#endif
+
 void term_init(void)
 {
 #if HAVE_TERMIOS_H
@@ -358,6 +386,9 @@ void term_init(void)
 #ifdef SIGXCPU
     signal(SIGXCPU, sigterm_handler);
 #endif
+#ifdef HAVE_SETCONSOLECTRLHANDLER
+    SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
+#endif
 }
 
 /* read a key without blocking */
-- 
1.9.5.msysgit.0

