forked from michaelmob/WebMCam
/
Form_Main.cs
422 lines (370 loc) · 15.1 KB
/
Form_Main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using Amib.Threading;
using System.Runtime.InteropServices;
namespace WebMCam
{
public partial class Form_Main : Form
{
static int FPS;
static List<Bitmap> Frames = new List<Bitmap>();
static int Frame_Count, Saved_Frame_Count;
int Time_Elapsed;
const double Version = 1.40;
string Temp_Storage;
Rectangle Record_Rectangle, Desktop_Rectangle;
Boolean Is_Recording, Is_Saving, Follow_Mouse = false;
//Native methods for global hotkey
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
PixelFormat Pixel_Format;
ImageFormat Image_Format;
string Image_Extension;
// Amib Smart Thread Pool
static SmartThreadPool Thread_Pool = new SmartThreadPool();
public Form_Settings Settings;
Audio_Capture Audio_Capture = new Audio_Capture();
private int lastX;
private int lastY;
private int offsetY;
public Form_Main()
{
InitializeComponent();
}
void MainFormLoad(object sender, EventArgs e)
{
// Load Settings
Settings = new Form_Settings();
// Restore window size from previous session
var Size = Ini_File.Exists("Frm", "size", "0,0");
// Catch if size is incorrect and fix it if it is
try
{
if (Size != "0,0")
{
var Size_Split = Size.Split(',');
this.Size = new Size(Convert.ToInt32(Size_Split[0]), Convert.ToInt32(Size_Split[1]));
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Ini_File.Write("Frm", "size", "0,0");
}
// Hit the method so the title sets the size
MainFormResize(sender, e);
//Register Hotkey
RegisterHotKey(this.Handle, 0x9724, (int)KeyModifier.Control, (int)Keys.F12);
}
void MainFormResize(object sender, EventArgs e)
{
Text = string.Format("WebMCam {0} | {1}x{2}", Version, Panel_Record.Size.Width, Panel_Record.Size.Height);
Form_MainMove(sender, e);
}
void Form_MainMove(object sender, EventArgs e)
{
var pt = Panel_Record.PointToScreen(new Point(0, 0));
Record_Rectangle = new Rectangle(pt.X, pt.Y, Panel_Record.Width, Panel_Record.Height);
}
void Chk_top_mostCheckedChanged(object sender, EventArgs e)
{
this.TopMost = chk_Top_Most.Checked;
}
void bgw_captureDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
while (timer_Elapsed.Enabled)
{
Thread_Pool.QueueWorkItem(new Amib.Threading.Func<PixelFormat, int>(capture_screen), Pixel_Format);
Thread.Sleep(1000 / FPS);
}
}
int capture_screen(PixelFormat format)
{
try
{
Frames.Add(Image_Capture.region(Record_Rectangle, chk_Cursor.Checked, format));
Frame_Count++;
}
catch
{
Frames.RemoveAt(1);
Debug.WriteLine("Out of memory!");
GC.Collect();
//MessageBox.Show("Ran out of memory!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return 0;
}
void Bgw_mouseFollowWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
while (timer_Elapsed.Enabled||Is_Recording)
{
if (Follow_Mouse) //Code for mouse following
{
var mousePoint = MousePosition;
var midX = Record_Rectangle.Width / 2;
var newX = mousePoint.X - midX;
var maxX = Desktop_Rectangle.Width - Record_Rectangle.Width - 8;
if (newX != this.lastX)
this.Invoke((MethodInvoker)(() =>
{
if (!(this.Disposing || this.IsDisposed))
this.Left = newX < -8 ? -8 : newX > maxX ? maxX : newX;
}));
this.lastX = newX;
var midY = Record_Rectangle.Height / 2;
var newY = mousePoint.Y - midY - Height + Record_Rectangle.Height;
var maxY = Desktop_Rectangle.Height - Record_Rectangle.Height + offsetY;
if (newY != this.lastY)
this.Invoke((MethodInvoker)(() =>
{
if (!(this.Disposing || this.IsDisposed))
this.Top = newY < offsetY ? offsetY : newY > maxY ? maxY : newY;
}));
this.lastY = newY;
}
}
}
void Bgw_saveDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
while (Is_Saving || timer_Elapsed.Enabled)
{
if (Frames.Count > 1)
{
try
{
// Save First Frame
Frames[0].Save(
Path.Combine(
Temp_Storage, string.Format("{0}.{1}", Saved_Frame_Count + 1, Image_Extension)
),
Image_Format
);
// Remove Frame now
Frames.RemoveAt(0);
Saved_Frame_Count++;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
else if (!timer_Elapsed.Enabled)
{
Is_Saving = false;
}
}
}
void Bgw_saveProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
Progress_Bar.Value = e.ProgressPercentage;
}
void Start_Record(int _fps)
{
// Set record rectangle
Form_MainMove(null, null);
// Dispose of each frame, if it's not empty
if (Frames.Count > 1)
{
for (int i = 0; i < Frames.Count; i++)
{
Frames[i].Dispose();
}
}
Temp_Storage = Path.Combine(
Settings.loc_temp, string.Format("WebMCam-{0}\\", DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond)
);
// If our temp dir doesn't exist we need to create it
if (!Directory.Exists(Temp_Storage))
Directory.CreateDirectory(Temp_Storage);
int threads = Convert.ToInt32(Settings.rec_threads);
Thread_Pool.Concurrency = threads;
// FPS
FPS = _fps;
// Framerate
Frame_Count = 0;
Saved_Frame_Count = 0;
Time_Elapsed = 1;
// Set Formats
Image_Format = Image_Capture.Image_Format(Settings.fmt_image);
Pixel_Format = Image_Capture.Pixel_Format(Settings.fmt_pixel);
Image_Extension = Settings.fmt_image;
// Set Saving & Recording variables
Is_Saving = true;
Is_Recording = true;
// Record Screen
timer_Elapsed.Start();
bgw_Capture.RunWorkerAsync();
bgw_Save.RunWorkerAsync();
bgw_MouseFollow.RunWorkerAsync();
// Record Audio
if (chk_Sound.Checked)
this.Audio_Capture.Start(Path.Combine(Temp_Storage, "audio.wav"));
}
void Stop_Record()
{
Is_Recording = false;
// Stop Sound Recording
this.Audio_Capture.Stop();
// Stop Screen Recording
Thread_Pool.Concurrency = 0;
timer_Elapsed.Stop();
bgw_Capture.CancelAsync();
bgw_MouseFollow.CancelAsync();
Progress_Bar.Value = 0;
Progress_Bar.Visible = true;
while (Is_Saving)
{
Progress_Bar.Value = Convert.ToInt32(((float)Saved_Frame_Count / (float)Frame_Count) * 100);
Thread.Sleep(1000);
}
this.Visible = false;
bool Save_Frames = true;
if (!chk_Sound.Checked)
{
Form_Frames Frames_Form = new Form_Frames(Temp_Storage, Settings.fmt_image);
Save_Frames = Frames_Form.ShowDialog() == DialogResult.OK;
}
if (Save_Frames) //Save only if there is frames
{
// Show dialog and only continue if OK.
var Save_Dialog = new SaveFileDialog();
Save_Dialog.Title = "Select a location and name for your webm";
Save_Dialog.Filter = "WebM (*.webm)|*.webm|All files (*.*)|*.*";
if (Save_Dialog.ShowDialog() == DialogResult.OK)
{
// The SaveFileDialog handled overwrite requesting
if (File.Exists(Save_Dialog.FileName))
File.Delete(Save_Dialog.FileName);
Form_Output form_output = new Form_Output(
Temp_Storage,
Settings.loc_ffmpeg,
Save_Dialog.FileName,
Settings.cmd_args
.Replace("%temp%", "")
.Replace("%duration%", Convert.ToString(Time_Elapsed + 1))
.Replace("%bitrate%", Convert.ToString((3 * 8192) / Time_Elapsed) + "k")
.Replace("%format%", Settings.fmt_image)
.Replace("%rfps%", Convert.ToString(Frame_Count / Time_Elapsed))
.Replace("%audio%", chk_Sound.Checked ? "-i audio.wav" : "")
.Replace("%fps%", Convert.ToString(num_FPS.Value))
+ " \"" + Save_Dialog.FileName + "\"",
Frame_Count
);
form_output.ShowDialog();
form_output.BringToFront();
}
}
// Delete our temp storage folder?
if (Settings.fmt_delete == "True")
Directory.Delete(Temp_Storage, true);
// Restart WebMCam so no errors
Application.Restart();
}
//Enum for the modifiers
enum KeyModifier
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
WinKey = 8
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x312) //Hotkey
{
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
if (key == Keys.F12) //F12 pressed
{
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF);
if (modifier == KeyModifier.Control) //With Control
Btn_recordClick(this, EventArgs.Empty); //Simulate the record button pressing
}
}
}
void Btn_recordClick(object sender, EventArgs e)
{
if (!File.Exists(Settings.loc_ffmpeg))
{
MessageBox.Show(
"Could not find FFmpeg.exe, please change your settings to set the FFmpeg.exe location.",
"ffmpeg.exe",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
return;
}
if (Is_Recording)
{
// Now that we're done recording, set back to Record
// and allow any maximum size
this.MinimumSize = new Size(107, 155);
this.MaximumSize = new Size(0, 0);
Stop_Record();
MainFormResize(sender, e);
btn_Record.Text = "Record (CTRL+F12)";
}
else
{
// If we're recording, let's set the minimum and maximum size
// limits so we don't get an error while trying to convert
// with ffmpeg due to different image sizes
this.MinimumSize = new Size(this.Width, this.Height);
this.MaximumSize = new Size(this.Width, this.Height);
Start_Record(Convert.ToInt32(num_FPS.Value));
btn_Record.Text = "Stop (CTRL+F12)";
}
}
void Btn_settingsClick(object sender, EventArgs e)
{
this.TopMost = false;
Settings.ShowDialog();
this.TopMost = chk_Top_Most.Checked;
}
void Timer_elapsedTick(object sender, EventArgs e)
{
FPS = Frame_Count / Time_Elapsed;
this.Text = string.Format(
"{0}s, RECORDING | {3} fps ({1} frames / {2} saved) (Threads: {4})",
Time_Elapsed, Frame_Count, Saved_Frame_Count,
FPS, Thread_Pool.ActiveThreads
);
Time_Elapsed += 1;
}
private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)
{
Ini_File.Write("Frm", "size", Width + "," + Height);
UnregisterHotKey(this.Handle, 0x9724);
}
#region Links
private void link_author_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("https://mikeserver.org/");
}
private void chk_Follow_Mouse_CheckedChanged(object sender, EventArgs e)
{
if (this.Follow_Mouse = chk_Follow_Mouse.Checked)
{
this.Desktop_Rectangle = Screen.PrimaryScreen.Bounds;
this.offsetY = Record_Rectangle.Height - (DesktopBounds).Height+8;
}
}
private void link_github_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("https://github.com/TheTarkus/WebMCam");
}
private void link_ffmpeg_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("https://ffmpeg.org/");
}
#endregion
}
}