Turn audio into a shareable video. forked from nypublicradio/audiogram

index.js 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. var d3 = require("d3"),
  2. $ = require("jquery"),
  3. preview = require("./preview.js"),
  4. video = require("./video.js"),
  5. audio = require("./audio.js"),
  6. timestamp,
  7. identifier;
  8. function addZero (digit) {
  9. if (digit.toString().length === 1) {
  10. return '0' + digit.toString();
  11. }
  12. else {
  13. return digit.toString();
  14. }
  15. }
  16. function timestamp () {
  17. var d = new Date();
  18. return addZero(d.getMonth() + 1)
  19. + addZero(d.getDate())
  20. + d.getFullYear().toString().slice(2,4) + '_'
  21. + addZero(d.getHours())
  22. + addZero(d.getMinutes())
  23. + addZero(d.getSeconds()) + '_';
  24. }
  25. d3.json("/settings/labels.json", function(err, labels){
  26. // Populate labels menu
  27. d3.select("#input-label")
  28. .on("change", updateLabel)
  29. .selectAll("option")
  30. .data(labels.podcasts)
  31. .enter()
  32. .append("option")
  33. .text(function(l){
  34. return l;
  35. });
  36. d3.select("#input-label").each(updateLabel);
  37. }); // end label ingestion
  38. d3.json("/settings/themes.json", function(err, themes){
  39. var errorMessage;
  40. // Themes are missing or invalid
  41. if (err || !d3.keys(themes).filter(function(d){ return d !== "default"; }).length) {
  42. if (err instanceof SyntaxError) {
  43. errorMessage = "Error in settings/themes.json:<br/><code>" + err.toString() + "</code>";
  44. } else if (err instanceof ProgressEvent) {
  45. errorMessage = "Error: no settings/themes.json.";
  46. } else if (err) {
  47. errorMessage = "Error: couldn't load settings/themes.json.";
  48. } else {
  49. errorMessage = "No themes found in settings/themes.json.";
  50. }
  51. d3.select("#loading-bars").remove();
  52. d3.select("#loading-message").html(errorMessage);
  53. if (err) {
  54. throw err;
  55. }
  56. return;
  57. }
  58. for (var key in themes) {
  59. themes[key] = $.extend({}, themes.default, themes[key]);
  60. }
  61. preloadImages(themes);
  62. });
  63. function submitted() {
  64. d3.event.preventDefault();
  65. var theme = preview.theme(),
  66. caption = preview.caption(),
  67. citation = preview.citation(),
  68. label = preview.label(),
  69. selection = preview.selection(),
  70. file = preview.file();
  71. // combine timestamp and caption for easy-to-scan filenames
  72. identifier = timestamp() + preview.caption().replace(/\s+/g, '_').replace(/\'|\"|\.|\?|\!/g, '').toLowerCase().slice(0, 20);
  73. if (!file) {
  74. d3.select("#row-audio").classed("error", true);
  75. return setClass("error", "No audio file selected.");
  76. }
  77. if (theme.maxDuration && selection.duration > theme.maxDuration) {
  78. return setClass("error", "Your Audiogram must be under " + theme.maxDuration + " seconds.");
  79. }
  80. if (!theme || !theme.width || !theme.height) {
  81. return setClass("error", "No valid theme detected.");
  82. }
  83. if (theme.labelText) {
  84. label = theme.labelText;
  85. }
  86. video.kill();
  87. audio.pause();
  88. var formData = new FormData();
  89. formData.append("audio", file);
  90. if (selection.start || selection.end) {
  91. formData.append("start", selection.start);
  92. formData.append("end", selection.end);
  93. }
  94. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  95. formData.append("caption", caption);
  96. formData.append("citation", citation);
  97. formData.append("label", label);
  98. formData.append("identifier", identifier);
  99. setClass("loading");
  100. d3.select("#loading-message").text("Uploading audio...");
  101. $.ajax({
  102. url: "/submit/",
  103. type: "POST",
  104. data: formData,
  105. contentType: false,
  106. dataType: "json",
  107. cache: false,
  108. processData: false,
  109. success: function(data){
  110. poll(data.id, 0);
  111. },
  112. error: error
  113. });
  114. }
  115. function poll(id) {
  116. setTimeout(function(){
  117. $.ajax({
  118. url: "/status/" + id + "/",
  119. error: error,
  120. dataType: "json",
  121. success: function(result){
  122. if (result && result.status && result.status === "ready" && result.url) {
  123. video.update(result.url, identifier);
  124. setClass("rendered");
  125. } else if (result.status === "error") {
  126. error(result.error);
  127. } else {
  128. d3.select("#loading-message").text(statusMessage(result));
  129. poll(id);
  130. }
  131. }
  132. });
  133. }, 2500);
  134. }
  135. function error(msg) {
  136. if (msg.responseText) {
  137. msg = msg.responseText;
  138. }
  139. if (typeof msg !== "string") {
  140. msg = JSON.stringify(msg);
  141. }
  142. if (!msg) {
  143. msg = "Unknown error";
  144. }
  145. d3.select("#loading-message").text("Loading...");
  146. setClass("error", msg);
  147. }
  148. // Once images are downloaded, set up listeners
  149. function initialize(err, themesWithImages) {
  150. // Populate themes menu
  151. d3.select("#input-theme")
  152. .on("change", updateTheme)
  153. .selectAll("option")
  154. .data(themesWithImages)
  155. .enter()
  156. .append("option")
  157. .text(function(d){
  158. return d.name;
  159. });
  160. // Get initial theme
  161. d3.select("#input-theme").each(updateTheme);
  162. // Get initial caption (e.g. back button)
  163. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  164. // Get initial citation (e.g. back button)
  165. d3.select("#input-citation").on("change keyup", updateCitation).each(updateCitation);
  166. // Space bar listener for audio play/pause
  167. d3.select(document).on("keypress", function(){
  168. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  169. audio.toggle();
  170. }
  171. });
  172. // Button listeners
  173. d3.selectAll("#play, #pause").on("click", function(){
  174. d3.event.preventDefault();
  175. audio.toggle();
  176. });
  177. d3.select("#restart").on("click", function(){
  178. d3.event.preventDefault();
  179. audio.restart();
  180. });
  181. // If there's an initial piece of audio (e.g. back button) load it
  182. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  183. d3.select("#return").on("click", function(){
  184. d3.event.preventDefault();
  185. video.kill();
  186. setClass(null);
  187. });
  188. d3.select("#submit").on("click", submitted);
  189. }
  190. function updateAudioFile() {
  191. d3.select("#row-audio").classed("error", false);
  192. audio.pause();
  193. video.kill();
  194. // Skip if empty
  195. if (!this.files || !this.files[0]) {
  196. d3.select("#minimap").classed("hidden", true);
  197. preview.file(null);
  198. setClass(null);
  199. return true;
  200. }
  201. d3.select("#loading-message").text("Analyzing...");
  202. setClass("loading");
  203. preview.loadAudio(this.files[0], function(err){
  204. if (err) {
  205. d3.select("#row-audio").classed("error", true);
  206. setClass("error", "Error decoding audio file");
  207. } else {
  208. setClass(null);
  209. }
  210. d3.selectAll("#minimap, #submit").classed("hidden", !!err);
  211. });
  212. }
  213. function updateCaption() {
  214. preview.caption(this.value);
  215. }
  216. function updateCitation() {
  217. preview.citation(this.value);
  218. }
  219. function updateLabel() {
  220. preview.label(this.value);
  221. }
  222. function updateTheme() {
  223. var theme_obj = d3.select(this.options[this.selectedIndex]).datum(),
  224. that = this;
  225. // Automatically set the label for themes that have them
  226. preview.theme(theme_obj);
  227. if (theme_obj.labelText) {
  228. preview.label(theme_obj.labelText);
  229. $('#input-label').children().each(function (i, c) {
  230. if (c.value === that.options[that.selectedIndex].value) {
  231. $(c).prop('selected', true);
  232. return false;
  233. }
  234. });
  235. $('#input-label').prop('disabled', true);
  236. }
  237. else {
  238. $('#input-label').prop('disabled', false);
  239. }
  240. }
  241. function preloadImages(themes) {
  242. // preload images
  243. var imageQueue = d3.queue();
  244. d3.entries(themes).forEach(function(theme){
  245. if (!theme.value.name) {
  246. theme.value.name = theme.key;
  247. }
  248. if (theme.key !== "default") {
  249. imageQueue.defer(getImage, theme.value);
  250. }
  251. });
  252. imageQueue.awaitAll(initialize);
  253. function getImage(theme, cb) {
  254. if (!theme.backgroundImage) {
  255. return cb(null, theme);
  256. }
  257. theme.backgroundImageFile = new Image();
  258. theme.backgroundImageFile.onload = function(){
  259. return cb(null, theme);
  260. };
  261. theme.backgroundImageFile.onerror = function(e){
  262. console.warn(e);
  263. return cb(null, theme);
  264. };
  265. theme.backgroundImageFile.src = "/settings/backgrounds/" + theme.backgroundImage;
  266. }
  267. }
  268. function setClass(cl, msg) {
  269. d3.select("body").attr("class", cl || null);
  270. d3.select("#error").text(msg || "");
  271. }
  272. function statusMessage(result) {
  273. switch (result.status) {
  274. case "queued":
  275. return "Waiting for other jobs to finish, #" + (result.position + 1) + " in queue";
  276. case "audio-download":
  277. return "Downloading audio for processing";
  278. case "trim":
  279. return "Trimming audio";
  280. case "probing":
  281. return "Probing audio file";
  282. case "waveform":
  283. return "Analyzing waveform";
  284. case "renderer":
  285. return "Initializing renderer";
  286. case "frames":
  287. var msg = "Generating frames";
  288. if (result.numFrames) {
  289. msg += ", " + Math.round(100 * (result.framesComplete || 0) / result.numFrames) + "% complete";
  290. }
  291. return msg;
  292. case "combine":
  293. return "Combining frames with audio";
  294. case "ready":
  295. return "Cleaning up";
  296. default:
  297. return JSON.stringify(result);
  298. }
  299. }