forked from illuspas/Node-Media-Server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
201 lines (168 loc) · 5.95 KB
/
app.js
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
const NodeMediaServer = require('./');
const MediaRoot = process.env.MEDIA_ROOT || './media'
const FfmpegPath = process.env.FFMPEG_PATH || '/usr/bin/ffmpeg'
const fs = require('fs');
const path = require('path');
const getStream = require('into-stream');
const { BlobServiceClient } = require("@azure/storage-blob");
const { DefaultAzureCredential } = require("@azure/identity");
const ONE_MEGABYTE = 1024 * 1024;
const uploadOptions = { bufferSize: 8 * ONE_MEGABYTE, maxBuffers: 20 };
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));
const account = process.env.AZURE_STORAGE_ACCOUNT_NAME || "";
const defaultAzureCredential = new DefaultAzureCredential();
const blobServiceClient = new BlobServiceClient(
`https://${account}.blob.core.windows.net`,
defaultAzureCredential
);
// Ensure required ENV vars are set
let requiredEnv = [
'AUTH_SECRET','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET'
];
let unsetEnv = requiredEnv.filter((env) => !(typeof process.env[env] !== 'undefined'));
if (unsetEnv.length > 0) {
throw new Error("Required ENV variables are not set: [" + unsetEnv.join(', ') + "]");
}
// Optimize encoding for H.264: https://trac.ffmpeg.org/wiki/Encode/H.264
const config = {
rtmp: {
port: 1935,
chunk_size: 60000,
gop_cache: true,
ping: 30,
ping_timeout: 60
},
http: {
port: 8000,
mediaroot: MediaRoot,
allow_origin: '*'
},
trans: {
ffmpeg: FfmpegPath,
tasks: [
{
app: 'live',
vc: "copy",
vcParam: ['-preset', 'slow', '-crf', '22'],
mp4: true,
mp4Flags: '[movflags=faststart]',
}
]
},
auth: {
play: true,
publish: true,
secret: process.env.AUTH_SECRET
}
};
let nms = new NodeMediaServer(config)
nms.run();
nms.on('preConnect', (id, args) => {
console.log('[NodeEvent on preConnect]', `id=${id} args=${JSON.stringify(args)}`);
// let session = nms.getSession(id);
// session.reject();
});
nms.on('postConnect', (id, args) => {
console.log('[NodeEvent on postConnect]', `id=${id} args=${JSON.stringify(args)}`);
});
nms.on('doneConnect', (id, args) => {
console.log('[NodeEvent on doneConnect]', `id=${id} args=${JSON.stringify(args)}`);
});
nms.on('prePublish', (id, StreamPath, args) => {
console.log('[NodeEvent on prePublish]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
// let session = nms.getSession(id);
// session.reject();
});
nms.on('postPublish', (id, StreamPath, args) => {
console.log('[NodeEvent on postPublish]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
nms.on('donePublish', (id, StreamPath, args) => {
console.log('[NodeEvent on donePublish]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
nms.on('doneTransSession', (StreamPath) => {
console.log('[NodeEvent on doneTransSession]', `StreamPath=${StreamPath}`);
setImmediate(() => {
sleep(2000).then(() => {
uploadToAzureBlobStorage(StreamPath);
});
})
});
nms.on('prePlay', (id, StreamPath, args) => {
console.log('[NodeEvent on prePlay]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
// let session = nms.getSession(id);
// session.reject();
});
nms.on('postPlay', (id, StreamPath, args) => {
console.log('[NodeEvent on postPlay]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
nms.on('donePlay', (id, StreamPath, args) => {
console.log('[NodeEvent on donePlay]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
function readdirAsync(path) {
return new Promise(function (resolve, reject) {
fs.readdir(path, function (error, result) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, function (err, data) {
if (err) {
reject(err);
}
resolve(data);
});
});
}
function removeFile(path) {
return new Promise((resolve, reject) => {
fs.unlink(path, function (err, data) {
if (err) {
reject(err);
}
resolve(data);
});
});
}
async function uploadToAzureBlobStorage(StreamPath){
console.log('[uploadToAzureBlobStorage]', `StreamPath=${StreamPath}`);
let ouPath = `${config.http.mediaroot}${StreamPath}`;
let files = await readdirAsync(ouPath);
for (const filename of files) {
if (filename.endsWith('.mp4')) {
let containerName = path.basename(StreamPath);
let containerClient = blobServiceClient.getContainerClient(containerName);
if(!(await containerClient.exists())) {
const createContainerResponse = await containerClient.create();
console.log(`[uploadToAzureBlobStorage] Create container ${containerName} successfully`, createContainerResponse.requestId);
}
let filepath = ouPath + '/' + filename;
data = await readFile(filepath);
console.log(`[uploadToAzureBlobStorage] mp4 buffer length:${data.length}`);
if(data.length > 0) {
let stream = getStream(data);
let blockBlobClient = containerClient.getBlockBlobClient(filename);
// if blob already exists no need to copy it again
if(!(await blockBlobClient.exists())) {
try {
console.log('[uploadToAzureBlobStorage] Uploading ' + filename + ' to Azure Blob Storage..');
const uploadBlobResponse = await blockBlobClient.uploadStream(stream, uploadOptions.bufferSize, 5, { blobHTTPHeaders: { blobContentType: "video/mp4" } });
console.log(`[uploadToAzureBlobStorage] Upload block blob ${filename} successfully`, uploadBlobResponse.requestId);
}
catch(err) {
console.log(err)
}
}
// Cleanup
console.log(`[uploadToAzureBlobStorage] Remove file ${filepath} from MediaRoot..`);
await removeFile(filepath);
}
}
}
console.log(`[uploadToAzureBlobStorage] Completed!`);
}